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, StateService.CurrentUserId);

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

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

            return(message);
        }
Esempio n. 2
0
        public void SendRequestAsync <T>(string caption, TLObject obj, int dcId, bool cdn, Action <T> callback, Action <TLRPCError> faultCallback = null)
        {
            Debug.WriteLine("Sending " + caption);

            var flags = RequestFlag.ForceDownload | RequestFlag.FailOnServerError;

            if (cdn)
            {
                flags |= RequestFlag.EnableUnauthorized;
            }

            try
            {
                var messageToken = _connectionManager.SendRequest(obj, (message, ex) =>
                {
                    if (message.Object is TLRPCError error)
                    {
                        faultCallback?.Invoke(error);
                    }
                    else if (message.Object is TLUnparsedObject unparsed)
                    {
                        callback?.Invoke(TLFactory.Read <T>(unparsed.Reader, unparsed.Constructor));
                    }
                    else
                    {
                        callback?.Invoke((T)(object)message.Object);
                    }
                },
                                                                  null, dcId, ConnectionType.Download, flags);
            }
            catch { }
        }
Esempio n. 3
0
 public UploadableItem(TLLong fileId, TLObject owner, string isoFileName, long isoFileLength)
 {
     FileId        = fileId;
     Owner         = owner;
     IsoFileName   = isoFileName;
     IsoFileLength = isoFileLength;
 }
        private UploadableItem GetUploadableItem(TLLong fileId, TLObject owner, string fileName, long fileLength, IList <UploadablePart> parts)
        {
            var item = new UploadableItem(fileId, owner, fileName, fileLength);

            item.Parts = GetItemParts(item, fileLength, parts);
            return(item);
        }
Esempio n. 5
0
        public override void OnSend(BinaryWriter writer)
        {
            writer.Write(requestCode);

            TLObject.WriteVector(writer, contacts);
            Serializers.Bool.Write(writer, replace);
        }
        public ChooseAttachmentViewModel(TLObject with,
                                         Action <TLUserBase> openInlineBotAction,
                                         Action <StorageFile> sendDocumentAction,
                                         Action <StorageFile> sendVideoAction,
                                         Action <IReadOnlyList <StorageFile> > sendPhotosAction,
                                         System.Action sendLocationAction,
                                         System.Action sendContactAction,
                                         ICacheService cacheService, ITelegramEventAggregator eventAggregator, INavigationService navigationService, IStateService stateService, bool contactEnabled = true)
        {
            InlineBots = new ObservableCollection <TLUserBase>();

            _with = with;
            _openInlineBotAction = openInlineBotAction;
            _sendDocumentAction  = sendDocumentAction;
            _sendVideoAction     = sendVideoAction;
            _sendPhotosAction    = sendPhotosAction;
            _sendLocationAction  = sendLocationAction;
            _sendContactAction   = sendContactAction;

            _cacheService      = cacheService;
            _stateService      = stateService;
            _navigationService = navigationService;
            _eventAggregator   = eventAggregator;

            _contactEnabled = contactEnabled;
            _eventAggregator.Subscribe(this);
        }
Esempio n. 7
0
        public void DownloadFile(TLEncryptedFile file, TLObject owner)
        {
            var inputFile = new TLInputEncryptedFileLocation {
                Id = file.Id, AccessHash = file.AccessHash
            };
            var downloadableItem = GetDownloadableItem(file.DCId, inputFile, owner, file.Size);

            lock (_itemsSyncRoot)
            {
                bool addFile = true;
                foreach (var item in _items)
                {
                    if (item.InputEncryptedFileLocation.LocationEquals(inputFile))
                    {
                        addFile = false;
                        break;
                    }
                }

                if (addFile)
                {
                    _items.Add(downloadableItem);
                }
            }

            StartAwaitingWorkers();
        }
Esempio n. 8
0
        private UploadableItem GetUploadableItem(long fileId, TLObject owner, string isoFileName, long isoFileLength)
        {
            var item = new UploadableItem(fileId, owner, isoFileName, isoFileLength);

            item.Parts = GetItemParts(item, isoFileLength);
            return(item);
        }
