Esempio n. 1
0
        public void EditChannelAboutAsync(TLChannel channel, TLString about, System.Action callback)
        {
            if (TLString.Equals(about, channel.About, StringComparison.Ordinal))
            {
                callback.SafeInvoke();
                return;
            }

            IsWorking = true;
            MTProtoService.EditAboutAsync(channel, about,
                                          statedMessage => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;

                channel.About = about;
                CacheService.Commit();

                callback.SafeInvoke();
            }),
                                          error => Execute.BeginOnUIThread(() =>
            {
                Execute.ShowDebugMessage("channels.editAbout error " + error);

                IsWorking = false;

                if (error.CodeEquals(ErrorCode.BAD_REQUEST) &&
                    error.TypeEquals(ErrorType.CHAT_ABOUT_NOT_MODIFIED))
                {
                }
                callback.SafeInvoke();
            }));
        }
Esempio n. 2
0
        public void Open()
        {
            var stickerSet = StickerSet as TLStickerSet32;

            if (stickerSet == null)
            {
                return;
            }

            TelegramViewBase.NavigateToStickers(MTProtoService, StateService, new TLInputStickerSetShortName {
                ShortName = stickerSet.ShortName
            },
                                                () =>
            {
                Items.Insert(0, stickerSet);
            },
                                                () =>
            {
                for (var index = 0; index < Items.Count; index++)
                {
                    var item = Items[index];
                    if (TLString.Equals(stickerSet.ShortName, item.ShortName, StringComparison.Ordinal))
                    {
                        Items.RemoveAt(index);
                        break;
                    }
                }
            });
        }
Esempio n. 3
0
        private void AddItemsChunk(int chunkSize, List <TLStickerSetBase> delayedItems, System.Action callback)
        {
            BeginOnUIThread(() =>
            {
                for (var i = 0; i < delayedItems.Count && i < chunkSize; i++)
                {
                    var stickerSet = delayedItems[i] as TLStickerSet;
                    if (stickerSet != null)
                    {
                        stickerSet.IsSelected = StickerSet != null && TLString.Equals(StickerSet.ShortName, stickerSet.ShortName, StringComparison.OrdinalIgnoreCase);
                    }

                    Items.Add(delayedItems[0]);
                    delayedItems.RemoveAt(0);
                }

                if (delayedItems.Count > 0)
                {
                    AddItemsChunk(25, delayedItems, callback);
                }
                else
                {
                    callback.SafeInvoke();
                }
            });
        }
Esempio n. 4
0
        private static string GetWavFileName(object dataContext)
        {
            var attachment = dataContext as TLMessageMediaAudio;

            if (attachment != null)
            {
                var audio = attachment.Audio as TLAudio;
                if (audio != null)
                {
                    if (TLString.Equals(audio.MimeType, new TLString("audio/mpeg"), StringComparison.OrdinalIgnoreCase))
                    {
                        Execute.BeginOnThreadPool(async() =>
                        {
                            var audioFileName = audio.GetFileName();
#if WP81
                            try
                            {
                                var documentFile = await ApplicationData.Current.LocalFolder.GetFileAsync(audioFileName);
                                Launcher.LaunchFileAsync(documentFile);
                            }
                            catch (Exception ex)
                            {
                                Execute.ShowDebugMessage("LocalFolder.GetFileAsync docLocal exception \n" + ex);
                            }
#elif WP8
                            var file = await ApplicationData.Current.LocalFolder.GetFileAsync(audioFileName);
                            Launcher.LaunchFileAsync(file);
                            return;
#endif
                        });
                    }
                    return(string.Format("audio{0}_{1}.wav", audio.Id, audio.AccessHash));
                }
            }

            var decryptedMediaAudio = dataContext as TLDecryptedMessageMediaAudio;
            if (decryptedMediaAudio != null)
            {
                var file = decryptedMediaAudio.File as TLEncryptedFile;
                if (file != null)
                {
                    return(string.Format("audio{0}_{1}.wav", file.Id, file.AccessHash));
                }
            }

            return(null);
        }
