コード例 #1
0
        public void EditMessageAsync(TLInputPeerBase peer, int id, string message, TLVector <TLMessageEntityBase> entities, TLReplyMarkupBase replyMarkup, bool noWebPage, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLMessagesEditMessage {
                Flags = 0, Peer = peer, Id = id, Message = message, IsNoWebPage = noWebPage, Entities = entities, ReplyMarkup = replyMarkup
            };

            const string caption = "messages.editMessage";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as ITLMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null, true);
                }

                callback?.Invoke(result);
            },
                                                   faultCallback);
        }
コード例 #2
0
        public void EditMessageAsync(TLInputPeerBase peer, TLInt id, TLString message, TLVector <TLMessageEntityBase> entities, TLInputMediaBase media, TLReplyKeyboardBase replyMarkup, bool noWebPage, bool stopGeoLive, TLInputGeoPointBase geoPoint, Action <TLUpdatesBase> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLEditMessage {
                Flags = new TLInt(0), Peer = peer, Id = id, Message = message, NoWebPage = noWebPage, Entities = entities, Media = media, ReplyMarkup = replyMarkup, StopGeoLive = stopGeoLive, GeoPoint = geoPoint
            };

            const string caption = "messages.editMessage";

            SendInformativeMessage <TLUpdatesBase>(caption, obj,
                                                   result =>
            {
                var multiPts = result as IMultiPts;
                if (multiPts != null)
                {
                    _updatesService.SetState(multiPts, caption);
                }
                else
                {
                    ProcessUpdates(result, null, true);
                }

                callback.SafeInvoke(result);
            },
                                                   faultCallback);
        }
コード例 #3
0
        public TLMessage34 GetMessage(TLObject With, TLInputPeerBase Peer, TLString text, TLMessageMediaBase media)
        {
            var broadcast = With as TLBroadcastChat;
            var channel   = With as TLChannel;
            var toId      = channel != null
                ? new TLPeerChannel {
                Id = channel.Id
            }
                : broadcast != null
                ? new TLPeerBroadcast {
                Id = broadcast.Id
            }
                : TLUtils.InputPeerToPeer(Peer, IoC.Get <IStateService>().CurrentUserId);

            var date = TLUtils.DateToUniversalTimeTLInt(IoC.Get <IMTProtoService>().ClientTicksDelta, DateTime.Now);

            var message = TLUtils.GetMessage(
                new TLInt(IoC.Get <IStateService>().CurrentUserId),
                toId,
                broadcast != null && channel == null ? MessageStatus.Broadcast : MessageStatus.Sending,
                TLBool.True,
                TLBool.True,
                date,
                text,
                media,
                TLLong.Random(),
                new TLInt(0)
                );

            return(message);
        }
コード例 #4
0
        public void GetMessageEditDataAsync(TLInputPeerBase peer, int id, Action <TLMessagesMessageEditData> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLMessagesGetMessageEditData {
                Peer = peer, Id = id
            };

            SendInformativeMessage("messages.getMessageEditData", obj, callback, faultCallback);
        }
コード例 #5
0
        public void ResetTopPeerRatingAsync(TLTopPeerCategoryBase category, TLInputPeerBase peer, Action <bool> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLContactsResetTopPeerRating {
                Category = category, Peer = peer
            };

            SendInformativeMessage <bool>("contacts.resetTopPeerRating", obj, callback, faultCallback);
        }
コード例 #6
0
        public override TLObject FromBytes(byte[] bytes, ref int position)
        {
            bytes.ThrowExceptionIfIncorrect(ref position, Signature);

            Peer = GetObject <TLInputPeerBase>(bytes, ref position);

            return(this);
        }
コード例 #7
0
        public void ReportPeerAsync(TLInputPeerBase peer, TLInputReportReasonBase reason, Action <TLBool> callback, Action <TLRPCError> faultCallback = null)
        {
            var obj = new TLReportPeer {
                Peer = peer, Reason = reason
            };

            SendInformativeMessage("account.reportPeer", obj, callback, faultCallback);
        }
コード例 #8
0
        public BotResultsCollection(IMTProtoService protoService, TLInputUserBase bot, TLInputPeerBase peer, TLInputGeoPointBase geoPoint, string query)
        {
            _protoService = protoService;
            _bot          = bot;
            _peer         = peer;
            _geoPoint     = geoPoint;
            _query        = query;

            _nextOffset = string.Empty;
        }