Esempio n. 9
0
        private void DeleteMessagesInternal(TLObject owner, TLMessageBase lastMessage, IList <TLMessageBase> messages)
        {
            var ids = new TLVector <TLInt>();

            for (int i = 0; i < messages.Count; i++)
            {
                ids.Add(messages[i].Id);
            }

            // duplicate: deleting performed through updates
            CacheService.DeleteMessages(ids);

            BeginOnUIThread(() =>
            {
                for (var i = 0; i < messages.Count; i++)
                {
                    for (var j = 0; j < Items.Count; j++)
                    {
                        var dialog = Items[j] as TLDialog;
                        if (dialog != null &&
                            dialog.TopMessage != null &&
                            dialog.TopMessage.Id.Value == messages[i].Index)
                        {
                            Items.RemoveAt(j);
                            break;
                        }
                    }
                }
            });

            EventAggregator.Publish(new DeleteMessagesEventArgs {
                Owner = owner, Messages = messages
            });
        }
Esempio n. 10
0
        public EditVideoViewModel(Action <CompressingVideoFile> sendVideoAction, Func <string, IList <TLUserBase> > getUsernameHints, TLObject with)
        {
            _with             = with;
            _getUsernameHints = getUsernameHints;
            _sendVideoAction  = sendVideoAction;

            PropertyChanged += (sender, args) =>
            {
                if (Property.NameEquals(args.PropertyName, () => SelectedQuality))
                {
                    UpdateEditedVideoParameters();

                    NotifyOfPropertyChange(() => EditedVideoParameters);
                }
                else if (Property.NameEquals(args.PropertyName, () => IsMuteEnabled))
                {
                    UpdateEditedVideoParameters();

                    NotifyOfPropertyChange(() => EditedVideoParameters);
                }
                else if (Property.NameEquals(args.PropertyName, () => Caption))
                {
                    LoadMentionHints(Caption);
                }
            };
        }
Esempio n. 11
0
        public override void OnSend(BinaryWriter writer)
        {
            writer.Write(requestCode);

            TLObject.WriteVector(writer, messages, writer.Write);
            writer.Write(pts);
        }
        private void SendDocumentInternal(StorageFile storageFile, TLObject obj)
        {
            var message = GetDecryptedMessage(obj);

            if (message == null)
            {
                return;
            }

            var media = message.Media as TLDecryptedMessageMediaDocument;

            if (media == null)
            {
                return;
            }

            var file = media.File as TLEncryptedFile;

            if (file == null)
            {
                return;
            }

            UploadDocumentFileManager.UploadFile(file.Id, obj, storageFile, media.Key, media.IV);
        }
Esempio n. 13
0
        public void DownloadFile(TLFileLocation file, TLObject owner, TLInt fileSize)
        {
            var downloadableItem = GetDownloadableItem(file, owner, fileSize);

            lock (_itemsSyncRoot)
            {
                bool addFile = true;
                foreach (var item in _items)
                {
                    if (item.Location.VolumeId.Value == file.VolumeId.Value &&
                        item.Location.LocalId.Value == file.LocalId.Value &&
                        item.Owner == owner)
                    {
                        addFile = false;
                        break;
                    }
                }

                if (addFile)
                {
                    _items.Add(downloadableItem);
                }
            }

            StartAwaitingWorkers();
        }
