Пример #1
0
        async Task RealtimeSub()
        {
            var user = _instaApi.GetLoggedUser().LoggedInUser;
            var dic  = new Dictionary <string, List <string> >
            {
                { "sub",
                  new List <string>
                  {
                      GraphQLSubscriptions.GetAppPresenceSubscription(),
                GraphQLSubscriptions.GetZeroProvisionSubscription(_instaApi.GetCurrentDevice().DeviceGuid.ToString()),
                      GraphQLSubscriptions.GetDirectStatusSubscription(),
                      GraphQLSubscriptions.GetDirectTypingSubscription(user?.Pk.ToString()),
                      GraphQLSubscriptions.GetAsyncAdSubscription(user?.Pk.ToString())
                  } }
            };
            var json       = JsonConvert.SerializeObject(dic);
            var bytes      = Encoding.UTF8.GetBytes(json);
            var dataStream = new MemoryStream(512);

            using (var zlibStream = new ZlibStream(dataStream, CompressionMode.Compress, CompressionLevel.Level9, true))
            {
                await zlibStream.WriteAsync(bytes, 0, bytes.Length);
            }

            var compressed    = dataStream.GetWindowsRuntimeBuffer(0, (int)dataStream.Length);
            var publishPacket = new PublishPacket(QualityOfService.AtLeastOnce, false, false)
            {
                Payload   = compressed,
                PacketId  = (ushort)CryptographicBuffer.GenerateRandomNumber(),
                TopicName = "/ig_realtime_sub"
            };
            await FbnsPacketEncoder.EncodePacket(publishPacket, _outboundWriter);
        }
Пример #2
0
        //private async Task RegisterClient(string token)
        //{
        //    if (string.IsNullOrEmpty(token)) throw new ArgumentNullException(nameof(token));
        //    if (ConnectionData.FbnsToken == token)
        //    {
        //        ConnectionData.FbnsToken = token;
        //        return;
        //    }

        //    var uri = new Uri("https://i.instagram.com/api/v1/push/register/");
        //    var fields = new Dictionary<string, string>
        //    {
        //        {"device_type", "android_mqtt"},
        //        {"is_main_push_channel", "true"},
        //        {"phone_id", _device.PhoneId.ToString()},
        //        {"device_sub_type", "2" },
        //        {"device_token", token},
        //        {"_csrftoken", _user.CsrfToken },
        //        {"guid", _device.Uuid.ToString() },
        //        {"_uuid", _device.Uuid.ToString() },
        //        {"users", _user.LoggedInUser.Pk.ToString() }
        //    };
        //    var result = await _instaApi.PostAsync(uri, new HttpFormUrlEncodedContent(fields));

        //    ConnectionData.FbnsToken = token;
        //}
        internal async Task RegisterClient(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }
            if (ConnectionData.FbnsToken == token)
            {
                ConnectionData.FbnsToken = token;
                return;
            }
            var deviceInfo = _instaApi.GetCurrentDevice();
            var user       = _instaApi.GetLoggedUser();
            var uri        = InstagramApiSharp.Helpers.UriCreator.GetPushRegisterUri();
            var users      = ApiList.Select(s => s.GetLoggedUser().LoggedInUser.Pk);
            var fields     = new Dictionary <string, string>
            {
                { "device_type", "android_mqtt" },
                { "is_main_push_channel", "true" },
                { "phone_id", deviceInfo.PhoneGuid.ToString() },
                { "device_token", token },
                { "_csrftoken", user.CsrfToken },
                { "guid", deviceInfo.PhoneGuid.ToString() },
                { "_uuid", deviceInfo.DeviceGuid.ToString() },
                { "users", string.Join(",", users) /*user.LoggedInUser.Pk.ToString()*/ }
            };

            var request  = _instaApi.HttpHelper.GetDefaultRequest(System.Net.Http.HttpMethod.Post, uri, deviceInfo, fields);
            var response = await _instaApi.HttpRequestProcessor.SendAsync(request);

            Debug.WriteLine(await response.Content.ReadAsStringAsync());

            ConnectionData.FbnsToken = token;
        }