コード例 #9
0
ファイル: DialogGalleryViewModel.cs プロジェクト: Fart03/lau
 public DialogGalleryViewModel(TLInputPeerBase peer, TLMessage selected, IMTProtoService protoService)
     : base(protoService, null, null)
 {
     if (selected.Media is TLMessageMediaPhoto photoMedia || selected.IsVideo() || selected.IsRoundVideo() || selected.IsGif())
     {
         Items = new MvxObservableCollection <GalleryItem> {
             new GalleryMessageItem(selected)
         };
         SelectedItem = Items[0];
         FirstItem    = Items[0];
     }
コード例 #10
0
        public ChatPhotosViewModel(IMTProtoService protoService, TLChatFullBase chatFull, TLChatBase chat)
            : base(protoService, null, null)
        {
            _peer      = chat.ToInputPeer();
            _lastMaxId = int.MaxValue;

            Items = new MvxObservableCollection <GalleryItem> {
                new GalleryPhotoItem(chatFull.ChatPhoto as TLPhoto, chat)
            };
            SelectedItem = Items[0];
            FirstItem    = Items[0];
            Initialize();
        }
コード例 #11
0
        public DialogGalleryViewModel(IMTProtoService protoService, ICacheService cacheService, TLInputPeerBase peer, TLMessage selected)
            : base(protoService, cacheService, null)
        {
            _group = new MvxObservableCollection <GalleryItem>();
            _peer  = peer;

            if (selected.Media is TLMessageMediaPhoto photoMedia || selected.IsVideo())
            {
                Items = new MvxObservableCollection <GalleryItem> {
                    new GalleryMessageItem(selected)
                };
                SelectedItem = Items[0];
                FirstItem    = Items[0];
            }
コード例 #12
0
        private static byte[] ComposeSendMessageRequest(TLInputPeerBase peerBase, TLString message, TLLong randomId)
        {
            //#4cde0aab
            var signature = new byte[] { 0xab, 0x0a, 0xde, 0x4c };

            TLUtils.WriteLine("Peer: " + peerBase);
            TLUtils.WriteLine("Message: " + message);
            TLUtils.WriteLine("RandomId: " + randomId);

            return(signature
                   .Concat(peerBase.ToBytes())
                   .Concat(message.ToBytes())
                   .Concat(randomId.ToBytes())
                   .ToArray());
        }
コード例 #13
0
 private static void DeleteHistoryAsync(IMTProtoService mtProtoService, TLInputPeerBase peer, TLInt offset, Action <TLAffectedHistory> callback, Action <TLRPCError> faultCallback = null)
 {
     mtProtoService.DeleteHistoryAsync(peer, offset,
                                       affectedHistory =>
     {
         if (affectedHistory.Offset.Value > 0)
         {
             DeleteHistoryAsync(mtProtoService, peer, affectedHistory.Offset, callback, faultCallback);
         }
         else
         {
             callback.SafeInvoke(affectedHistory);
         }
     },
                                       faultCallback.SafeInvoke);
 }
コード例 #14
0
        public ChatPhotosViewModel(IMTProtoService protoService, ICacheService cacheService, TLChatFullBase chatFull, TLChatBase chat, TLMessageService serviceMessage)
            : base(protoService, cacheService, null)
        {
            _peer      = chat.ToInputPeer();
            _lastMaxId = serviceMessage.Id;

            if (serviceMessage.Action is TLMessageActionChatEditPhoto editPhotoAction)
            {
                Items = new MvxObservableCollection <GalleryItem> {
                    new GalleryPhotoItem(editPhotoAction.Photo as TLPhoto, chat)
                };
                SelectedItem = Items[0];
                FirstItem    = Items[0];
            }

            Initialize(serviceMessage.Id);
        }
コード例 #15
0
        public WebViewModel(IStateService stateService, INavigationService navigationService, IMTProtoService mtProtoService)
        {
            _stateService      = stateService;
            _navigationService = navigationService;
            _mtProtoService    = mtProtoService;

            _sharedContact             = stateService.SharedContact as TLUser;
            stateService.SharedContact = null;

            var userName = _sharedContact as IUserName;

            if (userName != null && !TLString.IsNullOrEmpty(userName.UserName))
            {
                Subtitle = "@" + userName.UserName;
            }

            _botCallbackAnswer             = stateService.BotCallbackAnswer;
            stateService.BotCallbackAnswer = null;

            _forwardMessages             = stateService.ForwardMessages;
            stateService.ForwardMessages = null;

            var botCallbackAnswer54 = _botCallbackAnswer as TLBotCallbackAnswer54;

            if (botCallbackAnswer54 != null)
            {
                Url = new Uri(botCallbackAnswer54.Url.ToString(), UriKind.RelativeOrAbsolute);
#if DEBUG
                Clipboard.SetText(botCallbackAnswer54.Url.ToString());
                MessageBox.Show(botCallbackAnswer54.Url.ToString());
#endif
            }

            _game             = stateService.Game;
            stateService.Game = null;

            if (_game != null)
            {
                GameTitle = _game.Title.ToString();
            }

            _inputPeer             = stateService.InputPeer;
            stateService.InputPeer = null;

            _timer = new Timer(OnTimerTick);
        }
コード例 #16
0
        private static byte[] ComposeGetHistoryRequest(TLInputPeerBase peerBase, TLInt offset, TLInt maxId, TLInt limit)
        {
            //#92a1df2f
            var signature = new byte[] { 0x2f, 0xdf, 0xa1, 0x92 };

            TLUtils.WriteLine("Peer: " + peerBase);
            TLUtils.WriteLine("Offset: " + offset);
            TLUtils.WriteLine("MaxId: " + maxId);
            TLUtils.WriteLine("Limit: " + limit);

            return(signature
                   .Concat(peerBase.ToBytes())
                   .Concat(offset.ToBytes())
                   .Concat(maxId.ToBytes())
                   .Concat(limit.ToBytes())
                   .ToArray());
        }
コード例 #17
0
        private void ReportAsync(TLInputPeerBase inputPeer, TLVector <TLInt> id, TLInputReportReasonBase reason)
        {
            if (inputPeer == null)
            {
                return;
            }
            if (reason == null)
            {
                return;
            }

            if (id == null)
            {
                IsWorking = true;
                MTProtoService.ReportPeerAsync(inputPeer, reason,
                                               result => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    MessageBox.Show(AppResources.ReportSpamNotification, AppResources.AppName, MessageBoxButton.OK);
                }),
                                               error => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                }));
            }
            else
            {
                IsWorking = true;
                MTProtoService.ReportAsync(inputPeer, id, reason,
                                           result => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                    MessageBox.Show(AppResources.ReportSpamNotification, AppResources.AppName, MessageBoxButton.OK);
                }),
                                           error => Execute.BeginOnUIThread(() =>
                {
                    IsWorking = false;
                }));
            }
        }
