Пример #1
0
        public async Task <Platform> UpdatePlatformAsync(PlatformId id, PlatformRequest platformRequest, IAsyncDocumentSession session)
        {
            var project = await session
                          .Query <Project>()
                          .Where(p => p.Platforms.Any(a => a.Id == id.Value))
                          .FirstOrDefaultAsync();

            var platform = project.Platforms?.FirstOrDefault();

            if (platform == null)
            {
                throw new ApiException("I couldn't find that platform. Are you sure it's the right token?", 404);
            }

            if (platform.ExportDataUri == platformRequest.ExportDataUri
                )
            {
                // Nothing to update
                throw new ApiException("That's the same information that I have. Great, so we agree.", 200);
            }
            platform.ExportDataUri = platformRequest.ExportDataUri;
            platform.LastUpdate    = DateTime.Now;
            // TODO: Save session changes once
            await session.SaveChangesAsync();

            return(platform);
        }
Пример #2
0
        public ActionResult Update(Guid id, PlatformRequest planUpdateRequest)
        {
            Plan plan;

            if (!Enum.TryParse <Plan>(planUpdateRequest.plan, true, out plan))
            {
                throw new ArgumentException(string.Format("Plan \"{0}\" is not a valid plan", planUpdateRequest.plan));
            }

            // TODO: Fetch the resource from persistance store
            var resource = new Resource();

            resource.Plan = plan;

            // TODO: Update resource to reflect new plan

            // TODO: Persist the resource change

            var output = new
            {
                id     = resource.Id,
                config = new
                {
                    CONFIG_VAR = "CONFIGURATION_VALUE",
                }
            };

            return(Json(output));
        }
        public async Task <IActionResult> Createplatformrequest([FromForm] PlatformViewModel platformViewModel)
        {
            if (ModelState.IsValid)
            {
                var stylesheet = new ColorScheme()
                {
                    SocialBarColor  = platformViewModel.SocialBarColor,
                    NavBarColor     = platformViewModel.NavbarColor,
                    BannerColor     = platformViewModel.BannerColor,
                    ButtonColor     = platformViewModel.ButtonColor,
                    ButtonTextColor = platformViewModel.ButtonTextColor,
                    TextColor       = platformViewModel.TextColor,
                    BodyColor       = platformViewModel.BodyColor,
                };

                var logoFileName = Util.Util.GenerateDataStoreObjectName(platformViewModel.Name);
                var logoImageObj = new Media()
                {
                    Name = logoFileName,
                    Url  = await _fileUploader.UploadFile(logoFileName, "platform-logos", platformViewModel.Logo),
                };

                var bannerFileName = Util.Util.GenerateDataStoreObjectName(platformViewModel.Name);
                var bannerImageObj = new Media()
                {
                    Name = bannerFileName,
                    Url  = await _fileUploader.UploadFile(bannerFileName, "platform-banners", platformViewModel.Banner),
                };

                var platform = new Platform()
                {
                    Name        = platformViewModel.Name,
                    Tenant      = platformViewModel.Tenant,
                    Logo        = logoImageObj,
                    Banner      = bannerImageObj,
                    Description = platformViewModel.Description,
                    ColorScheme = stylesheet,
                };

                var user            = _userManager.GetUserAsync(User).Result;
                var platformRequest = new PlatformRequest()
                {
                    Accept           = false,
                    Date             = DateTime.Now,
                    OrganisationName = user.FirmName,
                    Reason           = platformViewModel.PlatformReason,
                    Treated          = false,
                    UserId           = user.Id,
                    Platform         = platform
                };

                _platformRequestManager.CreatePlatformRequest(platformRequest);
//                _platformManager.AddPlatform(platform);
                _unitOfWorkManager.Save();
                return(Ok());
            }
            return(StatusCode(400));
        }
        /// <summary>
        /// Enrolls a new platform using HTTP POST.
        /// </summary>
        /// <param name="request">The PlatformRequest object</param>
        /// <returns>The PlatformResponse object with information of the newly created platform</returns>
        /// <exception cref="ArgumentNullException">If the PlatformRequest object is null</exception>
        /// <exception cref="TikkieErrorResponseException">If the Tikkie API returns an error response.</exception>
        public async Task <PlatformResponse> CreatePlatformAsync(PlatformRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var jsonRequest = JsonConvert.SerializeObject(request);
            var content     = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

            return(await _authorizedRequestsHandler
                   .PostOrExceptionAsync <PlatformResponse>(UrlProvider.PlatformUrlSuffix, content));
        }
