public IActionResult Put(int id, Rating rat)
 {
     if (id == rat.ID_Rating)
     {
         TrueHomeContext.updateRating(rat);
     }
     return(Ok());
 }
Example #2
0
 public async Task <IActionResult> Delete([FromBody] IDJSON id)
 {
     if (id.IntID == null)
     {
         return(BadRequest());
     }
     TrueHomeContext.deleteApartment(id.IntID);
     return(Ok());
 }
Example #3
0
        public string Get(int id)
        {
            var ap = TrueHomeContext.getApartment(id);

            ap.ImgList = ap.ImgList.Select(fileName =>
                                           $"{_configuration["ResourceSrvUrl"]}/api/Pictures/{ap.ID_Ap}/{fileName}"
                                           ).ToArray();

            return(JsonConvert.SerializeObject(ap, Formatting.Indented));
        }
        public IActionResult GetAll()
        {
            var rentingList = TrueHomeContext.getAllRentings();

            if (rentingList == null)
            {
                return(NotFound());
            }
            return(Ok(JsonConvert.SerializeObject(rentingList, Formatting.Indented)));
        }
        public async Task <JObject> Post(Rating rat)
        {
            var userId = User.FindFirst("sub")?.Value;

            _logger.LogInformation("Adding new rating from " + User.Identity.Name);

            rat.IDUser = userId;
            var id = await TrueHomeContext.createRating(rat);

            return(JObject.Parse("{\"id\": " + id + ", \"UploadStatus\": " + 1 + "}"));
        }
        public IActionResult Put(Apartment ap)
        {
            var userId = User.FindFirst("sub")?.Value;

            if (ap.IDUser != userId)
            {
                return(BadRequest());
            }
            TrueHomeContext.updateApartment(ap);
            return(Ok());
        }
        public IActionResult GetByUser()
        {
            var userId = User.FindFirst("sub")?.Value;

            var renting = TrueHomeContext.getRentingByUser(userId);

            if (renting == null)
            {
                return(NotFound());
            }
            return(Ok(JsonConvert.SerializeObject(renting, Formatting.Indented)));
        }
Example #8
0
        public JObject getPhoneNumber()
        {
            var userId = User.FindFirst("sub")?.Value;

            string phoneNumber = TrueHomeContext.getPhoneNumber(userId);
            string jsonData    = null;

            if (phoneNumber == null)
            {
                jsonData = "{ 'phoneNumber': null }";
            }
            else
            {
                jsonData = "{'phoneNumber': " + $"'{phoneNumber}'" + "'}";
            }

            return(JObject.Parse(jsonData));
        }
Example #9
0
        public async Task <JObject> Post(Apartment ap)
        {
            var userId = User.FindFirst("sub")?.Value;

            _logger.LogInformation("Adding new apartment owned by " + User.Identity.Name);

            var phoneNum = TrueHomeContext.getPhoneNumber(userId);

            if (phoneNum == null)
            {
                TrueHomeContext.setPhoneNumber(ap.PhoneNumber, userId);
            }

            ap.IDUser = userId;
            var id = await TrueHomeContext.createApartment(ap);

            return(JObject.Parse("{\"id\": " + id + ", \"UploadStatus\": " + 1 + "}"));
        }
Example #10
0
        public async Task <JObject> register(RegisterJSON registerJson)
        {
            var client   = _clientFactory.CreateClient("auth");
            var response = await client.PostAsync(
                "connect/register",
                new FormUrlEncodedContent(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Login", registerJson.Login),
                new KeyValuePair <string, string>("Email", registerJson.Email),
                new KeyValuePair <string, string>("Password", registerJson.Password)
            }));

            var str = await response.Content.ReadAsStringAsync();

            _logger.LogInformation("Response from authServer: " + str);

            if (str.Length <= 1)
            {
                return(JObject.Parse("{\"RegisterStatus\": " + str + "}"));
            }

            var user = new User
            {
                ID_User   = str,
                Login     = registerJson.Login,
                Email     = registerJson.Email,
                Rate      = null,
                isBlocked = false,
                IDRole    = 1 //TODO: assign proper role ID
            };

            var personalData = new PersonalData
            {
                IDUser    = str,
                FirstName = registerJson.Name,
                LastName  = registerJson.Surname
            };

            await TrueHomeContext.addUser(user);

            await TrueHomeContext.addPersonalData(personalData);

            return(JObject.Parse("{\"RegisterStatus\": 1}"));
        }
        public async Task <IActionResult> Add(Renting ret)
        {
            var userId = User.FindFirst("sub")?.Value;

            _logger.LogInformation("Adding new renting from " + User.Identity.Name);

            ret.IDUser = userId;
            if (ret.date_to < ret.date_from || ret.date_to <= System.DateTime.Today)
            {
                return(BadRequest("Given date is smaller than today"));
            }
            var id = await TrueHomeContext.createRenting(ret);

            if (id == -1)
            {
                return(BadRequest("Something went wrong!"));
            }
            return(Ok(JObject.Parse("{\"id\": " + id + ", \"UploadStatus\": " + 1 + "}")));
        }