コード例 #18
0
 private void DeleteHistoryAsync(bool justClear, TLInputPeerBase peer, Action <TLAffectedHistory> callback, Action <TLRPCError> faultCallback = null)
 {
     DeleteHistoryAsync(MTProtoService, justClear, peer, new TLInt(0), callback, faultCallback);
 }
コード例 #19
0
        private void GetReasonAndReportAsync(TLInputPeerBase inputPeer, TLVector <TLInt> id, TLInputReportReasonBase reason)
        {
            if (reason is TLInputReportReasonOther)
            {
                var text = new TextBox {
                    Margin = new Thickness(0.0, 0.0, 12.0, 0.0)
                };
                TiltEffect.SetIsTiltEnabled(text, true);

                var reportContent = new StackPanel();
                reportContent.Children.Add(new TextBlock {
                    Text = AppResources.Description, Margin = new Thickness(12.0, 6.0, 12.0, -5.0), Style = (Style)Application.Current.Resources["PhoneTextSubtleStyle"]
                });
                reportContent.Children.Add(text);

                var confirmation = new CustomMessageBox
                {
                    Caption              = AppResources.Report,
                    Message              = string.Empty,
                    Content              = reportContent,
                    RightButtonContent   = AppResources.Cancel.ToLowerInvariant(),
                    LeftButtonContent    = AppResources.Ok.ToLowerInvariant(),
                    IsLeftButtonEnabled  = true,
                    IsRightButtonEnabled = true
                };

                text.Loaded += (o, e) =>
                {
                    confirmation.IsLeftButtonEnabled = false;
                    text.Focus();
                };
                text.TextChanged += (o, e) =>
                {
                    confirmation.IsLeftButtonEnabled = !string.IsNullOrEmpty(text.Text);
                };
#if WP8
                var isFullHD = Application.Current.Host.Content.ScaleFactor == 225;
                if (isFullHD || Environment.OSVersion.Version.Major >= 10)
                {
                    text.FontSize      = 17.667;
                    confirmation.Style = (Style)Application.Current.Resources["CustomMessageBoxFullHDStyle"];
                }
#endif

                confirmation.Dismissed += (sender, args) =>
                {
                    switch (args.Result)
                    {
                    case CustomMessageBoxResult.RightButton:
                        break;

                    case CustomMessageBoxResult.LeftButton:
                        reason = new TLInputReportReasonOther {
                            Text = new TLString(text.Text)
                        };
                        ReportAsync(inputPeer, id, reason);
                        break;

                    case CustomMessageBoxResult.None:
                        // Do something.
                        break;

                    default:
                        break;
                    }
                };
                confirmation.Show();
            }
            else
            {
                ReportAsync(inputPeer, id, reason);
            }
        }