Пример #5
0
        public async Task CreatePlatformAsync_ExpectedResult_VerifiesCall()
        {
            // Arrange
            var platformRequest = new PlatformRequest();
            var expectedResult  = new PlatformResponse();
            var urlSuffix       = UrlProvider.PlatformUrlSuffix;

            _mockAuthorizedRequestsHandler
            .Setup(m => m.PostOrExceptionAsync <PlatformResponse>(urlSuffix, It.IsAny <StringContent>()))
            .ReturnsAsync(expectedResult)
            .Verifiable();
            var sut = CreateSut();

            // Act
            var result = await sut.CreatePlatformAsync(platformRequest);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(expectedResult, result);
            _mockAuthorizedRequestsHandler
            .Verify(m => m.PostOrExceptionAsync <PlatformResponse>(urlSuffix, It.IsAny <StringContent>()), Times.Once);
        }
        public async Task CreatePlatformAsync_ExpectedResponse_VerifiesCall()
        {
            // Arrange
            var platformRequest             = new PlatformRequest();
            var expectedResult              = new PlatformResponse();
            var mockPlatformRequestsHandler = new Mock <IPlatformRequestsHandler>();

            mockPlatformRequestsHandler
            .Setup(m => m.CreatePlatformAsync(platformRequest))
            .ReturnsAsync(expectedResult)
            .Verifiable();

            var sut = new TikkieClient(mockPlatformRequestsHandler.Object, Mock.Of <IUserRequestsHandler>(), Mock.Of <IPaymentRequestsHandler>());

            // Act
            var result = await sut.CreatePlatformAsync(platformRequest);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(expectedResult, result);
            mockPlatformRequestsHandler
            .Verify(m => m.CreatePlatformAsync(platformRequest), Times.Once);
        }
