Пример #1
0
        public async Task <ActionResult <List <QueuedImage> > > AddToAlbum([FromBody] List <QueuedImage> queuedImages)
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            foreach (var queuedImage in queuedImages)
            {
                queuedImage.Status = 0;
                var fileToQueue =
                    await Utils.GetFileStreamAndContentType(_pdb, userId.GetValueOrDefault(), queuedImage.Path);

                // ReSharper disable once InvertIf
                if (fileToQueue == null)
                {
                    queuedImage.Status    = 4;
                    queuedImage.StatusMsg = "File not found";
                }
            }

            var queuedImagesResult = (await _pdb.AddImagesToQueue(userId.GetValueOrDefault(), queuedImages));

            if (queuedImagesResult != null)
            {
                return(queuedImagesResult);
            }

            return(new NotFoundResult());
        }
Пример #2
0
        public async Task <ActionResult> GetImage(ulong albumId, ulong imageId, [FromQuery] string size = "metadata")
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var validSizeValues = new[] { "metadata", "icon", "small", "medium", "large", "fullsize", "original" };

            if (!validSizeValues.Contains(size))
            {
                return(new BadRequestResult());
            }

            var image = await _pdb.GetImageByUserIdAlbumIdAndImageId(userId.GetValueOrDefault(), albumId, imageId);

            if (image == null)
            {
                return(new NoContentResult());
            }

            if (size == "metadata")
            {
                return(new OkObjectResult(image.GetPublic()));
            }

            try
            {
                var albumImageFile = image.ImageFiles.GetImageFile(size);
                if (albumImageFile == null)
                {
                    return(new NoContentResult());
                }

                var x = new FileStream(_imageHelper.GetFullPath(albumImageFile.Path), FileMode.Open);

                if (!x.CanRead)
                {
                    return(new NotFoundResult());
                }

                var fileExt         = Path.GetExtension(albumImageFile.Path);
                var virtualFilename = $"image_{albumId}_{imageId}_{size}{fileExt}";

                Response.Headers.Add("X-Width", albumImageFile.Width.ToString());
                Response.Headers.Add("X-Height", albumImageFile.Height.ToString());
                return(File(x, albumImageFile.MimeType, virtualFilename));
            }
            catch
            {
                return(new NotFoundResult());
            }
        }
Пример #3
0
        public async Task <ActionResult> GetFile([FromQuery] string path)
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var fileContent = await Utils.GetFileStreamAndContentType(_pdb, userId.GetValueOrDefault(), path);

            if (fileContent?.Item1 == null || fileContent.Item2 == null)
            {
                return(new NotFoundResult());
            }
            return(File(fileContent.Item1, fileContent.Item2));
        }
Пример #4
0
        public async Task <ActionResult <List <string> > > GetSources()
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var sources = (await _pdb.GetImageSourcesForUser(userId.GetValueOrDefault()))?.AsList();

            if (sources != null && sources.Count > 0)
            {
                return(sources.Select(x => x.SourceName).ToList());
            }

            return(new NoContentResult());
        }
Пример #5
0
        public async Task <ActionResult <List <QueuedImage> > > GetQueue()
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var queuedImages = (await _pdb.GetImageQueueForUser(userId.GetValueOrDefault()));

            if (queuedImages != null)
            {
                return(queuedImages.AsList());
            }

            return(new NotFoundResult());
        }
Пример #6
0
        public async Task <ActionResult <List <Album> > > GetReadable(string level)
        {
            AlbumAccessLevel accessLevel;

            switch (level)
            {
            case "admin":
                accessLevel = AlbumAccessLevel.Admin;
                break;

            case "write":
                accessLevel = AlbumAccessLevel.Write;
                break;

            case "share":
                accessLevel = AlbumAccessLevel.Share;
                break;

            case "read":
            case "":
            case null:
                accessLevel = AlbumAccessLevel.Read;
                break;

            default:
                return(new NotFoundResult());
            }

            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var albums = (await _pdb.GetAlbumsAccessibleByUser(userId.GetValueOrDefault(), accessLevel))?.AsList();

            if (albums != null && albums.Count > 0)
            {
                return(albums);
            }

            return(new NoContentResult());
        }