コード例 #20
0
        public void Report(TLInputPeerBase inputPeer, TLVector <TLInt> id = null)
        {
            var spamRadioButton = new RadioButton {
                Content = AppResources.Spam, IsChecked = true, Margin = new Thickness(0.0, 0.0, 12.0, -12.0), Background = new SolidColorBrush(Colors.Transparent), GroupName = "Report"
            };
            var violenceRadioButton = new RadioButton {
                Content = AppResources.Violence, Margin = new Thickness(0.0, -12.0, 12.0, -12.0), Background = new SolidColorBrush(Colors.Transparent), GroupName = "Report"
            };
            var pornographyRadioButton = new RadioButton {
                Content = AppResources.Pornography, Margin = new Thickness(0.0, -12.0, 12.0, -12.0), Background = new SolidColorBrush(Colors.Transparent), GroupName = "Report"
            };
            var copyrightRadioButton = new RadioButton {
                Content = AppResources.Copyright, Margin = new Thickness(0.0, -12.0, 12.0, -12.0), Background = new SolidColorBrush(Colors.Transparent), GroupName = "Report"
            };
            var otherRadioButton = new RadioButton {
                Content = AppResources.Other, Margin = new Thickness(0.0, -12.0, 12.0, -12.0), Background = new SolidColorBrush(Colors.Transparent), GroupName = "Report"
            };

            TiltEffect.SetIsTiltEnabled(spamRadioButton, true);
            TiltEffect.SetIsTiltEnabled(violenceRadioButton, true);
            TiltEffect.SetIsTiltEnabled(pornographyRadioButton, true);
            TiltEffect.SetIsTiltEnabled(otherRadioButton, true);

            var reportContent = new StackPanel();

            reportContent.Children.Add(spamRadioButton);
            reportContent.Children.Add(violenceRadioButton);
            reportContent.Children.Add(pornographyRadioButton);
            reportContent.Children.Add(copyrightRadioButton);
            reportContent.Children.Add(otherRadioButton);

            var confirmation = new CustomMessageBox
            {
                Caption              = AppResources.Report,
                Message              = string.Empty,
                Content              = reportContent,
                LeftButtonContent    = AppResources.Cancel.ToLowerInvariant(),
                RightButtonContent   = AppResources.Ok.ToLowerInvariant(),
                IsLeftButtonEnabled  = true,
                IsRightButtonEnabled = true
            };

#if WP8
            var isFullHD = Application.Current.Host.Content.ScaleFactor == 225 || Environment.OSVersion.Version.Major >= 10;
            if (isFullHD)
            {
                spamRadioButton.FontSize        = 17.667;
                violenceRadioButton.FontSize    = 17.667;
                pornographyRadioButton.FontSize = 17.667;
                copyrightRadioButton.FontSize   = 17.667;
                otherRadioButton.FontSize       = 17.667;
                confirmation.Style = (Style)Application.Current.Resources["CustomMessageBoxFullHDStyle"];
            }
#endif

            confirmation.Dismissed += (sender, args) =>
            {
                if (args.Result == CustomMessageBoxResult.RightButton)
                {
                    TLInputReportReasonBase reason = null;
                    if (spamRadioButton.IsChecked == true)
                    {
                        reason = new TLInputReportReasonSpam();
                    }
                    else if (violenceRadioButton.IsChecked == true)
                    {
                        reason = new TLInputReportReasonViolence();
                    }
                    else if (pornographyRadioButton.IsChecked == true)
                    {
                        reason = new TLInputReportReasonPornography();
                    }
                    else if (copyrightRadioButton.IsChecked == true)
                    {
                        reason = new TLInputReportReasonCopyright();
                    }
                    else if (otherRadioButton.IsChecked == true)
                    {
                        reason = new TLInputReportReasonOther {
                            Text = TLString.Empty
                        };
                    }
                    GetReasonAndReportAsync(inputPeer, id, reason);
                }
            };
            confirmation.Show();
        }
コード例 #21
0
 /// <summary>
 /// Выполняет отправку текстового сообщения.
 /// </summary>
 /// <param name="seqNo"></param>
 /// <param name="peerBase">     Пользователь или чат, куда будет отправлено сообщение</param>
 /// <param name="message">  Текст сообщения</param>
 /// <param name="randomId"> Уникальный клиентский идентификатор сообщений, необходимый для исключения повторной отправки сообщения</param>
 /// <returns></returns>
 private static TLResponse SendSendMessageRequest(int seqNo, TLInputPeerBase peerBase, TLString message, TLLong randomId)
 {
     return(RequestHelper.Send("messages.sendMessage", seqNo, () => ComposeSendMessageRequest(peerBase, message, randomId)));
 }