Пример #7
0
        //public uint RequestCount { get; private set; } = 1;

        //private readonly Random _random = new Random(Environment.TickCount);

        /*
         * private long PositiveRandom()
         * {
         *  long ret = _random.Next() | (_random.Next() << 32);
         *  // lrand48 ensures it's never < 0
         *  // So do the same
         *  if (ret < 0)
         *      ret = -ret;
         *  return ret;
         * }
         *
         * private void IncrementRequestCount()
         * {
         *  // Request counts on android jump more than 1 at a time according to logs
         *  // They are fully sequential on iOS though
         *  // So mimic that same behavior here.
         *  if (_client.Platform == Platform.Android)
         *      RequestCount += (uint)_random.Next(2, 15);
         *  else if (_client.Platform == Platform.Ios)
         *      RequestCount++;
         * }
         *
         * private ulong GetNextRequestId()
         * {
         *  if (RequestCount == 1)
         *  {
         *      IncrementRequestCount();
         *      if (_client.Platform == Platform.Android)
         *      {
         *          // lrand48 is "broken" in that the first run of it will return a static value.
         *          // So the first time we send a request, we need to match that initial value.
         *          // Note: On android srand(4) is called in .init_array which seeds the initial value.
         *          return 0x53B77E48000000B0;
         *      }
         *      if (_client.Platform == Platform.Ios)
         *      {
         *          // Same as lrand48, iOS uses "rand()" without a pre-seed which always gives the same first value.
         *          return 0x41A700000002;
         *      }
         *  }
         *
         *  // Note that the API expects a "positive" random value here. (At least on Android it does due to lrand48 implementation details)
         *  // So we'll just use the same for iOS since it doesn't hurt, and means less code required.
         *  ulong r = (((ulong)PositiveRandom() | ((RequestCount + 1) >> 31)) << 32) | (RequestCount + 1);
         *  IncrementRequestCount();
         *  return r;
         * }
         */

        //private RequestEnvelope.Types.PlatformRequest GenerateSignature(IEnumerable<IMessage> requests)
        /// <summary>
        /// EB Check IMessage
        /// </summary>
        /// <param name="requestEnvelope"></param>
        /// <returns></returns>
        /// Also pogolib does
        /// internal async Task<PlatformRequest> GenerateSignatureAsync(RequestEnvelope requestEnvelope)
        private RequestEnvelope.Types.PlatformRequest GenerateSignature(RequestEnvelope requestEnvelope)
        {
            var timestampSinceStart = (long)(Utils.GetTime(true) - _client.StartTime);
            var locationFixes       = BuildLocationFixes(requestEnvelope, timestampSinceStart);

            requestEnvelope.Accuracy = locationFixes[0].Altitude;
            requestEnvelope.MsSinceLastLocationfix = (long)locationFixes[0].TimestampSnapshot;

            #region GenerateSignature
            var signature = new Signature
            {
                TimestampSinceStart = (ulong)timestampSinceStart,
                Timestamp           = (ulong)Utils.GetTime(true), // true means in Ms

                SensorInfo =
                {
                    new SensorInfo
                    {
                        // Values are not the same used in PogoLib
                        TimestampSnapshot   = (ulong)(timestampSinceStart + RandomDevice.Next(100, 250)),
                        LinearAccelerationX = GenRandom(0.12271042913198471),
                        LinearAccelerationY = GenRandom(-0.015570580959320068),
                        LinearAccelerationZ = GenRandom(0.010850906372070313),
                        RotationRateX       = GenRandom(-0.0120010357350111),
                        RotationRateY       = GenRandom(-0.04214850440621376),
                        RotationRateZ       = GenRandom(0.94571763277053833),
                        AttitudePitch       = GenRandom(-47.149471283, 61.8397789001),
                        AttitudeYaw         = GenRandom(-47.149471283, 61.8397789001),
                        AttitudeRoll        = GenRandom(-47.149471283, 5),
                        GravityZ            = GenRandom(9.8),
                        GravityX            = GenRandom(0.02),
                        GravityY            = GenRandom(0.3),

/*                        MagneticFieldX = GenRandom(17.950439453125),
 *                      MagneticFieldY = GenRandom(-23.36273193359375),
 *                      MagneticFieldZ = GenRandom(-48.8250732421875),*/
                        MagneticFieldAccuracy = -1,
                        Status = 3
                    }
                },
                DeviceInfo     = _DeviceInfo,// dInfo,
                LocationFix    = { locationFixes },
                ActivityStatus = new ActivityStatus
                {
                    Stationary = true
                }
            };
            #endregion

            signature.SessionHash = _sessionHash;
            signature.Unknown25   = Resources.Unknown25;

            var serializedTicket = requestEnvelope.AuthTicket != null?requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray();

            var locationBytes = BitConverter.GetBytes(_latitude).Reverse()
                                .Concat(BitConverter.GetBytes(_longitude).Reverse())
                                .Concat(BitConverter.GetBytes(locationFixes[0].Altitude).Reverse()).ToArray();

            var requestsBytes = requestEnvelope.Requests.Select(x => x.ToByteArray()).ToArray();

            HashRequestContent hashRequest = new HashRequestContent()
            {
                Timestamp   = signature.Timestamp,
                Latitude    = requestEnvelope.Latitude,
                Longitude   = requestEnvelope.Longitude,
                Altitude    = requestEnvelope.Accuracy,
                AuthTicket  = serializedTicket,
                SessionData = signature.SessionHash.ToByteArray(),
                Requests    = new List <byte[]>(requestsBytes)
            };

            HashResponseContent responseContent;

            responseContent = _client.Hasher.RequestHashes(hashRequest);

            signature.LocationHash1 = unchecked ((int)responseContent.LocationAuthHash);
            signature.LocationHash2 = unchecked ((int)responseContent.LocationHash);
            signature.RequestHash.AddRange(responseContent.RequestHashes.Select(x => (ulong)x).ToArray());

            var encryptedSignature = new PlatformRequest
            {
                Type           = PlatformRequestType.SendEncryptedSignature,
                RequestMessage = new SendEncryptedSignatureRequest
                {
                    EncryptedSignature = ByteString.CopyFrom(PCryptPokeHash.Encrypt(signature.ToByteArray(), (uint)timestampSinceStart))
                }.ToByteString()
            };

            return(encryptedSignature);
        }