Esempio n. 14
0
        /// <summary>
        /// Attempts to handle the message on our side in the case it's a backend update
        /// </summary>
        /// <param name="Message">The update in question</param>
        /// <returns>True if the message was handled.  Otherwise, false.</returns>
        private async Task <bool> ProcessUpdate(TLObject Message)
        {
            Logger.Log(Logger.Level.Info, $"Beginning internal update processing of \"{(string)Message["body"]["_"]}\"");

            try
            {
                if (((int)Message["seqno"] & 0x01) != 0)
                {
                    Logger.Log(Logger.Level.Debug, $"Adding \"{(long)Message["msg_id"]}\" to be acked");
                    PendingAcks.Add((long)Message["msg_id"]);
                }

                var args = new object[] { this, new TLObjectEventArgs(new TLObject(Message["body"])) };
                UpdateReceivedEvent.RaiseEventSafe(ref args);

                return((Message["body"].Value <string>("_")) switch
                {
                    "bad_server_salt" => ProcessBadSalt(Message),
                    "bad_msg_notification" => ProcessBadMsgNotification(Message),
                    "future_salts" => ProcessFutureSalts(Message),
                    "gzip_packed" => await ProcessGzipPacked(Message),
                    "msg_container" => ProcessMessageContainer(Message),
                    "msg_detailed_info" => ProcessMessageDetailedInfo(Message),
                    "msg_new_detailed_info" => ProcessNewMessageDetailedInfo(Message),
                    "msg_resend_req" => ProcessMessageResendRequest(Message),
                    "msgs_ack" => ProcessMessageAck(Message),
                    "msgs_all_info" => ProcessMessageInfoAll(Message),
                    "msgs_state_req" => ProcessMessageStateReqest(Message),
                    "new_session_created" => ProcessNewSessionCreated(Message),
                    "pong" => ProcessPong(Message),
                    "rpc_result" => await ProcessRPCResult(Message),
                    _ => true,
                });
            }
Esempio n. 15
0
        private UploadableItem GetUploadableItem(long fileId, TLObject owner, byte[] bytes)
        {
            var item = new UploadableItem(fileId, owner, bytes);

            item.Parts = GetItemParts(item);
            return(item);
        }
Esempio n. 16
0
        /// <summary>
        /// Sends a request to the server asynchronously.  This method will either return the response (if applicable) or throw an exception (if applicable)
        /// </summary>
        /// <param name="request">The request to send to the server.</param>
        /// <returns>A Task that must be awaited to get a response.</returns>
        public Task <TLObject> Send(TLObject request)
        {
            // If we aren't even connected, there's no point in trying
            if (!CommunicationEstablished)
            {
                var sad = new RequestFailedException("Failed to send a request to the server because we are not connected", request);
                Logger.Log(sad);
                throw sad;
            }

            // Wrap the individual request in preparation to send
            var state = new RequestState(request);

            // Add to the send queue.
            SendQueue.Add(state);

            // Run un-awaited so as to let it process in the background.
            // This will take any and all messages out of the queue above
            // package them together in a container (if applicable) and
            // send to the server
            Task.Run(async() =>
            {
                Logger.Log(Logger.Level.Debug, "Starting send process");
                await ProcessSendQueue();
            });

            // Return the task associated with the request state.
            // When a response is received, the Task will
            // be resolved and the response returned
            return(state.Response.Task);
        }
Esempio n. 17
0
        public void UploadFile(long fileId, TLObject owner, string fileName, bool forceBigFile)
        {
            long fileLength = FileUtils.GetLocalFileLength(fileName);

            if (fileLength <= 0)
            {
                return;
            }

            var item = GetUploadableItem(fileId, owner, fileName, fileLength);

            var uploadedCount = item.Parts.Count(x => x.Status == PartStatus.Processed);
            var count         = item.Parts.Count;
            var isComplete    = uploadedCount == count;

            if (isComplete)
            {
                Execute.BeginOnThreadPool(() => _eventAggregator.Publish(item));
            }
            else
            {
                lock (_itemsSyncRoot)
                {
                    _items.Add(item);
                }

                StartAwaitingWorkers();
            }
        }
        public static void SendEncryptedService(TLEncryptedChat chat, TLObject obj, IMTProtoService mtProtoService, ICacheService cacheService, Action <TLSentEncryptedMessage> callbak)
        {
            var message = GetDecryptedServiceMessage(obj);

            if (message == null)
            {
                return;
            }

            cacheService.SyncDecryptedMessage(message, chat,
                                              cachedMessage =>
            {
                mtProtoService.SendEncryptedServiceAsync(new TLInputEncryptedChat {
                    AccessHash = chat.AccessHash, ChatId = chat.Id
                }, message.RandomId, TLUtils.EncryptMessage(obj, chat),
                                                         result =>
                {
                    callbak.SafeInvoke(result);

                    message.Status = MessageStatus.Confirmed;
                    message.NotifyOfPropertyChange(() => message.Status);

                    cacheService.SyncSendingDecryptedMessage(chat.Id, result.Date, message.RandomId, m => { });
                },
                                                         error =>
                {
                    message.Status = MessageStatus.Failed;
                    message.NotifyOfPropertyChange(() => message.Status);

                    Execute.ShowDebugMessage("messages.sendServiceEncrypted error " + error);
                });
            });
        }
        public static bool IsRequired(TLObject obj)
        {
            var userBase = obj as TLUserBase;

            return
                (userBase is TLUserRequest &&
                 !userBase.RemoveUserAction && userBase.Index != 777000);
        }
Esempio n. 20
0
 public static string ToJsonString(this TLObject obj, bool indented = false, bool escapeString = false)
 {
     using var buffer = new ArrayPoolBufferWriter <byte>(512);
     using var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = indented, Encoder = escapeString ? null : notEscapingEncoder });
     writer.WriteTLObjectValue(obj);
     writer.Flush();
     return(Encoding.UTF8.GetString(buffer.WrittenSpan));
 }