コード例 #22
0
ファイル: ShareViewModel.cs プロジェクト: nazzi88ua/Unigram
        private void SendExecute()
        {
            var dialogs = SelectedItems.ToList();

            if (dialogs.Count == 0)
            {
                return;
            }

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            if (_messages != null)
            {
                foreach (var dialog in dialogs)
                {
                    TLInputPeerBase toPeer   = dialog.ToInputPeer();
                    TLInputPeerBase fromPeer = null;
                    TLMessage       comment  = null;

                    var msgs   = new TLVector <TLMessage>();
                    var msgIds = new TLVector <int>();

                    var grouped = false;

                    foreach (var fwdMessage in _messages)
                    {
                        var clone = fwdMessage.Clone();
                        clone.Id              = 0;
                        clone.HasEditDate     = false;
                        clone.EditDate        = null;
                        clone.HasReplyToMsgId = false;
                        clone.ReplyToMsgId    = null;
                        clone.HasReplyMarkup  = false;
                        clone.ReplyMarkup     = null;
                        clone.Date            = date;
                        clone.ToId            = dialog.ToPeer();
                        clone.RandomId        = TLLong.Random();
                        clone.IsOut           = true;
                        clone.IsPost          = false;
                        clone.FromId          = SettingsHelper.UserId;
                        clone.IsMediaUnread   = dialog.ToPeer() is TLPeerChannel ? true : false;
                        clone.IsUnread        = true;
                        clone.State           = TLMessageState.Sending;
                        clone.HasGroupedId    = false;
                        clone.GroupedId       = null;

                        if (clone.Media == null)
                        {
                            clone.HasMedia = true;
                            clone.Media    = new TLMessageMediaEmpty();
                        }

                        if (fwdMessage.HasGroupedId)
                        {
                            grouped = true;
                        }

                        if (fwdMessage.Parent is TLChannel channel)
                        {
                            if (channel.IsBroadcast)
                            {
                                if (!channel.IsSignatures)
                                {
                                    clone.HasFromId = false;
                                    clone.FromId    = null;
                                }

                                // TODO
                                //if (IsSilent)
                                //{
                                //    clone.IsSilent = true;
                                //}

                                clone.HasViews = true;
                                clone.Views    = 1;
                            }
                        }

                        if (clone.Media is TLMessageMediaGame gameMedia)
                        {
                            clone.HasEntities = false;
                            clone.Entities    = null;
                            clone.Message     = null;
                        }
                        else if (clone.Media is TLMessageMediaGeoLive geoLiveMedia)
                        {
                            clone.Media = new TLMessageMediaGeo {
                                Geo = geoLiveMedia.Geo
                            };
                        }

                        if (fromPeer == null)
                        {
                            fromPeer = fwdMessage.Parent.ToInputPeer();
                        }

                        if (clone.FwdFrom == null && !clone.IsGame())
                        {
                            if (fwdMessage.ToId is TLPeerChannel)
                            {
                                var fwdChannel = CacheService.GetChat(fwdMessage.ToId.Id) as TLChannel;
                                if (fwdChannel != null && fwdChannel.IsMegaGroup)
                                {
                                    clone.HasFwdFrom = true;
                                    clone.FwdFrom    = new TLMessageFwdHeader
                                    {
                                        HasFromId = true,
                                        FromId    = fwdMessage.FromId,
                                        Date      = fwdMessage.Date
                                    };
                                }
                                else
                                {
                                    clone.HasFwdFrom = true;
                                    clone.FwdFrom    = new TLMessageFwdHeader
                                    {
                                        HasFromId = fwdMessage.HasFromId,
                                        FromId    = fwdMessage.FromId,
                                        Date      = fwdMessage.Date
                                    };

                                    if (fwdChannel.IsBroadcast)
                                    {
                                        clone.FwdFrom.HasChannelId  = clone.FwdFrom.HasChannelPost = true;
                                        clone.FwdFrom.ChannelId     = fwdChannel.Id;
                                        clone.FwdFrom.ChannelPost   = fwdMessage.Id;
                                        clone.FwdFrom.HasPostAuthor = fwdMessage.HasPostAuthor;
                                        clone.FwdFrom.PostAuthor    = fwdMessage.PostAuthor;
                                    }
                                }
                            }
                            else if (fwdMessage.FromId == SettingsHelper.UserId && fwdMessage.ToId is TLPeerUser peerUser && peerUser.UserId == SettingsHelper.UserId)
                            {
                            }
                            else
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = true,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };
                            }

                            if (clone.FwdFrom != null && ((toPeer is TLInputPeerUser user && user.UserId == SettingsHelper.UserId) || toPeer is TLInputPeerSelf))
                            {
                                clone.FwdFrom.SavedFromMsgId    = fwdMessage.Id;
                                clone.FwdFrom.SavedFromPeer     = fwdMessage.Parent?.ToPeer();
                                clone.FwdFrom.HasSavedFromMsgId = true;
                                clone.FwdFrom.HasSavedFromPeer  = clone.FwdFrom.SavedFromPeer != null;
                            }
                        }

                        msgs.Add(clone);
                        msgIds.Add(fwdMessage.Id);
                    }

                    if (!string.IsNullOrEmpty(_comment))
                    {
                        comment = TLUtils.GetMessage(SettingsHelper.UserId, toPeer.ToPeer(), TLMessageState.Sending, true, true, date, _comment, new TLMessageMediaEmpty(), TLLong.Random(), null);
                        msgs.Insert(0, comment);
                    }

                    CacheService.SyncSendingMessages(msgs, null, async(m) =>
                    {
                        if (comment != null)
                        {
                            msgs.Remove(comment);

                            var result = await ProtoService.SendMessageAsync(comment, null);
                            if (result.IsSucceeded)
                            {
                            }
                            else
                            {
                            }
                        }

                        var response = await ProtoService.ForwardMessagesAsync(toPeer, fromPeer, msgIds, msgs, IsWithMyScore, grouped);
                        if (response.IsSucceeded)
                        {
                            foreach (var i in m)
                            {
                                Aggregator.Publish(i);
                            }
                        }
                        else
                        {
                        }
                    });
                }

                NavigationService.GoBack();
            }