Пример #8
0
        public ActionResult Update(Guid id, PlatformRequest planUpdateRequest)
        {
            Plan plan;
            if (!Enum.TryParse<Plan>(planUpdateRequest.plan, true, out plan))
            {
                throw new ArgumentException(string.Format("Plan \"{0}\" is not a valid plan", planUpdateRequest.plan));
            }

            // TODO: Fetch the resource from persistance store
            var resource = new Resource();

            resource.Plan = plan;

            // TODO: Update resource to reflect new plan

            // TODO: Persist the resource change

            var output = new
            {
                id = resource.Id,
                config = new
                {
                    CONFIG_VAR = "CONFIGURATION_VALUE",
                }
            };

            return Json(output);
        }
Пример #9
0
        /// <summary>
        /// Generates the encrypted signature which is required for the <see cref="RequestEnvelope"/>.
        /// </summary>
        /// <returns>The encrypted <see cref="PlatformRequest"/>.</returns>
        internal async Task <PlatformRequest> GenerateSignatureAsync(RequestEnvelope requestEnvelope)
        {
            if (Configuration.Hasher == null)
            {
                throw new NullReferenceException($"{nameof(Configuration.Hasher)} is not set, which is required to send valid calls to PokemonGo.");
            }

            var timestampSinceStart = TimestampSinceStartMs;
            var locationFixes       = BuildLocationFixes(requestEnvelope, timestampSinceStart);
            var locationFix         = locationFixes.Last();

            _session.Player.Coordinate.HorizontalAccuracy = locationFix.HorizontalAccuracy;
            _session.Player.Coordinate.VerticalAccuracy   = locationFix.VerticalAccuracy;
            _session.Player.Coordinate.Altitude           = locationFix.Altitude;

            requestEnvelope.Accuracy = _session.Player.Coordinate.Altitude; // _session.Player.Coordinate.HorizontalAccuracy;
            requestEnvelope.MsSinceLastLocationfix = timestampSinceStart - (long)locationFix.TimestampSnapshot;

            var signature = new Signature
            {
                TimestampSinceStart = (ulong)timestampSinceStart,
                Timestamp           = (ulong)TimeUtil.GetCurrentTimestampInMilliseconds(),
                SensorInfo          =
                {
                    new SensorInfo
                    {
                        TimestampSnapshot     = (ulong)(timestampSinceStart + _session.Random.Next(100, 250)),
                        LinearAccelerationX   = -0.7 + _session.Random.NextDouble() * 1.4,
                        LinearAccelerationY   = -0.7 + _session.Random.NextDouble() * 1.4,
                        LinearAccelerationZ   = -0.7 + _session.Random.NextDouble() * 1.4,
                        RotationRateX         = 0.7 * _session.Random.NextDouble(),
                        RotationRateY         = 0.8 * _session.Random.NextDouble(),
                        RotationRateZ         = 0.8 * _session.Random.NextDouble(),
                        AttitudePitch         = -1.0 + _session.Random.NextDouble() * 2.0,
                        AttitudeRoll          = -1.0 + _session.Random.NextDouble() * 2.0,
                        AttitudeYaw           = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityX              = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityY              = -1.0 + _session.Random.NextDouble() * 2.0,
                        GravityZ              = -1.0 + _session.Random.NextDouble() * 2.0,
                        MagneticFieldAccuracy = -1,
                        Status = 3
                    }
                },
                DeviceInfo     = _session.DeviceInfo,
                LocationFix    = { locationFixes },
                ActivityStatus = new ActivityStatus
                {
                    Stationary = true
                }
            };

            // Hashing
            signature.SessionHash = _sessionHash;
            signature.Unknown25   = Configuration.Hasher.Unknown25;

            var serializedTicket = requestEnvelope.AuthTicket != null?requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray();

            var locationBytes = BitConverter.GetBytes(_session.Player.Coordinate.Latitude).Reverse()
                                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Longitude).Reverse())
                                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Altitude).Reverse()).ToArray();

            var requestsBytes = requestEnvelope.Requests.Select(x => x.ToByteArray()).ToArray();
            var hashData      = await Configuration.Hasher.GetHashDataAsync(requestEnvelope, signature, locationBytes, requestsBytes, serializedTicket);

            signature.LocationHash1 = (int)hashData.LocationAuthHash;
            signature.LocationHash2 = (int)hashData.LocationHash;

            signature.RequestHash.AddRange(hashData.RequestHashes);

            var encryptedSignature = new PlatformRequest
            {
                Type           = PlatformRequestType.SendEncryptedSignature,
                RequestMessage = new SendEncryptedSignatureRequest
                {
                    EncryptedSignature = ByteString.CopyFrom(Configuration.Hasher.GetEncryptedSignature(signature.ToByteArray(), (uint)timestampSinceStart))
                }.ToByteString()
            };

            return(encryptedSignature);
        }