Esempio n. 21
0
 internal static BaseConverter GetConverterForTLObject(TLObject obj)
 {
     if (_rtti_map.TryGetValue(obj.GetType(), out var conv))
     {
         return(conv);
     }
     throw new ArgumentException($"unknown type {obj.GetType()}");
 }
        public MultiImageEditorViewModel(Action <IReadOnlyList <StorageFile> > sendPhotosAction, Func <string, IList <TLUserBase> > getUsernameHints, TLObject with)
        {
            _with             = with;
            _sendPhotosAction = sendPhotosAction;
            _getUsernameHints = getUsernameHints;

            Items = new ObservableCollection <PhotoFile>();
        }
        private UploadableItem GetUploadableItem(TLLong fileId, TLObject owner, string fileName, long fileLength)
        {
            FileUtils.SwitchIdleDetectionMode(false);

            var item = new UploadableItem(fileId, owner, fileName, fileLength);
            item.Parts = GetItemParts(item, fileLength);
            return item;
        }
Esempio n. 24
0
        /// <summary>
        /// Computes v based on the following:
        ///
        /// v = pow(g, PH2(password, salt1, salt2)) mod p
        /// </summary>
        /// <param name="algo">The TLObject from account.getPassword["current_algo"]</param>
        /// <param name="password">The cloud password that the user provided</param>
        public static byte[] DigestPasswordHash(TLObject algo, string password)
        {
            var g   = new BigInteger(algo["g"].ToString());
            var PH2 = new BigInteger(1, PasswordHash(algo, password));
            var p   = new BigInteger(1, (byte[])algo["p"]);

            return(NumBytesForHash(g.ModPow(PH2, p).ToByteArrayUnsigned()));
        }
Esempio n. 25
0
        private void RemoveActionInfoFromFile(TLObject obj)
        {
            var actions = GetActionInfoFromFile();

            RemoveActionInfoCommon(actions, obj);

            SaveActionInfoToFile(actions);
        }
Esempio n. 26
0
 private void SendInformativeMessage <T>(string caption, TLObject obj, Action <T> callback, Action <TLRPCError> faultCallback = null,
                                         int?maxAttempt             = null, // to send delayed items
                                         Action <int> attemptFailed = null) // to send delayed items
 {
     Execute.BeginOnThreadPool(() =>
     {
         SendInformativeMessageInternal(caption, obj, callback, faultCallback, maxAttempt, attemptFailed);
     });
 }
Esempio n. 27
0
        public override TLObject FromBytes(byte[] bytes, ref int position)
        {
            bytes.ThrowExceptionIfIncorrect(ref position, Signature);

            RequestMessageId = GetObject <TLLong>(bytes, ref position);
            Object           = GetObject <TLObject>(bytes, ref position);

            return(this);
        }
        public UploadableItem(TLLong fileId, TLObject owner, StorageFile file, TLString key, TLString iv)
        {
            FileId = fileId;
            Owner  = owner;
            File   = file;

            Key = key;
            IV  = iv;
        }