コード例 #23
0
 public SearchDocumentsRequest(TLInputPeerBase inputPeer, string text, IList <TLMessageBase> source)
 {
     InputPeer = inputPeer;
     Text      = text;
     Source    = source;
 }
コード例 #24
0
ファイル: GallerySecretViewModel.cs プロジェクト: Fart03/lau
 public GallerySecretViewModel(TLInputPeerBase peer, TLMessage message, IMTProtoService protoService, ICacheService cacheService, ITelegramEventAggregator aggregator)
     : base(protoService, cacheService, aggregator)
 {
     SelectedItem = new GallerySecretMessageItem(message);
 }
コード例 #25
0
        private void SendExecute()
        {
            var dialogs = SelectedItems.ToList();

            if (dialogs.Count == 0)
            {
                return;
            }

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            if (_message != null)
            {
                foreach (var dialog in dialogs)
                {
                    TLInputPeerBase toPeer     = dialog.ToInputPeer();
                    TLInputPeerBase fromPeer   = null;
                    var             fwdMessage = _message;

                    var msgs   = new TLVector <TLMessage>();
                    var msgIds = new TLVector <int>();

                    var clone = fwdMessage.Clone();
                    clone.Id = 0;
                    clone.HasReplyToMsgId = false;
                    clone.ReplyToMsgId    = null;
                    clone.HasReplyMarkup  = false;
                    clone.ReplyMarkup     = null;
                    clone.Date            = date;
                    clone.ToId            = dialog.Peer;
                    clone.RandomId        = TLLong.Random();
                    clone.IsOut           = true;
                    clone.IsPost          = false;
                    clone.FromId          = SettingsHelper.UserId;
                    clone.IsMediaUnread   = dialog.Peer is TLPeerChannel ? true : false;
                    clone.IsUnread        = true;
                    clone.State           = TLMessageState.Sending;

                    if (clone.Media == null)
                    {
                        clone.HasMedia = true;
                        clone.Media    = new TLMessageMediaEmpty();
                    }

                    if (fwdMessage.Parent is TLChannel channel)
                    {
                        if (channel.IsBroadcast)
                        {
                            if (!channel.IsSignatures)
                            {
                                clone.HasFromId = false;
                                clone.FromId    = null;
                            }

                            // TODO
                            //if (IsSilent)
                            //{
                            //    clone.IsSilent = true;
                            //}

                            clone.HasViews = true;
                            clone.Views    = 1;
                        }
                    }

                    if (clone.Media is TLMessageMediaGame gameMedia)
                    {
                        clone.HasEntities = false;
                        clone.Entities    = null;
                        clone.Message     = null;
                    }

                    if (fromPeer == null)
                    {
                        fromPeer = fwdMessage.Parent.ToInputPeer();
                    }

                    if (clone.FwdFrom == null && !clone.IsGame())
                    {
                        if (fwdMessage.ToId is TLPeerChannel)
                        {
                            var fwdChannel = CacheService.GetChat(fwdMessage.ToId.Id) as TLChannel;
                            if (fwdChannel != null && fwdChannel.IsMegaGroup)
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = true,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };
                            }
                            else
                            {
                                clone.HasFwdFrom = true;
                                clone.FwdFrom    = new TLMessageFwdHeader
                                {
                                    HasFromId = fwdMessage.HasFromId,
                                    FromId    = fwdMessage.FromId,
                                    Date      = fwdMessage.Date
                                };

                                if (fwdChannel.IsBroadcast)
                                {
                                    clone.FwdFrom.HasChannelId = clone.FwdFrom.HasChannelPost = true;
                                    clone.FwdFrom.ChannelId    = fwdChannel.Id;
                                    clone.FwdFrom.ChannelPost  = fwdMessage.Id;
                                }
                            }
                        }
                        else if (fwdMessage.FromId == SettingsHelper.UserId && fwdMessage.ToId is TLPeerUser peerUser && peerUser.UserId == SettingsHelper.UserId)
                        {
                        }
                        else
                        {
                            clone.HasFwdFrom = true;
                            clone.FwdFrom    = new TLMessageFwdHeader
                            {
                                HasFromId = true,
                                FromId    = fwdMessage.FromId,
                                Date      = fwdMessage.Date
                            };
                        }
                    }

                    msgs.Add(clone);
                    msgIds.Add(fwdMessage.Id);

                    CacheService.SyncSendingMessage(clone, null, async(m) =>
                    {
                        var response = await ProtoService.ForwardMessagesAsync(toPeer, fromPeer, msgIds, msgs, IsWithMyScore);
                        if (response.IsSucceeded)
                        {
                            Aggregator.Publish(m);
                        }
                    });
                }

                NavigationService.GoBack();
            }