Esempio n. 5
0
        public void EditChannelTitleAsync(TLChannel channel, TLString title, System.Action callback)
        {
            if (TLString.Equals(title, channel.Title, StringComparison.Ordinal))
            {
                callback.SafeInvoke();
                return;
            }

            IsWorking = true;
            MTProtoService.EditTitleAsync(channel, title,
                                          result => Execute.BeginOnUIThread(() =>
            {
                IsWorking = false;

                var updates = result as TLUpdates;
                if (updates != null)
                {
                    var updateNewMessage = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage;
                    if (updateNewMessage != null)
                    {
                        EventAggregator.Publish(updateNewMessage.Message);
                    }
                }

                callback.SafeInvoke();
            }),
                                          error => Execute.BeginOnUIThread(() =>
            {
                Execute.ShowDebugMessage("channels.editTitle error " + error);

                IsWorking = false;

                if (error.CodeEquals(ErrorCode.BAD_REQUEST) &&
                    error.TypeEquals(ErrorType.CHAT_NOT_MODIFIED))
                {
                }
                callback.SafeInvoke();
            }));
        }
Esempio n. 6
0
 private void Set(TLStickerSetBase set, bool updateText)
 {
     StickerSet     = set;
     set.IsSelected = true;
     set.NotifyOfPropertyChange(() => set.IsSelected);
     foreach (var item in Items)
     {
         if (TLString.Equals(StickerSet.ShortName, item.ShortName, StringComparison.OrdinalIgnoreCase))
         {
             item.IsSelected = true;
             item.NotifyOfPropertyChange(() => item.IsSelected);
         }
         else
         {
             item.IsSelected = false;
             item.NotifyOfPropertyChange(() => item.IsSelected);
         }
     }
     if (updateText)
     {
         Text = set.ShortName.ToString();
     }
 }
        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;
                        NavigationService.UriFor <ProfilePhotoViewerViewModel>().Navigate();
                    }
                }

                return;
            }

            var message = messageBase as TLMessage;

            if (message == null)
            {
                return;
            }

            var mediaPhoto = message.Media as TLMessageMediaPhoto;

            if (mediaPhoto != null)
            {
                StateService.CurrentPhotoMessage  = message;
                StateService.CurrentMediaMessages =
                    Items
                    .OfType <TLMessage>()
                    .Where(x => x.Media is TLMessageMediaPhoto || x.Media is TLMessageMediaVideo)
                    .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.Uri = new Uri(webPage.Url.ToString(), UriKind.Absolute);
                                webBrowserTask.Show();
                            }

                            return;
                        }
                    }
                }
            }

            var mediaGeo = message.Media as TLMessageMediaGeo;

            if (mediaGeo != null)
            {
                StateService.MediaMessage = message;
                NavigationService.UriFor <MapViewModel>().Navigate();
                return;
            }

            var mediaContact = message.Media as TLMessageMediaContact;

            if (mediaContact != null)
            {
                var phoneNumber = mediaContact.PhoneNumber.ToString();

                if (mediaContact.UserId.Value == 0)
                {
                    if (!string.IsNullOrEmpty(phoneNumber))
                    {
                        if (!phoneNumber.StartsWith("+"))
                        {
                            phoneNumber = "+" + phoneNumber;
                        }

                        var task = new PhoneCallTask();
                        task.DisplayName = mediaContact.FullName;
                        task.PhoneNumber = phoneNumber;
                        task.Show();
                    }
                }
                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);
                }

                return;
            }

            var mediaDocument = message.Media as TLMessageMediaDocument;
            if (mediaDocument != null)
            {
                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");
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var isBlurEnabled = parameter == null || !string.Equals(parameter.ToString(), "noblur", StringComparison.OrdinalIgnoreCase);

            var options = BitmapCreateOptions.DelayCreation | BitmapCreateOptions.BackgroundCreation;

            var decryptedMediaPhoto = value as TLDecryptedMessageThumbMediaBase;

            if (decryptedMediaPhoto != null)
            {
                var buffer = decryptedMediaPhoto.Thumb.Data;

                if (buffer.Length > 0 &&
                    decryptedMediaPhoto.ThumbW.Value > 0 &&
                    decryptedMediaPhoto.ThumbH.Value > 0)
                {
                    if (!isBlurEnabled)
                    {
                        return(ImageUtils.CreateImage(buffer, options));
                    }
                    else
                    {
                        try
                        {
                            var memoryStream = new MemoryStream(buffer);
                            var bitmap       = PictureDecoder.DecodeJpeg(memoryStream);

                            BlurBitmap(bitmap, Secret);

                            var blurredStream = new MemoryStream();
                            bitmap.SaveJpeg(blurredStream, decryptedMediaPhoto.ThumbW.Value, decryptedMediaPhoto.ThumbH.Value, 0, 100);

                            return(ImageUtils.CreateImage(blurredStream, options));
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }

                return(null);
            }

            var mediaDocument = value as TLMessageMediaDocument;

            if (mediaDocument != null)
            {
                var document = mediaDocument.Document as TLDocument;
                if (document != null)
                {
                    var size = document.Thumb as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return(size.TempUrl);
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                         location.VolumeId,
                                                         location.LocalId,
                                                         location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return(ImageUtils.CreateImage(stream, options));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get <IFileManager>();
                                        fileManager.DownloadFile(location, document, size.Size,
                                                                 item =>
                                        {
                                            mediaDocument.NotifyOfPropertyChange(() => mediaDocument.ThumbSelf);
                                        });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetDocumentPreview(document.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                BlurBitmap(bitmap, Secret);

                                                var blurredStream = new MemoryStream();
                                                bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                return(bitmap);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                }

                                var fileManager = IoC.Get <IFileManager>();
                                fileManager.DownloadFile(location, document, size.Size,
                                                         item =>
                                {
                                    Execute.BeginOnUIThread(() =>
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName))
                                            {
                                                try
                                                {
                                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                    {
                                                        var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                        BlurBitmap(bitmap, Secret);

                                                        var blurredStream = new MemoryStream();
                                                        bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                        var previewfileName = string.Format("preview_document{0}.jpg", document.Id);
                                                        SaveFile(previewfileName, blurredStream);

                                                        mediaDocument.NotifyOfPropertyChange(() => mediaDocument.ThumbSelf);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }

                    var cachedSize = document.Thumb as TLPhotoCachedSize;
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return(cachedSize.TempUrl);
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return(ImageUtils.CreateImage(buffer, options));
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetDocumentPreview(document.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview_document{0}.jpg", document.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return(ImageUtils.CreateImage(blurredStream, options));
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        return(null);
                    }

                    return(null);
                }
            }

            var mediaPhoto = value as TLMessageMediaPhoto;

            if (mediaPhoto != null)
            {
                var photo = mediaPhoto.Photo as TLPhoto;
                if (photo != null)
                {
                    var size = photo.Sizes.FirstOrDefault(x => TLString.Equals(x.Type, new TLString("s"), StringComparison.OrdinalIgnoreCase)) as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return(size.TempUrl);
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                         location.VolumeId,
                                                         location.LocalId,
                                                         location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return(ImageUtils.CreateImage(stream, options));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get <IFileManager>();
                                        fileManager.DownloadFile(location, photo, size.Size,
                                                                 item =>
                                        {
                                            mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);
                                        });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                BlurBitmap(bitmap, Secret);

                                                var blurredStream = new MemoryStream();
                                                bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                return(bitmap);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                }

                                if (location.DCId.Value == 0)
                                {
                                    return(null);
                                }

                                var fileManager = IoC.Get <IFileManager>();
                                fileManager.DownloadFile(location, photo, size.Size,
                                                         item =>
                                {
                                    Execute.BeginOnUIThread(() =>
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName))
                                            {
                                                try
                                                {
                                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                    {
                                                        var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                        BlurBitmap(bitmap, Secret);

                                                        var blurredStream = new MemoryStream();
                                                        bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                        var previewfileName = string.Format("preview{0}.jpg", photo.Id);
                                                        SaveFile(previewfileName, blurredStream);

                                                        mediaPhoto.NotifyOfPropertyChange(() => mediaPhoto.ThumbSelf);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }

                    var cachedSize = (TLPhotoCachedSize)photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return(cachedSize.TempUrl);
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return(ImageUtils.CreateImage(buffer, options));
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview{0}.jpg", photo.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return(ImageUtils.CreateImage(blurredStream, options));
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        return(null);
                    }

                    return(null);
                }
            }

            var mediaGame = value as TLMessageMediaGame;

            if (mediaGame != null)
            {
                var photo = mediaGame.Photo as TLPhoto;
                if (photo != null)
                {
                    var size = photo.Sizes.FirstOrDefault(x => TLString.Equals(x.Type, new TLString("s"), StringComparison.OrdinalIgnoreCase)) as TLPhotoSize;
                    if (size != null)
                    {
                        if (!string.IsNullOrEmpty(size.TempUrl))
                        {
                            return(size.TempUrl);
                        }

                        var location = size.Location as TLFileLocation;
                        if (location != null)
                        {
                            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                                         location.VolumeId,
                                                         location.LocalId,
                                                         location.Secret);

                            if (!isBlurEnabled)
                            {
                                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                {
                                    if (store.FileExists(fileName))
                                    {
                                        try
                                        {
                                            using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                return(ImageUtils.CreateImage(stream, options));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        var fileManager = IoC.Get <IFileManager>();
                                        fileManager.DownloadFile(location, photo, size.Size,
                                                                 item =>
                                        {
                                            mediaGame.NotifyOfPropertyChange(() => mediaGame.ThumbSelf);
                                        });
                                    }
                                }
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                var fileManager = IoC.Get <IFileManager>();
                                fileManager.DownloadFile(location, photo, size.Size,
                                                         item =>
                                {
                                    Execute.BeginOnUIThread(() =>
                                    {
                                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            if (store.FileExists(fileName))
                                            {
                                                try
                                                {
                                                    using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                                                    {
                                                        var bitmap = PictureDecoder.DecodeJpeg(stream);

                                                        BlurBitmap(bitmap, Secret);

                                                        var blurredStream = new MemoryStream();
                                                        bitmap.SaveJpeg(blurredStream, size.W.Value, size.H.Value, 0, 100);

                                                        var previewfileName = string.Format("preview{0}.jpg", photo.Id);
                                                        SaveFile(previewfileName, blurredStream);

                                                        mediaGame.NotifyOfPropertyChange(() => mediaGame.ThumbSelf);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                }
                                            }
                                        }
                                    });
                                });
                            }
                        }
                    }

                    var cachedSize = (TLPhotoCachedSize)photo.Sizes.FirstOrDefault(x => x is TLPhotoCachedSize);
                    if (cachedSize != null)
                    {
                        if (!string.IsNullOrEmpty(cachedSize.TempUrl))
                        {
                            return(cachedSize.TempUrl);
                        }

                        var buffer = cachedSize.Bytes.Data;

                        if (buffer != null && buffer.Length > 0)
                        {
                            if (!isBlurEnabled)
                            {
                                return(ImageUtils.CreateImage(buffer, options));
                            }
                            else
                            {
                                BitmapImage preview;
                                if (TryGetPhotoPreview(photo.Id, out preview, options))
                                {
                                    return(preview);
                                }

                                try
                                {
                                    var bitmap = PictureDecoder.DecodeJpeg(new MemoryStream(buffer));

                                    BlurBitmap(bitmap, Secret);

                                    var blurredStream = new MemoryStream();
                                    bitmap.SaveJpeg(blurredStream, cachedSize.W.Value, cachedSize.H.Value, 0, 100);

                                    var fileName = string.Format("preview{0}.jpg", photo.Id);

                                    Telegram.Api.Helpers.Execute.BeginOnThreadPool(() => SaveFile(fileName, blurredStream));

                                    return(ImageUtils.CreateImage(blurredStream));
                                }
                                catch (Exception ex)
                                {
                                }
                            }
                        }

                        return(null);
                    }

                    return(null);
                }
            }

            return(null);
        }
        public void ProcessRepliesAndAudio(IList <TLMessageBase> messages)
        {
            for (var i = 0; i < messages.Count; i++)
            {
                var message = messages[i] as TLMessage;
                if (message != null)
                {
                    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);
                                });
                                continue;
                            }
                        }

                        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);
                            });
                            continue;
                        }
                    }
                }
            }

            var replyToMsgIds = new TLVector <TLInt>();
            var replyToMsgs   = new List <TLMessage25>();

            for (var i = 0; i < messages.Count; i++)
            {
                var message25 = messages[i] as TLMessage25;
                if (message25 != null)
                {
                    if (message25.ReplyToMsgId != null)
                    {
                        var replyToMsgId = message25.ReplyToMsgId;
                        if (replyToMsgId != null &&
                            replyToMsgId.Value != 0)
                        {
                            TLInt channelId   = null;
                            var   peerChannel = message25.ToId as TLPeerChannel;
                            if (peerChannel != null)
                            {
                                channelId = peerChannel.Id;
                            }

                            var reply = CacheService.GetMessage(replyToMsgId, channelId);
                            if (reply != null)
                            {
                                messages[i].Reply = reply;
                            }
                            else
                            {
                                replyToMsgIds.Add(replyToMsgId);
                                replyToMsgs.Add(message25);
                            }
                        }
                    }

                    if (message25.NotListened)
                    {
                        if (message25.Media != null)
                        {
                            message25.Media.NotListened = true;
                        }
                    }
                }
            }

            if (replyToMsgIds.Count > 0)
            {
                var channel = With as TLChannel;
                if (channel != null)
                {
                    var firstReplyToMsg = replyToMsgs.FirstOrDefault();
                    var peerChat        = firstReplyToMsg != null ? firstReplyToMsg.ToId as TLPeerChat : null;
                    if (peerChat != null)
                    {
                        MTProtoService.GetMessagesAsync(
                            replyToMsgIds,
                            result =>
                        {
                            CacheService.AddChats(result.Chats, results => { });
                            CacheService.AddUsers(result.Users, results => { });

                            for (var i = 0; i < result.Messages.Count; i++)
                            {
                                for (var j = 0; j < replyToMsgs.Count; j++)
                                {
                                    var messageToReply = replyToMsgs[j];
                                    if (messageToReply != null &&
                                        messageToReply.ReplyToMsgId.Value == result.Messages[i].Index)
                                    {
                                        replyToMsgs[j].Reply = result.Messages[i];
                                    }
                                }
                            }

                            //Execute.BeginOnUIThread(() =>
                            //{
                            for (var i = 0; i < replyToMsgs.Count; i++)
                            {
                                replyToMsgs[i].NotifyOfPropertyChange(() => replyToMsgs[i].ReplyInfo);
                            }
                            //});
                        },
                            error =>
                        {
                            Execute.ShowDebugMessage("messages.getMessages error " + error);
                        });
                    }
                    else
                    {
                        MTProtoService.GetMessagesAsync(
                            channel.ToInputChannel(),
                            replyToMsgIds,
                            result =>
                        {
                            CacheService.AddChats(result.Chats, results => { });
                            CacheService.AddUsers(result.Users, results => { });

                            for (var i = 0; i < result.Messages.Count; i++)
                            {
                                for (var j = 0; j < replyToMsgs.Count; j++)
                                {
                                    var messageToReply = replyToMsgs[j];
                                    if (messageToReply != null &&
                                        messageToReply.ReplyToMsgId.Value == result.Messages[i].Index)
                                    {
                                        replyToMsgs[j].Reply = result.Messages[i];
                                    }
                                }
                            }

                            //Execute.BeginOnUIThread(() =>
                            //{
                            for (var i = 0; i < replyToMsgs.Count; i++)
                            {
                                replyToMsgs[i].NotifyOfPropertyChange(() => replyToMsgs[i].ReplyInfo);
                            }
                            //});
                        },
                            error =>
                        {
                            Execute.ShowDebugMessage("channels.getMessages error " + error);
                        });
                    }
                }
                else
                {
                    MTProtoService.GetMessagesAsync(
                        replyToMsgIds,
                        result =>
                    {
                        CacheService.AddChats(result.Chats, results => { });
                        CacheService.AddUsers(result.Users, results => { });

                        for (var i = 0; i < result.Messages.Count; i++)
                        {
                            for (var j = 0; j < replyToMsgs.Count; j++)
                            {
                                var messageToReply = replyToMsgs[j];
                                if (messageToReply != null &&
                                    messageToReply.ReplyToMsgId.Value == result.Messages[i].Index)
                                {
                                    replyToMsgs[j].Reply = result.Messages[i];
                                }
                            }
                        }

                        //Execute.BeginOnUIThread(() =>
                        //{
                        for (var i = 0; i < replyToMsgs.Count; i++)
                        {
                            replyToMsgs[i].NotifyOfPropertyChange(() => replyToMsgs[i].ReplyInfo);
                        }
                        //});
                    },
                        error =>
                    {
                        Execute.ShowDebugMessage("messages.getMessages error " + error);
                    });
                }
            }
        }