Пример #10
0
 /// <summary>
 /// Enrolls a new platform using HTTP POST.
 /// </summary>
 /// <param name="request">The PlatformRequest object</param>
 /// <returns>The PlatformResponse object with information of the newly created platform</returns>
 /// <exception cref="ArgumentNullException">If the PlatformRequest object is null</exception>
 /// <exception cref="TikkieErrorResponseException">If the Tikkie API returns an error response.</exception>
 public async Task <PlatformResponse> CreatePlatformAsync(PlatformRequest request)
 {
     return(await _platformRequestsHandler.CreatePlatformAsync(request));
 }
 public async Task <Core.Entities.Platform> UpdatePlatform([FromRoute] PlatformId id, [FromBody] PlatformRequest platformRequest)
 {
     using var session = _documentStore.OpenAsyncSession();
     return(await _platformManager.UpdatePlatformAsync(id, platformRequest, session));
 }
Пример #12
0
 public void Update(PlatformRequest platformRequest)
 {
     _platformRequestRepository.Update(platformRequest);
 }
Пример #13
0
 public void CreatePlatformRequest(PlatformRequest platformRequest)
 {
     _platformRequestRepository.CreatePlatformRequest(platformRequest);
 }
Пример #14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // HttpRequest를 이용하여 PlatformRequest 생성
        PlatformRequest req = new PlatformRequest(Request.InputStream);

        // 데이터 수신
        req.ReceiveData();

        // 수신받은 데이터 획득
        PlatformData reqData    = req.GetData();
        VariableList reqVarList = reqData.GetVariableList();

        // 부서명 획득
        string name = reqVarList.GetString("name");

        // 송신할 데이터 생성
        PlatformData resData    = new PlatformData();
        VariableList resVarList = resData.GetVariableList();

        // 부서별 인원을 저장할 DataSet 생성
        DataSet employees = new DataSet("employees");

        // DataSet에 열(column) 추가
        employees.AddColumn(new ColumnHeader("name", DataTypes.STRING, 8));
        employees.AddColumn(new ColumnHeader("jobTitle", DataTypes.STRING));
        employees.AddColumn(new ColumnHeader("number", DataTypes.INT));
        employees.AddColumn(new ColumnHeader("manager", DataTypes.BOOLEAN));

        // 부서별 인원 데이터 추가
        if ("R&D Center".Equals(name))
        {
            // 행(row) 추가
            int row = employees.NewRow();
            // 추가된 행(row)의 데이터 설정
            employees.Set(row, "name", "John Jones");
            employees.Set(row, "jobTitle", "developer");
            employees.Set(row, "number", 1234);
            employees.Set(row, "manager", false);
            // ...
            // 정상 수행
            resData.AddDataSet(employees);
            resVarList.Add("ERROR_CODE", 200);
        }
        else if ("Quality Assurance".Equals(name))
        {
            // 행(row) 추가
            int row = employees.NewRow();
            // 추가된 행(row)의 데이터 설정
            employees.Set(row, "name", "Tom Glover");
            employees.Set(row, "jobTitle", "manager");
            employees.Set(row, "number", 9876);
            employees.Set(row, "manager", true);
            // ...
            // 정상 수행
            resData.AddDataSet(employees);
            resVarList.Add("ERROR_CODE", 200);
        }
        else
        {
            // 오류 발생
            resVarList.Add("ERROR_CODE", 500);
        }
        // HttpServletResponse를 이용하여 PlatformResponse 생성
        PlatformResponse res = new PlatformResponse(Response.OutputStream);

        res.SetData(resData);
        // 데이터 송신
        res.SendData();
    }
Пример #15
0
 public void Update(PlatformRequest platformRequest)
 {
     _ctx.PlatformRequests.Update(platformRequest);
     _ctx.SaveChanges();
 }
Пример #16
0
 public void CreatePlatformRequest(PlatformRequest platformRequest)
 {
      _ctx.PlatformRequests.Add(platformRequest);
      _ctx.SaveChanges();
 }