Example #12
0
        public string Get(LimitOffset limitOffset)
        {
            var limit  = limitOffset.limit;
            var offset = limitOffset.offset;

            var aps = TrueHomeContext.getApartments(limit, offset);

            foreach (var ap in aps.apartmentsList)
            {
                ap.ImgList = ap.ImgList?.Select(fileName =>
                                                $"{_configuration["ResourceSrvUrl"]}/api/Pictures/{ap.ID_Ap}/{fileName}"
                                                ).ToArray();

                if (!string.IsNullOrEmpty(ap.ImgThumb))
                {
                    ap.ImgThumb = $"{_configuration["ResourceSrvUrl"]}/api/Pictures/{ap.ID_Ap}/{ap.ImgThumb}";
                }
            }

            return(JsonConvert.SerializeObject(aps, Formatting.Indented));
        }
        public IActionResult DeleteImg(int idAp, string filename)
        {
            var path = $"/data/pictures/{idAp}/{filename}";

            try
            {
                _logger.LogDebug("Deleting picture " + path);

                System.IO.File.SetAttributes(path, FileAttributes.Normal);
                System.IO.File.Delete(path);

                TrueHomeContext.DeletePictureRef(idAp, filename);

                return(Ok());
            }
            catch (FileNotFoundException)
            {
                _logger.LogError("Picture not found!");
                return(NotFound());
            }
        }
Example #14
0
        public string Details()
        {
            var userId = User.FindFirst("sub")?.Value;

            if (string.IsNullOrEmpty(userId))
            {
                return("Missing user with this id");
            }

            var userDetails = new UserDetailsJSON
            {
                personalData  = TrueHomeContext.getPersonalDataByUserID(userId),
                user          = TrueHomeContext.getUser(userId),
                apartmentList = TrueHomeContext.getUserApartmentList(userId)
            };

            if (userDetails.personalData != null && userDetails.user != null)
            {
                return(JsonConvert.SerializeObject(userDetails, Formatting.Indented));
            }
            return("Missing user with this id");
        }
        public string Get(int idAp, int limit, int offset)
        {
            var rat = TrueHomeContext.getRatings(idAp, limit, offset);

            return(JsonConvert.SerializeObject(rat, Formatting.Indented));
        }
Example #16
0
 public async Task <IActionResult> Put(Apartment ap)
 {
     TrueHomeContext.updateApartment(ap);
     return(Ok());
 }
 public IActionResult Delete(int id)
 {
     TrueHomeContext.deleteRating(id);
     return(Ok());
 }
        public async Task <IActionResult> UploadImg(int idAp)
        {
            IFormFile image;

            try
            {
                if (HttpContext.Request.Form.Files[0] != null)
                {
                    image = HttpContext.Request.Form.Files[0];
                }
                else
                {
                    throw new ArgumentNullException("image", "Could not bind uploaded image or no image sent");
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(BadRequest(e.ToString()));
            }

            if (image.Length > 0 && image.ContentType.Contains("image"))
            {
                var    dirPath   = $"/data/pictures/{idAp}";
                var    filePath  = $"{dirPath}/{image.FileName}";
                string thumbName = null;

                if (System.IO.File.Exists(filePath))
                {
                    _logger.LogWarning($"File {filePath} already exists, aborting.");
                    return(Ok());
                }

                try
                {
                    var ap = TrueHomeContext.getApartment(idAp);

                    if (string.IsNullOrEmpty(ap.ImgThumb))
                    {
                        _logger.LogInformation($"Received first picture for apartment {idAp}, creating thumbnail copy");
                        Directory.CreateDirectory(dirPath);

                        thumbName = Path.GetFileNameWithoutExtension(image.FileName) +
                                    "_thumb" +
                                    Path.GetExtension(image.FileName);

                        using (var inputStream = image.OpenReadStream())
                            using (var imgThumb = Image.Load(inputStream))
                            {
                                imgThumb.Mutate(x => x
                                                .Resize(0, 300));

                                imgThumb.Save($"{dirPath}/{thumbName}");
                            }

                        ap.ImgThumb = thumbName;
                    }

                    using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        await image.CopyToAsync(fileStream);
                    }

                    ap.ImgList = ap.ImgList
                                 ?.Concat(new[] { image.FileName }).ToArray()
                                 ?? new[] { image.FileName };

                    TrueHomeContext.updateApartment(ap);

                    _logger.LogInformation("Uploaded new picture to apartment " + idAp);
                    return(Ok());
                }
                catch (Npgsql.PostgresException e)
                {
                    _logger.LogError(e, "Database error while saving picture. Deleting any saved pictures");

                    if (thumbName != null && System.IO.File.Exists($"{dirPath}/{thumbName}"))
                    {
                        System.IO.File.Delete($"{dirPath}/{thumbName}");
                        _logger.LogInformation($"Deleted thumbnail file {dirPath}/{thumbName}");
                    }

                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                        _logger.LogInformation($"Deleted file {filePath}");
                    }
                    return(BadRequest(e));
                }
                catch (IOException e)
                {
                    _logger.LogError(e, "IO exception while saving file! Database not updated");
                    return(BadRequest(e));
                }
                catch (Exception e)
                {
                    _logger.LogError("Error while saving file: " + e);
                    return(BadRequest(e));
                }
            }

            _logger.LogError("Wrong file format or no file given.");
            return(BadRequest());
        }