Esempio n. 10
0
        private void UpdateSets(TLAllStickers29 allStickers, System.Action callback)
        {
            _allStickers = allStickers;

            _emoticons.Clear();
            _stickerSets.Clear();

            for (var i = 0; i < allStickers.Documents.Count; i++)
            {
                var document22 = allStickers.Documents[i] as TLDocument22;
                if (document22 != null)
                {
                    if (document22.StickerSet != null)
                    {
                        var setId = document22.StickerSet.Name;
                        TLVector <TLStickerItem> stickers;
                        if (_stickerSets.TryGetValue(setId, out stickers))
                        {
                            stickers.Add(new TLStickerItem {
                                Document = document22
                            });
                        }
                        else
                        {
                            _stickerSets[setId] = new TLVector <TLStickerItem> {
                                new TLStickerItem {
                                    Document = document22
                                }
                            };
                        }
                    }
                }
            }

            Items.Clear();

            var firstChunkSize = 10;
            var count          = 0;
            var delayedItems   = new List <TLStickerSetBase>();

            for (var i = 0; i < allStickers.Sets.Count; i++)
            {
                var set     = allStickers.Sets[i];
                var setName = set.Id.ToString();
                TLVector <TLStickerItem> stickers;
                if (_stickerSets.TryGetValue(setName, out stickers))
                {
                    var objects = new TLVector <TLObject>();
                    foreach (var sticker in stickers)
                    {
                        objects.Add(sticker);
                    }

                    set.IsSelected = StickerSet != null && TLString.Equals(StickerSet.ShortName, set.ShortName, StringComparison.OrdinalIgnoreCase);
                    set.Stickers   = objects;
                    if (set.Stickers.Count > 0)
                    {
                        if (count < firstChunkSize)
                        {
                            Items.Add(set);
                            count++;
                        }
                        else
                        {
                            delayedItems.Add(set);
                        }
                    }
                }
            }

            AddItemsChunk(25, delayedItems, callback);
        }
        public void ContinueSendVideo(CompressingVideoFile videoFile)
        {
            if (videoFile == null)
            {
                return;
            }

            var file = videoFile.Source;

            if (file == null)
            {
                return;
            }

            if (!CheckDocumentSize(videoFile.Size))
            {
                MessageBox.Show(
                    string.Format(AppResources.MaximumFileSizeExceeded, MediaSizeConverter.Convert((int)Telegram.Api.Constants.MaximumUploadedFileSize)),
                    AppResources.Error,
                    MessageBoxButton.OK);
                return;
            }

            // to get access to the file with StorageFile.GetFileFromPathAsync in future
            AddFileToFutureAccessList(file);

            var documentAttributeVideo = new TLDocumentAttributeVideo
            {
                Duration = new TLInt((int)videoFile.Duration),
                W        = new TLInt((int)videoFile.Width),
                H        = new TLInt((int)videoFile.Height)
            };

            var documentAttributeFileName = new TLDocumentAttributeFileName
            {
                FileName = new TLString(file.Name)
            };

            var document = new TLDocument54
            {
                Id         = TLLong.Random(),
                AccessHash = new TLLong(0),
                Date       = TLUtils.DateToUniversalTimeTLInt(MTProtoService.ClientTicksDelta, DateTime.Now),
                MimeType   = new TLString(file.ContentType),
                Size       = new TLInt((int)videoFile.Size),
                Thumb      = videoFile.ThumbPhoto ?? new TLPhotoSizeEmpty {
                    Type = TLString.Empty
                },
                DCId       = new TLInt(0),
                Version    = new TLInt(0),
                Attributes = new TLVector <TLDocumentAttributeBase> {
                    documentAttributeFileName, documentAttributeVideo
                }
            };

            if (videoFile.EncodingProfile != null &&
                videoFile.EncodingProfile.Audio == null &&
                videoFile.Size < Telegram.Api.Constants.GifMaxSize &&
                TLString.Equals(document.MimeType, new TLString("video/mp4"), StringComparison.OrdinalIgnoreCase))
            {
                document.Attributes.Add(new TLDocumentAttributeAnimated());
            }

            var media = new TLMessageMediaDocument75 {
                Flags = new TLInt(0), Document = document, IsoFileName = file.Path, File = file, Caption = TLString.Empty
            };

            var caption = string.IsNullOrEmpty(videoFile.Caption) ? TLString.Empty : new TLString(videoFile.Caption);
            var message = GetMessage(caption, media);

            if (videoFile.TimerSpan != null && videoFile.TimerSpan.Seconds > 0)
            {
                message.NotListened = true;
                var ttlMessageMedia = message.Media as ITTLMessageMedia;
                if (ttlMessageMedia != null)
                {
                    ttlMessageMedia.TTLSeconds = new TLInt(videoFile.TimerSpan.Seconds);
                }
            }

            _mentions = videoFile.Mentions;
            var processedText = string.Empty;
            var entities      = GetEntities(message.Message.ToString(), out processedText);

            _mentions = null;

            if (entities.Count > 0)
            {
                message.Message  = new TLString(processedText);
                message.Entities = new TLVector <TLMessageEntityBase>(entities);
            }

            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, videoFile)));
            });
        }