コード例 #26
0
        private void SendReply(TLInputPeerBase inputPeer, TLString message, TLInt msgId)
        {
            if (msgId == null)
            {
                return;
            }
            if (TLString.IsNullOrEmpty(message))
            {
                return;
            }

            var actionInfo = TLUtils.OpenObjectFromMTProtoFile <TLVector <TLActionInfo> >(_actionInfoSyncRoot, Constants.ActionQueueFileName) ?? new TLVector <TLActionInfo>();

            var count = actionInfo.Count;

            Log("send count=" + count);

            var peerChannel = inputPeer as TLInputPeerChannel;
            var readHistory = peerChannel != null
                ? (TLObject) new TLReadChannelHistory {
                Channel = new TLInputChannel {
                    ChannelId = peerChannel.ChatId, AccessHash = peerChannel.AccessHash
                }, MaxId = msgId
            }
                : new TLReadHistory {
                Peer = inputPeer, MaxId = msgId
            };

            var readHistoryActionInfo = new TLActionInfo();

            readHistoryActionInfo.SendBefore = new TLInt(0);
            readHistoryActionInfo.Action     = readHistory;

            actionInfo.Add(readHistoryActionInfo);

            var sendMessage = new TLSendMessage();

            sendMessage.Flags    = new TLInt(0);
            sendMessage.Peer     = inputPeer;
            sendMessage.Message  = message;
            sendMessage.RandomId = TLLong.Random();

            var sendMessageActionInfo = new TLActionInfo();

            sendMessageActionInfo.SendBefore = new TLInt(0);
            sendMessageActionInfo.Action     = sendMessage;

            actionInfo.Add(sendMessageActionInfo);

            TLUtils.SaveObjectToMTProtoFile(new object(), Constants.ActionQueueFileName, actionInfo);

            if (actionInfo.Count > 0)
            {
                var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "InteractiveNotificationsBackgroundTask", _id);
                var eventAggregator     = new TelegramEventAggregator();
                var cacheService        = new InMemoryCacheService(eventAggregator);
                var updatesService      = new UpdatesService(cacheService, eventAggregator);
                var transportService    = new TransportService();
                var connectionService   = new ConnectionService(deviceInfoService);
                var publicConfigService = new MockupPublicConfigService();

                var manualResetEvent = new ManualResetEvent(false);
                Log("before init");
                var requestsToRemove = new List <TLObject>();
                var mtProtoService   = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);
                mtProtoService.Initialized += async(o, e) =>
                {
                    Log("init completed");

                    var actionsString = new StringBuilder();
                    foreach (var info in actionInfo)
                    {
                        actionsString.AppendLine(info.ToString());
                    }
                    Log(actionsString.ToString());

                    var       sendMessageActions = new List <TLObject>();
                    const int maxActionCount     = 10;
                    var       currentCount       = 0;
                    foreach (var ai in actionInfo)
                    {
                        if (TLUtils.IsValidAction(ai.Action) && currentCount < maxActionCount)
                        {
                            currentCount++;
                            sendMessageActions.Add(ai.Action);
                        }
                    }

                    if (sendMessageActions.Count > 0)
                    {
                        mtProtoService.SendActionsAsync(sendMessageActions,
                                                        (request, result) => // will be invoked for each sent action
                        {
                            requestsToRemove.Add(request);
                            var sendingMessages = mtProtoService.SendingMessages;
                            Log("send completed count=" + sendingMessages, () =>
                            {
                                if (sendingMessages == 0)
                                {
                                    _clearActionInfoFile = true;

                                    manualResetEvent.Set();
                                }
                            });
                        },
                                                        error =>
                        {
                            Log(string.Format("send error={0}\n{1}", error, error.Exception),
                                async() =>
                            {
                                await Task.Delay(TimeSpan.FromSeconds(1.0));
                                manualResetEvent.Set();
                            });
                        });
                    }
                    else
                    {
                        manualResetEvent.Set();
                    }
                };
                mtProtoService.InitializationFailed += (o, e) =>
                {
                    Log("init failed");

                    manualResetEvent.Set();
                };
                mtProtoService.Initialize();
#if DEBUG
                manualResetEvent.WaitOne();
#else
                manualResetEvent.WaitOne(15000);