Пример #3
0
        internal async Task RegisterClient(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException(nameof(token));
            }
            //var tokenChanged = false;
            //var a = DateTime.UtcNow.ToUnixTime().FromUnixTimeSeconds() - ConnectionData.FbnsTokenUpdatedAt.FromUnixTimeSeconds();
            //if ((a).TotalHours <= 24 && !string.IsNullOrEmpty(ConnectionData.FbnsToken))
            //{
            //    //token = ConnectionData.FbnsToken;
            //}
            //else
            //    tokenChanged = true;
            var deviceInfo = _instaApi.GetCurrentDevice();
            var user       = _instaApi.GetLoggedUser();
            var uri        = UriCreator.GetPushRegisterUri();
            var users      = ApiList.Select(s => s.GetLoggedUser().LoggedInUser.Pk).ToList();

            if (!ApiList.Any(x => x.GetCurrentDevice().DeviceGuid.ToString() != deviceInfo.DeviceGuid.ToString()))
            {
                users.Clear();
                users.Add(user.LoggedInUser.Pk);
            }

            var fields = new Dictionary <string, string>
            {
                { "device_type", "android_mqtt" },
                { "is_main_push_channel", "true" },
                { "phone_id", deviceInfo.PhoneGuid.ToString() },
                { "device_token", token },
                { "_csrftoken", user.CsrfToken },
                { "guid", deviceInfo.PhoneGuid.ToString() },
                { "_uuid", deviceInfo.DeviceGuid.ToString() },
                { "users", string.Join(",", users) /*user.LoggedInUser.Pk.ToString()*/ }
            };

            Debug.WriteLine(JsonConvert.SerializeObject(fields, Formatting.Indented));
            var request  = _instaApi.HttpHelper.GetDefaultRequest(System.Net.Http.HttpMethod.Post, uri, deviceInfo, fields);
            var response = await _instaApi.HttpRequestProcessor.SendAsync(request);

            Debug.WriteLine(await response.Content.ReadAsStringAsync());

            ConnectionData.FbnsToken = token;

            //if (tokenChanged)
            {
                ConnectionData.FbnsTokenUpdatedAt = DateTime.UtcNow.ToUnixTime();
                FbnsTokenChanged?.Invoke(this, "FbnsToken");
            }
        }
Пример #4
0
        private static async Task <byte[]> ToThrift()
        {
            var device    = InstaApi.GetCurrentDevice();
            var cookies   = InstaApi.HttpRequestProcessor.HttpHandler.CookieContainer.GetCookies(InstaApi.HttpRequestProcessor.Client.BaseAddress);
            var sessionId = cookies["sessionid"]?.Value ?? string.Empty;

            await WriteString(CLIENT_ID, device.DeviceGuid.ToString().Substring(0, 20));

            #region Write struct ClientInfo
            await WriteStructBegin(CLIENT_INFO);
            await WriteInt64(USER_ID, InstaApi.GetLoggedUser().LoggedInUser.Pk);
            await WriteString(USER_AGENT, FbnsUserAgent.BuildFbUserAgent(InstaApi));
            await WriteInt64(CLIENT_CAPABILITIES, 183);
            await WriteInt64(ENDPOINT_CAPABILITIES, _payloadData.EndpointCapabilities);
            await WriteInt32(PUBLISH_FORMAT, _payloadData.PublishFormat);
            await WriteBool(NO_AUTOMATIC_FOREGROUND, _payloadData.NoAutomaticForeground);
            await WriteBool(MAKE_USER_AVAILABLE_IN_FOREGROUND, _payloadData.MakeUserAvailableInForeground);
            await WriteString(DEVICE_ID, device.DeviceGuid.ToString());
            await WriteBool(IS_INITIALLY_FOREGROUND, _payloadData.IsInitiallyForeground);
            await WriteInt32(NETWORK_TYPE, _payloadData.NetworkType);
            await WriteInt32(NETWORK_SUBTYPE, _payloadData.NetworkSubtype);

            if (_payloadData.ClientMqttSessionId == 0)
            {
                var difference = DateTime.Today.DayOfWeek - DayOfWeek.Monday;
                var lastMonday = new DateTimeOffset(DateTime.Today.Subtract(TimeSpan.FromDays(difference > 0 ? difference : 7)));
                _payloadData.ClientMqttSessionId = DateTimeOffset.Now.ToUnixTimeMilliseconds() - lastMonday.ToUnixTimeMilliseconds();
            }

            await WriteInt64(CLIENT_MQTT_SESSION_ID, _payloadData.ClientMqttSessionId);
            await WriteListInt32(SUBSCRIBE_TOPICS, new int[] { 88, 135, 149, 150, 133, 146 });
            await WriteString(CLIENT_TYPE, "cookie_auth");
            await WriteInt64(APP_ID, 567067343352427);
            await WriteString(DEVICE_SECRET, "");
            await WriteByte(CLIENT_STACK, _payloadData.ClientStack);
            await WriteFieldStop();
            await WriteStructEnd();

            #endregion

            await WriteString(PASSWORD, $"sessionid={sessionId}");
            await WriteUsername();
            await WriteFieldStop();

            return(_memoryBufferTransport.GetBuffer());
        }