Esempio n. 12
0
        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;
            }
        }
Esempio n. 13
0
        public void ResolveUsername(string text, string command = null)
        {
            if (IsEditingEnabled)
            {
                return;
            }

            if (string.IsNullOrEmpty(text))
            {
                CurrentInlineBot = null;

                return;
            }

            var username = new TLString(text.TrimStart('@'));

            var users = CacheService.GetUsers();

            for (var i = 0; i < users.Count; i++)
            {
                var user = users[i] as TLUser;
                if (user != null && user.IsInlineBot &&
                    TLString.Equals(user.UserName, username, StringComparison.OrdinalIgnoreCase))
                {
                    Execute.OnUIThread(() =>
                    {
                        if (!string.IsNullOrEmpty(command))
                        {
                            _currentInlineBot = user;
                            GetInlineBotResults(command);
                        }
                        else
                        {
                            CurrentInlineBot = user;
                            GetInlineBotResults(string.Empty);
                        }
                    });
                    return;
                }
            }

            CurrentInlineBot = null;
            NotifyOfPropertyChange(() => CurrentInlineBot);

            if (CurrentInlineBot == null)
            {
                IsWorking = true;
                MTProtoService.ResolveUsernameAsync(username,
                                                    result => BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    if (!string.IsNullOrEmpty(command))
                    {
                        _currentInlineBot = result.Users.FirstOrDefault();
                        GetInlineBotResults(command);
                    }
                    else
                    {
                        CurrentInlineBot = result.Users.FirstOrDefault();
                        GetInlineBotResults(string.Empty);
                    }
                }),
                                                    error => BeginOnUIThread(() =>
                {
                    IsWorking = false;

                    Telegram.Api.Helpers.Execute.ShowDebugMessage("contacts.resolveUsername error " + error);
                }));
            }
        }
        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");
        }