private async void EditPhotoExecute(StorageFile file) { 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); await file.CopyAndReplaceAsync(fileCache); var fileScale = fileCache; var basicProps = await fileScale.GetBasicPropertiesAsync(); var imageProps = await fileScale.Properties.GetImagePropertiesAsync(); var fileId = TLLong.Random(); var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name); if (upload != null) { var response = await ProtoService.EditChatPhotoAsync(_item.Id, new TLInputChatUploadedPhoto { File = upload.ToInputFile() }); if (response.IsSucceeded) { } } }
private async void EditPhotoExecute(StorageFile file) { _uploadingPhoto = true; 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); await file.CopyAndReplaceAsync(fileCache); var fileScale = fileCache; Preview = new BitmapImage(FileUtils.GetTempFileUri(fileName)); var fileId = TLLong.Random(); var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name); if (upload != null) { _photo = upload.ToInputFile(); _uploadingPhoto = false; _uploadingCallback?.Invoke(); } }
public void SetChannelPhoto() { EditChatActions.EditPhoto(photo => { 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), //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(photo, 0, photo.Length); } } Photo = new TLChatPhoto { PhotoSmall = new TLFileLocation { DCId = fileLocation.DCId, VolumeId = fileLocation.VolumeId, LocalId = fileLocation.LocalId, Secret = fileLocation.Secret }, PhotoBig = new TLFileLocation { DCId = fileLocation.DCId, VolumeId = fileLocation.VolumeId, LocalId = fileLocation.LocalId, Secret = fileLocation.Secret } }; NotifyOfPropertyChange(() => Photo); _uploadingPhoto = true; var fileId = TLLong.Random(); _uploadManager.UploadFile(fileId, new TLChannel(), photo); }); }
private void SendDocument(Photo p) { var chat = Chat as TLEncryptedChat; if (chat == null) { return; } var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt(p.Bytes.Length), KeyFingerprint = new TLInt(0), FileName = new TLString(Path.GetFileName(p.FileName)) }; var fileName = String.Format("{0}_{1}_{2}.jpg", fileLocation.Id, fileLocation.DCId, fileLocation.AccessHash); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { using (var fileStream = store.CreateFile(fileName)) { fileStream.Write(p.Bytes, 0, p.Bytes.Length); } } var keyIV = GenerateKeyIV(); int thumbHeight; int thumbWidth; var thumb = ImageUtils.CreateThumb(p.Bytes, Constants.DocumentPreviewMaxSize, Constants.DocumentPreviewQuality, out thumbHeight, out thumbWidth); var decryptedMediaDocument = GetDecryptedMediaDocument(p, chat, TLString.FromBigEndianData(thumb), new TLInt(thumbWidth), new TLInt(thumbHeight), new TLString("image/jpeg"), keyIV, fileLocation); var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaDocument, chat, true); InsertSendingMessage(decryptedTuple.Item1); RaiseScrollToBottom(); NotifyOfPropertyChange(() => DescriptionVisibility); BeginOnThreadPool(() => CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat, cachedMessage => SendDocumentInternal(p.Bytes, decryptedTuple.Item2))); }
private static async Task <TLPhotoSizeBase> GetFileThumbAsync(StorageFile file) { try { var thumb = await file.GetThumbnailAsync(ThumbnailMode.PicturesView, 190, ThumbnailOptions.ResizeThumbnail); 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((int)thumb.OriginalWidth), H = new TLInt((int)thumb.OriginalHeight), Size = new TLInt((int)thumb.Size), Type = new TLString(""), Location = thumbLocation, }; return(thumbSize); } catch (Exception ex) { Telegram.Api.Helpers.Execute.ShowDebugMessage("GetFileThumbAsync exception " + ex); } return(null); }
private async void EditPhotoExecute(StorageFile file) { 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); //var fileScale = await ImageHelper.ScaleJpegAsync(file, fileCache, 640, 0.77); await file.CopyAndReplaceAsync(fileCache); var fileScale = fileCache; var basicProps = await fileScale.GetBasicPropertiesAsync(); var imageProps = await fileScale.Properties.GetImagePropertiesAsync(); var fileId = TLLong.Random(); var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name); if (upload != null) { var response = await ProtoService.UploadProfilePhotoAsync(upload.ToInputFile() as TLInputFile); if (response.IsSucceeded) { var user = Self as TLUser; if (user == null) { return; } var userFull = CacheService.GetFullUser(user.Id); if (userFull == null) { return; } userFull.HasProfilePhoto = true; userFull.ProfilePhoto = response.Result.Photo; userFull.RaisePropertyChanged(() => userFull.ProfilePhoto); } } }
public async Task <TLMessage25> GetPhotoMessage(StorageFile file) { 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(); var resizedPhoto = await ResizeJpeg(stream, Constants.DefaultImageSize, file.DisplayName, fileName); 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) }; var photo = new TLPhoto33 { Id = new TLLong(0), AccessHash = new TLLong(0), Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), Sizes = new TLVector <TLPhotoSizeBase> { photoSize }, }; var media = new TLMessageMediaPhoto28 { Photo = photo, Caption = TLString.Empty, File = resizedPhoto.File }; return(GetMessage(TLString.Empty, media)); }
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))); }); }
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 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.SingleItem, 96, ThumbnailOptions.ResizeThumbnail)) { if (thumb != null) { 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(bitmapDecoder.BitmapPixelFormat, 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)); }
public static void NavigateToUser(TLUserBase userBase, string accessToken, PageKind pageKind = PageKind.Dialog) { if (userBase == null) { return; } Execute.BeginOnUIThread(() => { var navigationService = IoC.Get <INavigationService>(); if (pageKind == PageKind.Profile) { IoC.Get <IStateService>().CurrentContact = userBase; //IoC.Get<IStateService>().RemoveBackEntries = true; navigationService.Navigate(new Uri("/Views/Contacts/ContactView.xaml", UriKind.Relative)); } else if (pageKind == PageKind.Search) { var user = userBase as TLUser; if (user != null && user.IsBotGroupsBlocked) { MessageBox.Show(AppResources.AddBotToGroupsError, AppResources.Error, MessageBoxButton.OK); return; } IoC.Get <IStateService>().With = userBase; IoC.Get <IStateService>().RemoveBackEntries = true; IoC.Get <IStateService>().AccessToken = accessToken; IoC.Get <IStateService>().Bot = userBase; navigationService.Navigate(new Uri("/Views/Dialogs/ChooseDialogView.xaml?rndParam=" + TLInt.Random(), UriKind.Relative)); } else { IoC.Get <IStateService>().With = userBase; IoC.Get <IStateService>().RemoveBackEntries = true; IoC.Get <IStateService>().AccessToken = accessToken; IoC.Get <IStateService>().Bot = userBase; navigationService.Navigate(new Uri("/Views/Dialogs/DialogDetailsView.xaml?rndParam=" + TLInt.Random(), UriKind.Relative)); } // fix DialogDetailsView -> DialogDetailsView //IoC.Get<INavigationService>().UriFor<DialogDetailsViewModel>().Navigate(); }); }
private static void NavigateToShareTarget(string weblink) { if (string.IsNullOrEmpty(weblink)) { return; } Execute.BeginOnUIThread(() => { Execute.ShowDebugMessage(weblink); var navigationService = IoC.Get <INavigationService>(); navigationService.Navigate(new Uri("/Views/Dialogs/ChooseDialogView.xaml?rndParam=" + TLInt.Random(), UriKind.Relative)); }); }
public void SendAudio(AudioEventArgs args) { var chat = Chat as TLEncryptedChat; if (chat == null) { return; } if (string.IsNullOrEmpty(args.OggFileName)) { return; } var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var oggFileName = String.Format("audio{0}_{1}.mp3", id, accessHash); var wavFileName = Path.GetFileNameWithoutExtension(oggFileName) + ".wav"; long size = 0; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { storage.MoveFile(args.OggFileName, oggFileName); using (var file = storage.OpenFile(oggFileName, FileMode.Open, FileAccess.Read)) { size = file.Length; } var wavStream = Wav.GetWavAsMemoryStream(args.PcmStream, 16000, 1, 16); using (var file = new IsolatedStorageFileStream(wavFileName, FileMode.OpenOrCreate, storage)) { wavStream.Seek(0, SeekOrigin.Begin); wavStream.CopyTo(file); file.Flush(); } } var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt((int)size), KeyFingerprint = new TLInt(0), FileName = new TLString(Path.GetFileName(oggFileName)) }; var keyIV = GenerateKeyIV(); TLDecryptedMessageMediaAudio decryptedMediaAudio; var encryptedChat17 = chat as TLEncryptedChat17; if (encryptedChat17 != null) { decryptedMediaAudio = new TLDecryptedMessageMediaAudio17 { Duration = new TLInt((int)args.Duration), MimeType = new TLString("audio/ogg"), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, UserId = new TLInt(StateService.CurrentUserId), File = fileLocation, UploadingProgress = 0.001 }; } else { decryptedMediaAudio = new TLDecryptedMessageMediaAudio { Duration = new TLInt((int)args.Duration), //MimeType = new TLString("audio/ogg"), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, UserId = new TLInt(StateService.CurrentUserId), File = fileLocation, UploadingProgress = 0.001 }; } var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaAudio, chat, true); BeginOnUIThread(() => { Items.Insert(0, decryptedTuple.Item1); NotifyOfPropertyChange(() => DescriptionVisibility); }); BeginOnThreadPool(() => CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat, cachedMessage => SendAudioInternal(decryptedTuple.Item2))); }
public async Task <Telegram.Api.WindowsPhone.Tuple <TLDecryptedMessageBase, TLObject> > GetPhotoMessage(StorageFile file) { var chat = Chat as TLEncryptedChat; if (chat == null) { return(null); } if (file == null) { return(null); } var properties = await file.GetBasicPropertiesAsync(); var size = properties.Size; var thumb = await DialogDetailsViewModel.GetFileThumbAsync(file) as TLPhotoSize; var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var fileName = String.Format("{0}_{1}_{2}.jpg", id, dcId, accessHash); var stream = await file.OpenReadAsync(); var resizedPhoto = await DialogDetailsViewModel.ResizeJpeg(stream, Constants.DefaultImageSize, file.DisplayName, fileName); var keyIV = GenerateKeyIV(); var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt(resizedPhoto.Bytes.Length), KeyFingerprint = new TLInt(0), FileName = new TLString(Path.GetFileName(file.Name)) }; TLDecryptedMessageMediaPhoto decryptedMediaPhoto; var chat17 = chat as TLEncryptedChat17; if (chat17 != null && chat17.Layer.Value >= Constants.MinSecretChatWithCaptionsLayer) { decryptedMediaPhoto = new TLDecryptedMessageMediaPhoto45 { Thumb = thumb != null ? thumb.Bytes : TLString.Empty, ThumbW = thumb != null ? thumb.W : new TLInt(0), ThumbH = thumb != null ? thumb.H : new TLInt(0), Size = new TLInt(resizedPhoto.Bytes.Length), Key = keyIV.Item1, IV = keyIV.Item2, W = new TLInt(resizedPhoto.Width), H = new TLInt(resizedPhoto.Height), Caption = TLString.Empty, File = fileLocation, StorageFile = resizedPhoto.File, UploadingProgress = 0.001 }; } else { decryptedMediaPhoto = new TLDecryptedMessageMediaPhoto { Thumb = thumb != null ? thumb.Bytes : TLString.Empty, ThumbW = thumb != null ? thumb.W : new TLInt(0), ThumbH = thumb != null ? thumb.H : new TLInt(0), Size = new TLInt(resizedPhoto.Bytes.Length), Key = keyIV.Item1, IV = keyIV.Item2, W = new TLInt(resizedPhoto.Width), H = new TLInt(resizedPhoto.Height), File = fileLocation, StorageFile = resizedPhoto.File, UploadingProgress = 0.001 }; } var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaPhoto, chat, true); return(decryptedTuple); }
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 async void SendDocument(StorageFile file) { var chat = Chat as TLEncryptedChat; if (chat == null) { return; } if (file == null) { return; } var properties = await file.GetBasicPropertiesAsync(); var size = properties.Size; if (!DialogDetailsViewModel.CheckDocumentSize(size)) { MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK); return; } DialogDetailsViewModel.AddFileToFutureAccessList(file); var thumb = await DialogDetailsViewModel.GetFileThumbAsync(file) as TLPhotoSize; var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt((int)size), KeyFingerprint = new TLInt(0), FileName = new TLString(Path.GetFileName(file.Name)) }; var keyIV = GenerateKeyIV(); var decryptedMediaDocument = new TLDecryptedMessageMediaDocument { Thumb = thumb != null? thumb.Bytes : TLString.Empty, ThumbW = thumb != null? thumb.W : new TLInt(0), ThumbH = thumb != null? thumb.H : new TLInt(0), FileName = new TLString(Path.GetFileName(file.Name)), MimeType = new TLString(file.ContentType), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, File = fileLocation, StorageFile = file, UploadingProgress = 0.001 }; var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaDocument, chat, true); BeginOnUIThread(() => { Items.Insert(0, decryptedTuple.Item1); RaiseScrollToBottom(); NotifyOfPropertyChange(() => DescriptionVisibility); BeginOnThreadPool(() => CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat, cachedMessage => SendDocumentInternal(file, decryptedTuple.Item2))); }); }
public void SendAudio(AudioEventArgs args) { var chat = Chat as TLEncryptedChat; if (chat == null) { return; } if (string.IsNullOrEmpty(args.OggFileName)) { return; } var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var oggFileName = String.Format("audio{0}_{1}.mp3", id, accessHash); var wavFileName = Path.GetFileNameWithoutExtension(oggFileName) + ".wav"; long size = 0; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { storage.MoveFile(args.OggFileName, oggFileName); using (var file = storage.OpenFile(oggFileName, FileMode.Open, FileAccess.Read)) { size = file.Length; } var wavStream = Wav.GetWavAsMemoryStream(args.PcmStream, 16000, 1, 16); using (var file = new IsolatedStorageFileStream(wavFileName, FileMode.OpenOrCreate, storage)) { wavStream.Seek(0, SeekOrigin.Begin); wavStream.CopyTo(file); file.Flush(); } } var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt((int)size), KeyFingerprint = new TLInt(0), FileName = new TLString(Path.GetFileName(oggFileName)) }; var keyIV = GenerateKeyIV(); TLDecryptedMessageMediaBase decryptedMediaAudio; var encryptedChat17 = chat as TLEncryptedChat17; if (encryptedChat17 != null) { if (encryptedChat17.Layer.Value >= Constants.MinSecretChatWithAudioAsDocumentsLayer) { var opus = new TelegramClient_Opus.WindowsPhoneRuntimeComponent(); var bytes = opus.GetWaveform(ApplicationData.Current.LocalFolder.Path + "\\" + oggFileName); var resultSamples = bytes.Length; var bites2 = new BitArray(5 * bytes.Length); var count = 0; for (var i = 0; i < bytes.Length; i++) { var result = bytes[i]; var bit1 = result >> 0 & 0x1; var bit2 = result >> 1 & 0x1; var bit3 = result >> 2 & 0x1; var bit4 = result >> 3 & 0x1; var bit5 = result >> 4 & 0x1; bites2[count] = Convert.ToBoolean(bit1); bites2[count + 1] = Convert.ToBoolean(bit2); bites2[count + 2] = Convert.ToBoolean(bit3); bites2[count + 3] = Convert.ToBoolean(bit4); bites2[count + 4] = Convert.ToBoolean(bit5); count = count + 5; } var bytesCount = (resultSamples * 5) / 8 + (((resultSamples * 5) % 8) == 0 ? 0 : 1); var waveformBytes = new byte[bytesCount]; bites2.CopyTo(waveformBytes, 0); var waveform = waveformBytes != null?TLString.FromBigEndianData(waveformBytes) : TLString.Empty; var audioAttribute = new TLDocumentAttributeAudio46 { Flags = new TLInt((int)DocumentAttributeAudioFlags.Voice), Duration = new TLInt((int)args.Duration) }; if (waveformBytes != null) { audioAttribute.Waveform = waveform; } var attributes = new TLVector <TLDocumentAttributeBase> { audioAttribute }; decryptedMediaAudio = new TLDecryptedMessageMediaDocument45 { Thumb = TLString.Empty, ThumbW = new TLInt(0), ThumbH = new TLInt(0), MimeType = new TLString("audio/ogg"), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, Attributes = attributes, Caption = TLString.Empty, NotListened = true, File = fileLocation, UploadingProgress = 0.001 }; } else { decryptedMediaAudio = new TLDecryptedMessageMediaAudio17 { Duration = new TLInt((int)args.Duration), MimeType = new TLString("audio/ogg"), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, UserId = new TLInt(StateService.CurrentUserId), File = fileLocation, UploadingProgress = 0.001 }; } } else { decryptedMediaAudio = new TLDecryptedMessageMediaAudio { Duration = new TLInt((int)args.Duration), //MimeType = new TLString("audio/ogg"), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, UserId = new TLInt(StateService.CurrentUserId), File = fileLocation, UploadingProgress = 0.001 }; } var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaAudio, chat, true); //var message45 = decryptedTuple.Item1 as TLDecryptedMessage45; //if (message45 != null && message45.IsVoice()) //{ // message45.NotListened = true; //} BeginOnUIThread(() => { InsertSendingMessage(decryptedTuple.Item1); NotifyOfPropertyChange(() => DescriptionVisibility); }); BeginOnThreadPool(() => CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat, cachedMessage => SendAudioInternal(decryptedTuple.Item2))); }
private void SendVideo(string videoFileName, long duration) { var chat = Chat as TLEncryptedChat; if (chat == null) { return; } if (string.IsNullOrEmpty(videoFileName)) { return; } long size = 0; byte[] data; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var file = storage.OpenFile(videoFileName, FileMode.Open, FileAccess.Read)) { size = file.Length; data = new byte[size]; file.Read(data, 0, data.Length); } } byte[] thumb; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var file = storage.OpenFile(videoFileName + ".jpg", FileMode.Open, FileAccess.Read)) { thumb = new byte[file.Length]; file.Read(thumb, 0, thumb.Length); } } var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt((int)size), KeyFingerprint = new TLInt(0), FileName = new TLString(""), Duration = new TLInt((int)duration) }; var fileName = String.Format("{0}_{1}_{2}.mp4", fileLocation.Id, fileLocation.DCId, fileLocation.AccessHash); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { store.CopyFile(videoFileName, fileName, true); store.DeleteFile(videoFileName); } var keyIV = GenerateKeyIV(); int thumbHeight; int thumbWidth; thumb = ImageUtils.CreateThumb(thumb, Constants.VideoPreviewMaxSize, Constants.VideoPreviewQuality, out thumbHeight, out thumbWidth); TLDecryptedMessageMediaVideo decryptedMediaVideo; var encryptedChat17 = chat as TLEncryptedChat17; if (encryptedChat17 != null) { decryptedMediaVideo = new TLDecryptedMessageMediaVideo17 { Thumb = TLString.FromBigEndianData(thumb), ThumbW = new TLInt(thumbWidth), ThumbH = new TLInt(thumbHeight), Duration = new TLInt((int)duration), MimeType = new TLString("video/mp4"), W = new TLInt(640), H = new TLInt(480), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, File = fileLocation, UploadingProgress = 0.001 }; } else { decryptedMediaVideo = new TLDecryptedMessageMediaVideo { Thumb = TLString.FromBigEndianData(thumb), ThumbW = new TLInt(thumbWidth), ThumbH = new TLInt(thumbHeight), Duration = new TLInt((int)duration), //MimeType = new TLString("video/mp4"), W = new TLInt(640), H = new TLInt(480), Size = new TLInt((int)size), Key = keyIV.Item1, IV = keyIV.Item2, File = fileLocation, UploadingProgress = 0.001 }; } var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaVideo, chat, true); Items.Insert(0, decryptedTuple.Item1); RaiseScrollToBottom(); NotifyOfPropertyChange(() => DescriptionVisibility); BeginOnThreadPool(() => CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat, cachedMessage => SendVideoInternal(data, decryptedTuple.Item2))); }
public override Uri MapUri(Uri uri) { #if WP81 var op = ((App)Application.Current).ShareOperation; if (op != null) { ((App)Application.Current).ShareOperation = null; if (op.Data.Contains(StandardDataFormats.WebLink)) { IoC.Get <IStateService>().WebLink = op.Data.GetWebLinkAsync().GetResults(); IoC.Get <INavigationService>().Navigate(new Uri("/Views/Dialogs/ChooseDialogView.xaml?rndParam=" + TLInt.Random(), UriKind.Relative)); } } #endif var tempUri = HttpUtility.UrlDecode(uri.ToString()); if (tempUri.Contains("msg_id") || tempUri.Contains("SecondaryTile")) { var uriParams = ParseQueryString(tempUri); if (tempUri.Contains("from_id")) { IoC.Get <IStateService>().RemoveBackEntries = true; IoC.Get <IStateService>().UserId = uriParams["from_id"]; } else if (tempUri.Contains("encryptedchat_id") && tempUri.Contains("encrypteduser_id")) { IoC.Get <IStateService>().ChatId = uriParams["encryptedchat_id"]; IoC.Get <IStateService>().UserId = uriParams["encrypteduser_id"]; return(new Uri("/Views/Dialogs/SecretDialogDetailsView.xaml", UriKind.Relative)); } else if (tempUri.Contains("chat_id")) { IoC.Get <IStateService>().RemoveBackEntries = true; IoC.Get <IStateService>().ChatId = uriParams["chat_id"]; } else if (tempUri.Contains("broadcast_id")) { IoC.Get <IStateService>().RemoveBackEntries = true; IoC.Get <IStateService>().BroadcastId = uriParams["broadcast_id"]; } else { return(uri); } return(new Uri("/Views/Dialogs/DialogDetailsView.xaml", UriKind.Relative)); } if (tempUri.StartsWith("/Protocol?encodedLaunchUri")) { return(new Uri("/Views/ShellView.xaml", UriKind.Relative)); } if (tempUri.StartsWith("/PeopleExtension?action")) { return(new Uri("/Views/ShellView.xaml", UriKind.Relative)); } if (tempUri.Contains("Action=ENCRYPTED_MESSAGE")) { IoC.Get <IStateService>().ClearNavigationStack = true; return(uri); } // check ShellView.xaml.cs OnNavigatedTo //if (tempUri.Contains("FileId")) //{ //var uriParams = ParseQueryString(tempUri); //IoC.Get<IStateService>().FileId = uriParams["FileId"]; //IoC.Get<IStateService>().ClearNavigationStack = true; //return new Uri("/Views/ShellView.xaml", UriKind.Relative); //} // Otherwise perform normal launch. return(uri); }
internal async void OutgoingCall(int userId, long accessHash) { await UpdateStateAsync(TLPhoneCallState.Requesting); var coordinator = VoipCallCoordinator.GetDefault(); var call = coordinator.RequestNewOutgoingCall("Unigram", _user.FullName, "Unigram", VoipPhoneCallMedia.Audio); _outgoing = true; _systemCall = call; _systemCall.AnswerRequested += OnAnswerRequested; _systemCall.RejectRequested += OnRejectRequested; var reqConfig = new TLMessagesGetDHConfig { Version = 0, RandomLength = 256 }; var config = await SendRequestAsync <TLMessagesDHConfig>("messages.getDhConfig", reqConfig); if (config.IsSucceeded) { var dh = config.Result; if (!TLUtils.CheckPrime(dh.P, dh.G)) { return; } var salt = new byte[256]; var secureRandom = new SecureRandom(); secureRandom.NextBytes(salt); secretP = dh.P; a_or_b = salt; g_a = MTProtoService.GetGB(salt, dh.G, dh.P); var request = new TLPhoneRequestCall { UserId = new TLInputUser { UserId = userId, AccessHash = accessHash }, RandomId = TLInt.Random(), GAHash = Utils.ComputeSHA256(g_a), Protocol = new TLPhoneCallProtocol { IsUdpP2p = true, IsUdpReflector = true, MinLayer = Telegram.Api.Constants.CallsMinLayer, MaxLayer = Telegram.Api.Constants.CallsMaxLayer, } }; var response = await SendRequestAsync <TLPhonePhoneCall>("phone.requestCall", request); if (response.IsSucceeded) { var update = new TLUpdatePhoneCall { PhoneCall = response.Result.PhoneCall }; Handle(update); await UpdateStateAsync(TLPhoneCallState.Waiting); } else { Debugger.Break(); } } }
private async Task SendFileAsync(StorageFile file, string caption) { if (_peer == null) { return; } var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var fileName = string.Format("{0}_{1}_{2}.dat", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var fileCache = await FileUtils.CreateTempFileAsync(fileName); await file.CopyAndReplaceAsync(fileCache); var basicProps = await fileCache.GetBasicPropertiesAsync(); var thumbnail = await FileUtils.GetFileThumbnailAsync(file); if (thumbnail as TLPhotoSize != null) { await SendThumbnailFileAsync(file, fileLocation, fileName, basicProps, thumbnail as TLPhotoSize, fileCache, caption); } else { 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, 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, fileName, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction { Progress = progress })); if (upload != null) { var inputMedia = new TLInputMediaUploadedDocument { File = upload.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); // } // } // } //} } }); } }
public static void NavigateToChat(TLChatBase chatBase) { if (chatBase == null) { return; } Execute.BeginOnUIThread(() => { IoC.Get <IStateService>().With = chatBase; IoC.Get <IStateService>().RemoveBackEntries = true; IoC.Get <INavigationService>().Navigate(new Uri("/Views/Dialogs/DialogDetailsView.xaml?rndParam=" + TLInt.Random(), UriKind.Relative)); }); }
public async Task SendVideoAsync(StorageFile file, string caption, bool round, VideoTransformEffectDefinition transform = null, MediaEncodingProfile profile = null) { if (_peer == null) { return; } var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var fileName = string.Format("{0}_{1}_{2}.mp4", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var fileCache = await FileUtils.CreateTempFileAsync(fileName); await file.CopyAndReplaceAsync(fileCache); var basicProps = await fileCache.GetBasicPropertiesAsync(); var videoProps = await fileCache.Properties.GetVideoPropertiesAsync(); var thumbnailBase = await FileUtils.GetFileThumbnailAsync(file); var thumbnail = thumbnailBase as TLPhotoSize; if (thumbnail == 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 videoWidth = (int)videoProps.Width; var videoHeight = (int)videoProps.Height; if (profile != null) { videoWidth = (int)profile.Video.Width; videoHeight = (int)profile.Video.Height; } 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 }, new TLDocumentAttributeVideo { Duration = (int)videoProps.Duration.TotalSeconds, W = videoWidth, H = videoHeight, IsRoundMessage = round } } }; 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) => { if (transform != null && profile != null) { await fileCache.RenameAsync(fileName + ".temp.mp4"); var fileResult = await FileUtils.CreateTempFileAsync(fileName); var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties); var prepare = await transcoder.PrepareFileTranscodeAsync(fileCache, fileResult, profile); await prepare.TranscodeAsync().AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction { Progress = progress }, 0, 200.0)); //await fileCache.DeleteAsync(); fileCache = fileResult; thumbnailBase = await FileUtils.GetFileThumbnailAsync(fileCache); thumbnail = thumbnailBase as TLPhotoSize; desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret); document.Thumb = thumbnail; } var fileId = TLLong.Random(); var upload = await _uploadVideoManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction { Progress = progress }, 0.5, 2.0)); 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); // } // } // } //} } }); }
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); }
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 override void Create() { if (string.IsNullOrEmpty(Title)) { MessageBox.Show(AppResources.PleaseEnterGroupSubject, AppResources.Error, MessageBoxButton.OK); return; } var participants = new TLVector <TLInputUserBase>(); foreach (var item in SelectedUsers) { participants.Add(item.ToInputUser()); } if (participants.Count == 0) { MessageBox.Show(AppResources.PleaseChooseAtLeastOneParticipant, AppResources.Error, MessageBoxButton.OK); return; } var broadcastChat = new TLBroadcastChat { Id = TLInt.Random(), Photo = new TLChatPhotoEmpty(), Title = new TLString(Title), ParticipantIds = new TLVector <TLInt> { Items = SelectedUsers.Select(x => x.Id).ToList() } }; CacheService.SyncBroadcast(broadcastChat, result => { var broadcastPeer = new TLPeerBroadcast { Id = broadcastChat.Id }; var serviceMessage = new TLMessageService17 { FromId = new TLInt(StateService.CurrentUserId), ToId = broadcastPeer, Status = MessageStatus.Confirmed, Out = new TLBool { Value = true }, Date = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now), //IsAnimated = true, RandomId = TLLong.Random(), Action = new TLMessageActionChatCreate { Title = broadcastChat.Title, Users = broadcastChat.ParticipantIds } }; serviceMessage.SetUnread(new TLBool(false)); CacheService.SyncMessage(serviceMessage, message => { StateService.With = broadcastChat; StateService.RemoveBackEntry = true; NavigationService.UriFor <DialogDetailsViewModel>().Navigate(); }); }); }
private async Task SendGifAsync(StorageFile file, string caption) { var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var fileName = string.Format("{0}_{1}_{2}.gif", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var fileCache = await FileUtils.CreateTempFileAsync(fileName); await file.CopyAndReplaceAsync(fileCache); var basicProps = await fileCache.GetBasicPropertiesAsync(); var imageProps = await fileCache.Properties.GetImagePropertiesAsync(); var thumbnailBase = await FileUtils.GetFileThumbnailAsync(file); var thumbnail = thumbnailBase as TLPhotoSize; 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 TLDocumentAttributeAnimated(), new TLDocumentAttributeFilename { FileName = file.Name }, new TLDocumentAttributeImageSize { W = (int)imageProps.Width, H = (int)imageProps.Height }, new TLDocumentAttributeVideo { W = (int)imageProps.Width, H = (int)imageProps.Height, } } }; var media = new TLMessageMediaDocument { Caption = caption, Document = document }; 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, fileName, false).AsTask(media.Document.Upload()); 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); } } }); }
public async void SendDocument(StorageFile file) { var chat = Chat as TLEncryptedChat; if (chat == null) { return; } if (file == null) { return; } var properties = await file.GetBasicPropertiesAsync(); var size = properties.Size; if (!DialogDetailsViewModel.CheckDocumentSize(size)) { MessageBox.Show(string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)), AppResources.Error, MessageBoxButton.OK); return; } DialogDetailsViewModel.AddFileToFutureAccessList(file); var thumb = await DialogDetailsViewModel.GetFileThumbAsync(file) as TLPhotoSize; var dcId = TLInt.Random(); var id = TLLong.Random(); var accessHash = TLLong.Random(); var fileLocation = new TLEncryptedFile { Id = id, AccessHash = accessHash, DCId = dcId, Size = new TLInt((int)size), KeyFingerprint = new TLInt(0), FileName = new TLString(Path.GetFileName(file.Name)) }; var keyIV = GenerateKeyIV(); var decryptedMediaDocumentBase = GetDecryptedMediaDocument(file, chat, thumb, size, keyIV, fileLocation); var decryptedMediaDocument45 = decryptedMediaDocumentBase as TLDecryptedMessageMediaDocument45; if (decryptedMediaDocument45 != null) { if (string.Equals(decryptedMediaDocument45.FileExt, "webp", StringComparison.OrdinalIgnoreCase) && decryptedMediaDocument45.DocumentSize < Telegram.Api.Constants.StickerMaxSize) { decryptedMediaDocument45.MimeType = new TLString("image/webp"); decryptedMediaDocument45.Attributes.Add(new TLDocumentAttributeSticker29 { Alt = TLString.Empty, Stickerset = new TLInputStickerSetEmpty() }); var fileName = decryptedMediaDocument45.GetFileName(); await file.CopyAsync(ApplicationData.Current.LocalFolder, fileName, NameCollisionOption.ReplaceExisting); } else if (string.Equals(decryptedMediaDocument45.FileExt, "mp3", StringComparison.OrdinalIgnoreCase)) { var musicProperties = await file.Properties.GetMusicPropertiesAsync(); if (musicProperties != null) { var documentAttributeAudio = new TLDocumentAttributeAudio32 { Duration = new TLInt(0), Title = TLString.Empty, Performer = TLString.Empty }; documentAttributeAudio.Duration = new TLInt((int)musicProperties.Duration.TotalSeconds); if (!string.IsNullOrEmpty(musicProperties.Title)) { documentAttributeAudio.Title = new TLString(musicProperties.Title); } if (!string.IsNullOrEmpty(musicProperties.Artist)) { documentAttributeAudio.Performer = new TLString(musicProperties.Artist); } decryptedMediaDocument45.Attributes.Add(documentAttributeAudio); } } } var decryptedTuple = GetDecryptedMessageAndObject(TLString.Empty, decryptedMediaDocumentBase, chat, true); BeginOnUIThread(() => { InsertSendingMessage(decryptedTuple.Item1); RaiseScrollToBottom(); NotifyOfPropertyChange(() => DescriptionVisibility); BeginOnThreadPool(() => CacheService.SyncDecryptedMessage(decryptedTuple.Item1, chat, cachedMessage => SendDocumentInternal(file, decryptedTuple.Item2))); }); }
public async Task SendAudioAsync(StorageFile file, int duration, bool voice, string title, string performer, string caption) { var fileLocation = new TLFileLocation { VolumeId = TLLong.Random(), LocalId = TLInt.Random(), Secret = TLLong.Random(), DCId = 0 }; var fileName = string.Format("{0}_{1}_{2}.ogg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret); var fileCache = await FileUtils.CreateTempFileAsync(fileName); await file.CopyAndReplaceAsync(fileCache); var basicProps = await fileCache.GetBasicPropertiesAsync(); var imageProps = await fileCache.Properties.GetImagePropertiesAsync(); var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now); var media = new TLMessageMediaDocument { Caption = caption, Document = new TLDocument { Id = TLLong.Random(), AccessHash = TLLong.Random(), Date = date, MimeType = "audio/ogg", Size = (int)basicProps.Size, Thumb = new TLPhotoSizeEmpty { Type = string.Empty }, Version = 0, DCId = 0, Attributes = new TLVector<TLDocumentAttributeBase> { new TLDocumentAttributeAudio { IsVoice = voice, Duration = duration, Title = title, Performer = performer } } } }; 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 _uploadAudioManager.UploadFileAsync(fileId, fileName, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadAudioAction { Progress = progress })); if (upload != null) { var inputMedia = new TLInputMediaUploadedDocument { File = upload.ToInputFile(), MimeType = "audio/ogg", Caption = media.Caption, Attributes = new TLVector<TLDocumentAttributeBase> { new TLDocumentAttributeAudio { IsVoice = voice, Duration = duration, Title = title, Performer = performer } } }; var result = await ProtoService.SendMediaAsync(Peer, inputMedia, message); } }); }