Пример #5
0
        public static string BuildRTUserAgent(IInstaApi insta)
        {
            var device = insta.GetCurrentDevice();
            var dpi    = int.Parse(device.Dpi.Replace("dpi", ""));
            var res    = device.Resolution.Split('x');
            var width  = res[0];
            var height = res[1];


            var dic = new Dictionary <string, string>
            {
                { "FBAN", "MQTT" },
                { "FBAV", insta.GetApiVersionInfo().AppVersion },
                { "FBBV", "567310203415052" /*insta.GetApiVersionInfo().AppApiVersionCode*/ },
                { "FBDM",
                  $"{{density={Math.Round(dpi/ 160f, 1):F1},width={width},height={height}}}" },
                { "FBLC", InstaApiConstants.ACCEPT_LANGUAGE.Replace("-", "_") },
                { "FBCR", "" },   // We don't have cellular
                { "FBMF", device.HardwareManufacturer },
                { "FBBD", device.HardwareManufacturer },
                { "FBPN", InstaApiConstants.INSTAGRAM_PACKAGE_NAME },
                { "FBDV", device.HardwareModel.Replace(" ", "") },
                { "FBSV", device.AndroidVer.VersionNumber },
                { "FBLR", "0" },  // android.hardware.ram.low
                { "FBBK", "1" },  // Const (at least in 10.12.0)
                { "FBCA", AndroidDevice.CPU_ABI }
            };
            var mergeList = new List <string>();

            foreach (var field in dic)
            {
                mergeList.Add($"{field.Key}/{field.Value}");
            }

            var userAgent = "";

            foreach (var field in mergeList)
            {
                userAgent += field + ';';
            }

            return('[' + userAgent + ']');
        }
Пример #6
0
        HttpRequestMessage GetRequest(ulong position)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, _requestUri);

            System.Globalization.CultureInfo currentCulture = GetCurrentCulture();
            System.Globalization.CultureInfo.CurrentCulture = EnglishCulture;

            request.Headers.Add(InstaApiConstants.HEADER_USER_AGENT, InstagramApiSharp.ExtensionHelper.GenerateUserAgent(_instaApi.GetCurrentDevice(), _instaApi.GetApiVersionInfo(), _instaApi));

            request.Headers.Add(InstaApiConstants.HEADER_ACCEPT_LANGUAGE, _instaApi.AcceptLanguage);

            request.Headers.Add(InstaApiConstants.HEADER_X_FB_HTTP_ENGINE, "Liger");

            request.Headers.Add(InstaApiConstants.HEADER_X_FB_HTTP_IP, "True");

            request.Headers.Add(InstaApiConstants.HEADER_X_FB_SERVER_CLUSTER, "True");

            request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue((long)position, null);

            if (!string.IsNullOrEmpty(_etagHeader))
            {
                request.Headers.Add("If-Match", _etagHeader);
            }

            if (!string.IsNullOrEmpty(_lastModifiedHeader))
            {
                request.Headers.Add("If-Unmodified-Since", _lastModifiedHeader);
            }

            System.Globalization.CultureInfo.CurrentCulture = currentCulture;
            return(request);
        }