Esempio n. 29
0
        public static bool IsRequired(TLObject obj)
        {
            var userBase = obj as TLUserBase;

            return
                (userBase != null &&
                 userBase.IsRequest &&
                 !userBase.RemoveUserAction && userBase.Index != Constants.TelegramNotificationsId);
        }
Esempio n. 30
0
        // return big-endian authKey
        public static byte[] GetAuthKey(byte[] bBytes, byte[] g_aData, byte[] dhPrimeData)
        {
            int position = 0;
            var b        = new BigInteger(bBytes.Reverse().Concat(new byte[] { 0x00 }).ToArray());
            var dhPrime  = TLObject.GetObject <TLString>(dhPrimeData, ref position).ToBigInteger();

            position = 0;
            var g_a = TLObject.GetObject <TLString>(g_aData, ref position).ToBigInteger();

            var authKey = BigInteger.ModPow(g_a, b, dhPrime).ToByteArray(); // little endian + (may be) zero last byte

            //remove last zero byte
            if (authKey[authKey.Length - 1] == 0x00)
            {
                authKey = authKey.SubArray(0, authKey.Length - 1);
            }

            authKey = authKey.Reverse().ToArray();

            if (authKey.Length > 256)
            {
#if DEBUG
                var authKeyInfo = new StringBuilder();
                authKeyInfo.AppendLine("auth_key length > 256: " + authKey.Length);
                authKeyInfo.AppendLine("g_a=" + g_a);
                authKeyInfo.AppendLine("b=" + b);
                authKeyInfo.AppendLine("dhPrime=" + dhPrime);
                Execute.ShowDebugMessage(authKeyInfo.ToString());
#endif

                var correctedAuth = new byte[256];
                Array.Copy(authKey, authKey.Length - 256, correctedAuth, 0, 256);
                authKey = correctedAuth;
            }
            else if (authKey.Length < 256)
            {
#if DEBUG
                var authKeyInfo = new StringBuilder();
                authKeyInfo.AppendLine("auth_key length < 256: " + authKey.Length);
                authKeyInfo.AppendLine("g_a=" + g_a);
                authKeyInfo.AppendLine("b=" + b);
                authKeyInfo.AppendLine("dhPrime=" + dhPrime);
                Execute.ShowDebugMessage(authKeyInfo.ToString());
#endif

                var correctedAuth = new byte[256];
                Array.Copy(authKey, 0, correctedAuth, 256 - authKey.Length, authKey.Length);
                for (var i = 0; i < 256 - authKey.Length; i++)
                {
                    authKey[i] = 0;
                }
                authKey = correctedAuth;
            }

            return(authKey);
        }
Esempio n. 31
0
 /**
  * Writing tl-object to stream
  *
  * @param v      tl-object
  * @param stream destination stream
  * @throws IOException
  */
 public static void writeTLObject(TLObject v, /*OutputStream*/ StreamWriter stream)
 {
     try {
         v.serialize(stream);
     } catch (IOException e) {
         System.Diagnostics.Debug.WriteLine(e.StackTrace);
         throw e;
     }
 }
Esempio n. 32
0
 /**
  * Writing tl-vector to stream
  *
  * @param v      tl-vector
  * @param stream destination stream
  * @throws IOException
  */
 public static void writeTLVector(/*TLVector*/TLObject v, /*OutputStream*/ StreamWriter stream)
 {
     try {
         writeTLObject(v, stream);
     } catch(IOException e) {
         System.Diagnostics.Debug.WriteLine(e.StackTrace);
         throw e;
     }
 }
Esempio n. 33
0
 public ExpressionValue( TLObject value )
 {
     Value = value;
 }
Esempio n. 34
0
 public void Declare( String identifier, TLObject value )
 {
     myVariables.Add( identifier, value );
 }