Пример #1
0
        public async Task MyIdShouldReturnId()
        {
            // Arrange
            //
            var telegramBotMock = new Mock <ITelegramBotClient>();

            telegramBotMock.Setup(_ => _.SendTextMessageAsync(
                                      It.IsAny <ChatId>(),
                                      It.IsAny <string>(),
                                      It.IsAny <ParseMode>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <int>(),
                                      It.IsAny <IReplyMarkup>(),
                                      It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Message())
            .Verifiable();

            var dcFactory       = new DataConnectionFactory(_connectionSettings);
            var telegramService = new TelegramService(
                TestHelper.GetLoggerMock <TelegramService>().Object,
                telegramBotMock.Object,
                dcFactory);

            _mockMessage.Text = "/myid";

            var publicUserId = shortid.ShortId.Generate();
            var yasUser      = new YasUser {
                TelegramId = 0, PublicId = publicUserId, UserName = "******"
            };

            await using var dc = dcFactory.Create();
            {
                dc.GetTable <YasUser>().DataContext.InsertWithIdentity(yasUser);
            }

            // Act
            //
            await telegramService.OnBotMessage(_mockMessage);


            // Assert
            //
            telegramBotMock.Verify(_ => _.SendTextMessageAsync(
                                       It.IsAny <ChatId>(), It.Is <string>(m => m.Equals($"{publicUserId}")),
                                       It.IsAny <ParseMode>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <int>(),
                                       It.IsAny <IReplyMarkup>(),
                                       It.IsAny <CancellationToken>()));

            long usersCount;

            await using var dc2 = dcFactory.Create();
            {
                usersCount = await dc2.GetTable <YasUser>().CountAsync();
            }
            Assert.Equal(1, usersCount);
        }
Пример #2
0
        /// <summary>
        /// Store Weather Request and response info in DB
        /// </summary>
        /// <param name="watchRequest">Watch request data</param>
        /// <param name="weatherInfo">Weather data</param>
        /// <param name="locationInfo">Location data</param>
        /// <param name="exchangeRateInfo">Exchange rate data</param>
        public virtual async Task SaveRequestInfo(
            [NotNull] WatchRequest watchRequest,
            [NotNull] WeatherInfo weatherInfo,
            [NotNull] LocationInfo locationInfo,
            [NotNull] ExchangeRateInfo exchangeRateInfo)
        {
            await using var dbWatchServer = _connectionFactory.Create();
            var deviceData = dbWatchServer.QueryProc <DeviceData>(
                "add_device",
                new DataParameter("device_id", watchRequest.DeviceId ?? "unknown"),
                new DataParameter("device_name", watchRequest.DeviceName))
                             .Single();

            var requestData = _mapper.Map <RequestData>(watchRequest);

            requestData = _mapper.Map(weatherInfo, requestData);
            requestData = _mapper.Map(locationInfo, requestData);
            requestData = _mapper.Map(exchangeRateInfo, requestData);
            requestData.DeviceDataId = deviceData.Id;
            requestData.RequestTime  = DateTime.UtcNow;

            await dbWatchServer.GetTable <RequestData>().DataContext.InsertAsync(requestData);

            _logger.LogDebug("{@requestInfo}", requestData);
        }
Пример #3
0
        /// <summary>
        /// Save Data into persistent storage
        /// </summary>
        private async Task SaveData(
            WatchRequest watchRequest, WeatherInfo weatherInfo, LocationInfo locationInfo, ExchangeRateInfo exchangeRateInfo)
        {
            await using var dbConnection = _dbFactory.Create();
            var deviceData = await dbConnection.GetTable <DeviceData>()
                             .SingleOrDefaultAsync(_ => _.DeviceId == watchRequest.DeviceId);

            if (deviceData == null)
            {
                deviceData = new DeviceData
                {
                    DeviceId         = watchRequest.DeviceId,
                    DeviceName       = watchRequest.DeviceName,
                    FirstRequestTime = watchRequest.RequestTime
                };
                deviceData.Id = await dbConnection.GetTable <DeviceData>().DataContext.InsertWithInt32IdentityAsync(deviceData);
            }

            var requestData = _mapper.Map <RequestData>(watchRequest);

            requestData = _mapper.Map(weatherInfo, requestData);
            requestData = _mapper.Map(locationInfo, requestData);
            requestData = _mapper.Map(exchangeRateInfo, requestData);
            requestData.DeviceDataId = deviceData.Id;

            await dbConnection.GetTable <RequestData>().DataContext.InsertAsync(requestData);
        }
Пример #4
0
        public async Task <ActionResult <IEnumerable <YasRoute> > > RouteList([FromRoute] string publicId)
        {
            await using var db = _dbFactory.Create();
            var yasUser = db.GetTable <YasUser>().SingleOrDefault(u => u.PublicId == publicId);

            if (yasUser == null)
            {
                return(NotFound(new ErrorResponse()
                {
                    StatusCode = StatusCodes.Status404NotFound, Description = "User not found"
                }));
            }

            var routes = db.GetTable <YasRoute>().Where(r => r.UserId == yasUser.UserId)
                         .OrderByDescending(r => r.UploadTime);
            var wayPoints   = routes.Join(db.GetTable <YasWaypoint>(), r => r.RouteId, w => w.RouteId, (r, w) => w).ToArray();
            var routesArray = routes.ToArray();

            foreach (var route in routesArray)
            {
                route.Waypoints = wayPoints.Where(w => w.RouteId == route.RouteId).OrderBy(w => w.OrderId);
            }

            _logger.LogInformation("Watch app request from User {@YasUser}, {RoutesCount} routes found", yasUser, routesArray.Length);
            return(routesArray);
        }
Пример #5
0
        public async Task RouteListShouldReturnList()
        {
            // Arrange
            //
            var telegramBotMock = new Mock <ITelegramBotClient>();

            telegramBotMock.Setup(_ => _.SendTextMessageAsync(
                                      It.IsAny <ChatId>(),
                                      It.IsAny <string>(),
                                      It.IsAny <ParseMode>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <int>(),
                                      It.IsAny <IReplyMarkup>(),
                                      It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Message())
            .Verifiable();

            var dcFactory       = new DataConnectionFactory(_connectionSettings);
            var telegramService = new TelegramService(
                TestHelper.GetLoggerMock <TelegramService>().Object,
                telegramBotMock.Object,
                dcFactory);

            _mockMessage.Text = "/list";

            var publicUserId = shortid.ShortId.Generate();
            var yasUser      = new YasUser {
                TelegramId = 0, PublicId = publicUserId, UserName = "******"
            };
            var yasRoute = new YasRoute {
                RouteName = "route1"
            };

            await using var dc = dcFactory.Create();
            {
                var userId = await dc.GetTable <YasUser>().DataContext.InsertWithInt64IdentityAsync(yasUser);

                yasRoute.UserId = userId;
                dc.GetTable <YasRoute>().DataContext.InsertWithIdentity(yasRoute);
            }

            // Act
            //
            await telegramService.OnBotMessage(_mockMessage);


            // Assert
            //
            telegramBotMock.Verify(_ => _.SendTextMessageAsync(
                                       It.IsAny <ChatId>(), It.Is <string>(m => m.StartsWith("<b> 1 </b> : <code>route1")),
                                       It.IsAny <ParseMode>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <int>(),
                                       It.IsAny <IReplyMarkup>(),
                                       It.IsAny <CancellationToken>()));
        }
Пример #6
0
        public async Task NewUserShouldBeCreatedInDb()
        {
            // Arrange
            //
            var telegramBotMock = new Mock <ITelegramBotClient>();

            telegramBotMock.Setup(_ => _.SendTextMessageAsync(
                                      It.IsAny <ChatId>(),
                                      It.IsAny <string>(),
                                      It.IsAny <ParseMode>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <int>(),
                                      It.IsAny <IReplyMarkup>(),
                                      It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Message())
            .Verifiable();

            var dcFactory       = new DataConnectionFactory(_connectionSettings);
            var telegramService = new TelegramService(
                TestHelper.GetLoggerMock <TelegramService>().Object,
                telegramBotMock.Object,
                dcFactory);

            _mockMessage.Text = "/myid";


            // Act
            //
            await telegramService.OnBotMessage(_mockMessage);


            // Assert
            //
            telegramBotMock.Verify(_ => _.SendTextMessageAsync(
                                       It.IsAny <ChatId>(), It.IsAny <string>(),
                                       It.IsAny <ParseMode>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <int>(),
                                       It.IsAny <IReplyMarkup>(),
                                       It.IsAny <CancellationToken>()), Times.Once);

            long usersCount;

            await using var dc2 = dcFactory.Create();
            {
                usersCount = await dc2.GetTable <YasUser>().CountAsync();
            }
            Assert.Equal(1, usersCount);
        }
Пример #7
0
        public async static Task Postgres2MsSql(DataConnectionFactory pgFactory, DataConnectionFactory msSqlFactory, DateTime transferDate)
        {
            await using var pgConnection    = pgFactory.Create();
            await using var msSqlConnection = msSqlFactory.Create();

            // msSqlConnection.Command.CommandText = "SET IDENTITY_INSERT DeviceInfo ON";
            //msSqlConnection.Command.ExecuteNonQuery();

            int count = 0;

            var devices = (transferDate == DateTime.MaxValue)
                ? await pgConnection.GetTable <DeviceData>().ToArrayAsync()
                : await pgConnection.GetTable <DeviceData>()
                          .Where(d => d.Id.In(pgConnection.GetTable <RequestData>()
                                              .Where(r => r.RequestTime.Value.Date == transferDate.Date)
                                              .Select(r => r.DeviceDataId)))
                          .ToArrayAsync();


            foreach (var device in devices)
            {
                count++;
                var requests = pgConnection.GetTable <RequestData>()
                               .Where(r => r.DeviceDataId == device.Id);

                if (transferDate != DateTime.MaxValue)
                {
                    requests = requests.Where(r => r.RequestTime.Value.Date == transferDate.Date);
                }


                await msSqlConnection.GetTable <DeviceData>().DataContext.InsertOrReplaceAsync(device);

                msSqlConnection.GetTable <RequestData>().BulkCopy(
                    new BulkCopyOptions {
                    KeepIdentity = true
                },
                    await requests.ToArrayAsync());

                Console.Write("\r{0} out of {1} devices processed - {2}% :: current: {3}, requests:{4}                           ",
                              count, devices.Length, count * 100 / devices.Length, device.DeviceName, requests.Count());
            }
        }
Пример #8
0
        private async Task <string> ProcessGpx(Message message, YasUser yasUser)
        {
            var fileId   = message.Document.FileId;
            var fileName = message.Document.FileName;

            await using var memoryStream = new MemoryStream();
            await _telegramBot.GetInfoAndDownloadFileAsync(fileId, memoryStream);

            memoryStream.Position = 0;
            XNamespace ns      = "http://www.topografix.com/GPX/1/1";
            var        root    = XElement.Load(memoryStream);
            var        orderId = 0;
            var        points  = root.Elements(ns + "rte").Elements(ns + "rtept")
                                 .Union(root.Elements(ns + "wpt"))
                                 .Select(w => new YasWaypoint()
            {
                Name      = w.Element(ns + "name")?.Value,
                Latitude  = Convert.ToDecimal(w.Attribute("lat")?.Value),
                Longitude = Convert.ToDecimal(w.Attribute("lon")?.Value),
                OrderId   = orderId++
            }).ToList();

            if (points.Count == 0)
            {
                return($"No route or way points were found in {fileName} ");
            }

            var route = new YasRoute
            {
                UserId     = yasUser.UserId,
                UploadTime = DateTime.UtcNow,
                RouteName  = root.Element(ns + "rte")?.Element(ns + "name")?.Value ?? Path.GetFileNameWithoutExtension(fileName)
            };

            await using var db = _dbFactory.Create();
            await db.BeginTransactionAsync();

            route.RouteId = await db.GetTable <YasRoute>().DataContext.InsertWithInt64IdentityAsync(route);

            foreach (var point in points)
            {
                point.RouteId = route.RouteId;
            }
            db.BulkCopy(points);
            await db.CommitTransactionAsync();

            return($"The route <b> {route.RouteId} </b> : {route.RouteName} ({points.Count} way points) has been uploaded \n userId:{yasUser.PublicId}");
        }
Пример #9
0
        public async Task RenameCommandShouldRenameSpecifedRoute(long routeId)
        {
            // Arrange
            //
            var telegramBotMock = new Mock <ITelegramBotClient>();

            telegramBotMock.Setup(_ => _.SendTextMessageAsync(
                                      It.IsAny <ChatId>(),
                                      It.IsAny <string>(),
                                      It.IsAny <ParseMode>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <bool>(),
                                      It.IsAny <int>(),
                                      It.IsAny <IReplyMarkup>(),
                                      It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Message())
            .Verifiable();

            var dcFactory       = new DataConnectionFactory(_connectionSettings);
            var telegramService = new TelegramService(
                TestHelper.GetLoggerMock <TelegramService>().Object,
                telegramBotMock.Object,
                dcFactory);


            var yasUser = new YasUser {
                TelegramId = 0, PublicId = shortid.ShortId.Generate(), UserName = "******"
            };
            var yasRoute1 = new YasRoute {
                RouteName = "route-1"
            };
            var yasRoute2 = new YasRoute {
                RouteName = "route-2"
            };

            await using var dc = dcFactory.Create();
            {
                var userId = await dc.GetTable <YasUser>().DataContext.InsertWithInt64IdentityAsync(yasUser);

                yasRoute1.UserId = userId;
                dc.GetTable <YasRoute>().DataContext.InsertWithIdentity(yasRoute1);
                dc.GetTable <YasRoute>().DataContext.InsertWithIdentity(yasRoute2);
                _mockMessage.Text = $"/rename:{routeId} new-name";
            }


            // Act
            //
            await telegramService.OnBotMessage(_mockMessage);


            // Assert
            //
            telegramBotMock.Verify(_ => _.SendTextMessageAsync(
                                       It.IsAny <ChatId>(), It.Is <string>(
                                           m => (routeId == 1 && m.Equals($"Route id: <b> 1 </b>, new name: <b> new-name </b>")) ||
                                           (routeId != 1 && m.Equals($"Cannot find the route id: <b> {routeId} </b>"))),
                                       It.IsAny <ParseMode>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <int>(),
                                       It.IsAny <IReplyMarkup>(),
                                       It.IsAny <CancellationToken>()));

            await using var dc2 = dcFactory.Create();
            {
                var route0Count = await dc2.GetTable <YasRoute>().Where(r => r.RouteName == "new-name").CountAsync();

                var route1Count = await dc2.GetTable <YasRoute>().Where(r => r.RouteName == "route-1").CountAsync();

                var route2Count = await dc2.GetTable <YasRoute>().Where(r => r.RouteName == "route-2").CountAsync();

                Assert.Equal(routeId == 1 ? 1 : 0, route0Count);
                Assert.Equal(routeId == 1 ? 0 : 1, route1Count);
                Assert.Equal(1, route2Count);
            }
        }