#endif
                if (_clearActionInfoFile)
                {
                    Log("clear");
                    lock (_actionInfoSyncRoot)
                    {
                        var actions = actionInfo;

                        foreach (var o in requestsToRemove)
                        {
                            MTProtoService.RemoveActionInfoCommon(actions, o);
                        }

                        TLUtils.SaveObjectToMTProtoFile(_actionInfoSyncRoot, Constants.ActionQueueFileName, actions);
                    }
                }
            }
        }
コード例 #27
0
ファイル: OutputTypingManager.cs プロジェクト: Fart03/lau
 public OutputTypingManager(IMTProtoService protoService, TLInputPeerBase peer, double delay = 5.0)
 {
     _peer         = peer;
     _delay        = delay;
     _protoService = protoService;
 }
コード例 #28
0
 public MediaCollection(IMTProtoService protoService, TLInputPeerBase peer, TLMessagesFilterBase filter)
 {
     _protoService = protoService;
     _peer         = peer;
     _filter       = filter;
 }
コード例 #29
0
        private void UpdateNotifySettings(TLInputPeerBase inputPeer, TLInt muteUntil)
        {
            var deviceInfoService   = new DeviceInfoService(GetInitConnection(), true, "InteractiveNotificationsBackgroundTask", _id);
            var eventAggregator     = new TelegramEventAggregator();
            var cacheService        = new InMemoryCacheService(eventAggregator);
            var updatesService      = new UpdatesService(cacheService, eventAggregator);
            var transportService    = new TransportService();
            var connectionService   = new ConnectionService(deviceInfoService);
            var publicConfigService = new MockupPublicConfigService();

            var manualResetEvent = new ManualResetEvent(false);

            Log("before init");
            var mtProtoService = new MTProtoService(deviceInfoService, updatesService, cacheService, transportService, connectionService, publicConfigService);

            mtProtoService.Initialized += (o, e) =>
            {
                Log("init completed");

                mtProtoService.GetNotifySettingsAsync(new TLInputNotifyPeer {
                    Peer = inputPeer
                },
                                                      result =>
                {
                    Log("getNotifySettings completed", () =>
                    {
                        var peerNotifySettings = result as TLPeerNotifySettings;
                        if (peerNotifySettings != null)
                        {
                            if (muteUntil.Value < int.MaxValue)
                            {
                                muteUntil = TLUtils.DateToUniversalTimeTLInt(mtProtoService.ClientTicksDelta, DateTime.Now.AddSeconds(muteUntil.Value));
                            }

                            var inputPeerNotifySettings = new TLInputPeerNotifySettings78
                            {
                                Flags     = new TLInt(0),
                                MuteUntil = muteUntil,
                                Sound     = peerNotifySettings.Sound,
                            };

                            mtProtoService.UpdateNotifySettingsAsync(new TLInputNotifyPeer {
                                Peer = inputPeer
                            },
                                                                     inputPeerNotifySettings,
                                                                     result2 =>
                            {
                                Log("setNotifySettings completed", () =>
                                {
                                    manualResetEvent.Set();
                                });
                            },
                                                                     error2 =>
                            {
                                Log(string.Format("setNotifySettings error={0}\n{1}", error2, error2.Exception),
                                    async() =>
                                {
                                    await Task.Delay(TimeSpan.FromSeconds(1.0));
                                    manualResetEvent.Set();
                                });
                            });
                        }
                        else
                        {
                            manualResetEvent.Set();
                        }
                    });
                },
                                                      error =>
                {
                    Log(string.Format("getNotifySettings error={0}\n{1}", error, error.Exception),
                        async() =>
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1.0));
                        manualResetEvent.Set();
                    });
                });
            };
            mtProtoService.InitializationFailed += (o, e) =>
            {
                Log("init failed");

                manualResetEvent.Set();
            };
            mtProtoService.Initialize();
#if DEBUG
            manualResetEvent.WaitOne();
#else
            manualResetEvent.WaitOne(15000);
#endif
        }
コード例 #30
0
 /// <summary>
 /// Возвращает сообщения из истории переписки внутри одного диалога.
 /// </summary>
 /// <param name="seqNo"></param>
 /// <param name="peerBase">     Пользователь или чат, истории переписки с которым интересует</param>
 /// <param name="offset">   Количество элементов списка, которое необходимо пропустить</param>
 /// <param name="maxId">    Если передано положительное значение, метод вернет только сообщения с идентификаторами меньше заданного</param>
 /// <param name="limit">    Количество элементов списка, которое необходимо вернуть</param>
 /// <returns></returns>
 private static TLResponse SendGetHistoryRequest(int seqNo, TLInputPeerBase peerBase, TLInt offset, TLInt maxId, TLInt limit)
 {
     return(RequestHelper.Send("messages.getHistory", seqNo, () => ComposeGetHistoryRequest(peerBase, offset, maxId, limit)));
 }