Пример #7
0
        public async Task <ActionResult <List <AlbumImage.Public> > > ListImages(ulong albumId)
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var images =
                (await _pdb.GetImagesInAlbumByUserIdAndAlbumId(userId.GetValueOrDefault(), albumId)).AsList();

            if (images != null && images.Count > 0)
            {
                return(images.Select(x => x.GetPublic()).ToList());
            }

            return(new NoContentResult());
        }
Пример #8
0
        public async Task <ActionResult <Album> > PostNewAlbum([FromBody] Album newAlbum)
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var createdAlbum = await _pdb.CreateNewAlbum(userId.GetValueOrDefault(), newAlbum.AlbumName);

            if (createdAlbum != null)
            {
                return(createdAlbum);
            }
            else
            {
                return(new BadRequestResult());
            }
        }
Пример #9
0
        public async Task <ActionResult <List <string> > > GetDirectory([FromQuery] string path)
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var dirContent = await Utils.GetDirectoryContent(_pdb, userId.GetValueOrDefault(), path);

            if (dirContent == null)
            {
                return(new NotFoundResult());
            }
            if (dirContent.Count == 0)
            {
                return(new NoContentResult());
            }
            return(dirContent);
        }
Пример #10
0
        public async Task <ActionResult <List <AlbumAccess> > > GetAccessList(ulong albumId)
        {
            var userId = PhotoDatabaseHelper.GetUserId(User);

            if (userId == null)
            {
                return(Unauthorized());
            }

            var accessList = (await _pdb.GetAlbumAccessByUserIdAndAlbumId(
                                  userId.GetValueOrDefault(),
                                  albumId)
                              )?.AsList();

            if (accessList != null && accessList.Count > 0)
            {
                return(accessList);
            }

            return(new NoContentResult());
        }
Пример #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // MySQL Connector/Net connection string
            // https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
            // Examples: 'Server=127.0.0.1;Database=my_db_name;Uid=my_username;Pwd=my_password;SslMode=none;'
            // Examples: 'Server=127.0.0.1;Database=my_db_name;Uid=my_username;Pwd=my_password;SslMode=Preferred;'
            // Examples: 'Server=127.0.0.1;Database=my_db_name;Uid=my_username;Pwd=my_password;SslMode=Required;'
            var            connectionString = StaticConfiguration["SHUTTRE_CONNECTION_STRING"];
            IPhotoDatabase pdb = new PhotoDatabase(connectionString);

            var config = pdb.GetConfig().Result;

            if (config == null)
            {
                Console.Error.WriteLine("Could not read configuration from database.");
                System.Environment.Exit(1);
            }
            if (!config.OidcVerificationMethodIsAuthorityUrl)
            {
                Console.Error.WriteLine("For now, 'authority_url' is the only supported verification method");
                System.Environment.Exit(1);
            }

            var claimRequirements = config.ClaimRequirements;

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = config.OidcAuthorityUrl;
                options.Audience  = config.OidcAudience;
                options.Events    = new JwtBearerEvents
                {
                    OnTokenValidated = async context =>
                    {
                        if (!(context.SecurityToken is JwtSecurityToken securityToken))
                        {
                            context.Fail("SecurityToken is not JwtSecurityToken");
                            return;
                        }

                        if (!claimRequirements.Verify(securityToken.Claims))
                        {
                            context.Fail("claimRequirements.Verify failed");
                            return;
                        }

                        var user = await pdb.GetUserByOidcIdCached(securityToken.Subject);
                        if (user == null)
                        {
                            var newUser = await PhotoDatabaseHelper.RegisterNewUser(securityToken);
                            if (newUser == null)
                            {
                                context.Fail("User not in database, and could not create user.");
                                return;
                            }

                            user = newUser;
                        }

                        var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
                        foreach (var claim in user.GetClaims())
                        {
                            claimsIdentity.AddClaim(claim);
                        }
                    }
                };
            });

            services.AddSingleton(pdb);
            services.AddSingleton(config);
            services.AddSingleton <IHostedService, HandleQueuedImagesService>();
            services.AddSingleton <IImageHelper, ImageHelper>();

            var frontendUurl = config.FrontendUrl;

            services.AddCors(options =>
            {
                options.AddPolicy(_myCorsOriginsPolicy,
                                  builder =>
                {
                    builder
                    .WithOrigins(frontendUurl)
                    .WithHeaders("Authorization", "Content-Type")
                    .WithMethods("GET", "POST")
                    .SetPreflightMaxAge(TimeSpan.FromSeconds(120));
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }