Пример #1
0
        public async Task RunExiftoolGetImageSizeAndExposureTime()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());

            sut.Initialize();

            // act
            var result = await sut.ExecuteAsync(
                new[]
            {
                "-s",
                "-ImageSize",
                "-ExposureTime",
                image,
            })
                         .ConfigureAwait(false);

            // assert
            result.Should().Be("ImageSize                       : 1712x2288" + Environment.NewLine);

            await sut.DisposeAsync().ConfigureAwait(false);

            // just for fun
            output.WriteLine(image);
            output.WriteLine(result);
        }
Пример #2
0
        public AsyncExifToolSimpleTest()
        {
            shell = A.Fake <IShell>();
            sut   = testSut = new TestableAsyncFakeExifTool(shell);

            A.CallTo(() => shell.WriteLineAsync(A <string> ._)).Returns(Task.CompletedTask);
        }
Пример #3
0
        public async Task RunWithInputStreamTest()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());
            var sw  = Stopwatch.StartNew();

            sut.Initialize();
            sw.Stop();
            output.WriteLine($"It took {sw.Elapsed.ToString()} to Initialize exiftool");

            // act
            sw.Reset();
            sw.Start();
            var version = string.Empty;

            for (var i = 0; i < Repeat; i++)
            {
                version = await sut.GetVersionAsync().ConfigureAwait(false);
            }
            sw.Stop();
            await sut.DisposeAsync().ConfigureAwait(false);

            // assert
            output.WriteLine($"It took {sw.Elapsed.ToString()} to retrieve exiftool version {Repeat} times");
            output.WriteLine($"Version: {version}");
            version.Should().NotBeNullOrEmpty();
        }
Пример #4
0
        public async Task WriteXmpSubjectsToImageTest()
        {
            // arrange
#if NETCOREAPP3_0
            await using var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());
#else
            using var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());
#endif
            sut.Initialize();

            // act
            var @params = new[] { "-XMP-dc:Subject+=def", "-XMP-dc:Subject+=abc", "-XMP-dc:Subject=xyz", image, };

            var readResultBefore = await sut.ExecuteAsync(image).ConfigureAwait(false);

            var writeResult = await sut.ExecuteAsync(@params).ConfigureAwait(false);

            var readResultAfter = await sut.ExecuteAsync(image).ConfigureAwait(false);

            // assert
            readResultBefore.Should().Contain("Subject                         : dog, new york, puppy");
            readResultBefore.Should().NotContain("Subject                         : dog, new york, puppy, def, abc, xyz");
            writeResult.Should().Be("    1 image files updated" + Environment.NewLine);
            readResultAfter.Should().Contain("Subject                         : dog, new york, puppy, def, abc, xyz" + Environment.NewLine);

            // just for fun
            output.WriteLine(readResultAfter);
        }
        public async Task WriteCustomXmpTagsToImageTest()
        {
            // arrange
#if NETCOREAPP3_0
            await using var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.CreateWithCustomConfig());
#else
            using var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.CreateWithCustomConfig());
#endif
            sut.Initialize();

            // act
            var @params = new[] { "-XMP-CoenmAsyncExifTool:MyCustomId=test123", "-XMP-CoenmAsyncExifTool:MyCustomTimestamp=2020:05:08 12:00:45+02:00", "-XMP-CoenmAsyncExifTool:MyCustomTags+=holidays", "-XMP-CoenmAsyncExifTool:MyCustomTags+=summer", image, };

            var readResultBefore = await sut.ExecuteAsync(image).ConfigureAwait(false);

            var writeResult = await sut.ExecuteAsync(@params).ConfigureAwait(false);

            var readResultAfter = await sut.ExecuteAsync(image).ConfigureAwait(false);

            // assert
            writeResult.Trim().Should().Be("1 image files updated");

            readResultBefore.Should().NotContain("My Custom Id                    : test123");
            readResultBefore.Should().NotContain("My Custom Tags                  : holidays, summer");
            readResultBefore.Should().NotContain("My Custom Timestamp             : 2020:05:08 12:00:45");

            readResultAfter.Should().Contain("My Custom Id                    : test123");
            readResultAfter.Should().Contain("My Custom Tags                  : holidays, summer");
            readResultAfter.Should().Contain("My Custom Timestamp             : 2020:05:08 12:00:45+02:00");

            // just for fun
            output.WriteLine(readResultAfter);
        }
Пример #6
0
        public async Task RunExifToolWithThreeCommands()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());

            sut.Initialize();

            // act
            var task1 = sut.ExecuteAsync(image);
            var task2 = sut.ExecuteAsync(image);
            var task3 = sut.ExecuteAsync(image);

            // assert
            var result3 = await task3.ConfigureAwait(false);

            result3.Should().NotBeNullOrEmpty();

            var result2 = await task2.ConfigureAwait(false);

            result2.Should().NotBeNullOrEmpty();

            var result1 = await task1.ConfigureAwait(false);

            result1.Should().NotBeNullOrEmpty();

            await sut.DisposeAsync().ConfigureAwait(false);
        }
Пример #7
0
        public async Task RunExiftool_ShouldReturnEmpty_WhenQueriedTagDoesNotExist()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());

            sut.Initialize();

            // act
            var result = await sut.ExecuteAsync(
                new[]
            {
                "-ExposureTime",
                image,
            })
                         .ConfigureAwait(false);

            // assert
            result.Should().Be(string.Empty);

            await sut.DisposeAsync().ConfigureAwait(false);

            // just for fun
            output.WriteLine(image);
            output.WriteLine(result);
        }
 /// <summary>
 /// Execute single command on ExifTool instance.
 /// </summary>
 /// <param name="this">Instance of <see cref="AsyncExifTool"/> to use to execute this command. Cannot be <c>null</c>.</param>
 /// <param name="singleArg">The command to run on exiftool. For instance `-ver`. See the ExifTool website for all options.</param>
 /// <param name="ct">Cancellation token. Optional. Defaults to <see cref="CancellationToken.None"/>.</param>
 /// <returns>ExifTool result containing the version information.</returns>
 /// <exception cref="ArgumentNullException">Thrown when <paramref name="this"/> is <c>null</c>.</exception>
 public static Task <string> ExecuteAsync([NotNull] this AsyncExifTool @this, string singleArg, CancellationToken ct = default)
 {
     if (@this == null)
     {
         throw new ArgumentNullException(nameof(@this));
     }
     return(@this.ExecuteAsync(new[] { singleArg }, ct));
 }
        public AsyncExifToolRotationService()
        {
            // var logger = new ExifToolConsoleLogger();
            var configuration = new AsyncExifToolConfiguration("exiftool.exe", Encoding.UTF8, Environment.NewLine, new List <string>());

            asyncExifTool = new AsyncExifTool(configuration);
            asyncExifTool.Initialize();
        }
Пример #10
0
        public void Ctor_ShouldThrow_WhenConfigurationIsNull()
        {
            // arrange
            AsyncExifToolConfiguration configuration = null;

            // act
            Action act = () => _ = new AsyncExifTool(configuration);

            // assert
            act.Should().Throw <ArgumentNullException>();
        }
Пример #11
0
        private static void ParseImageFile(string path, AsyncExifTool asyncExifTool, Dictionary <string, Dictionary <string, ExifData> > data)
        {
            Console.WriteLine("Processing {0}...", path);

            var fileData = new Dictionary <string, ExifData>();

            data.Add(path, fileData);

            ParseFileData(asyncExifTool.ExecuteAsync(new[] { "-a", "-g", "-sort", path }).ConfigureAwait(false).GetAwaiter().GetResult(), fileData, true);
            ParseFileData(asyncExifTool.ExecuteAsync(new[] { "-a", "-g", "-n", "-sort", path }).ConfigureAwait(false).GetAwaiter().GetResult(), fileData, false);
        }
Пример #12
0
        public void Ctor_ShouldThrow_WhenLoggerIsNull()
        {
            // arrange
            ILogger logger = null;

            // act
            Action act = () => _ = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create(), logger);

            // assert
            act.Should().Throw <ArgumentNullException>();
        }
Пример #13
0
        public async Task InitAndDisposeTest()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());

            // act
            sut.Initialize();
            await sut.DisposeAsync().ConfigureAwait(false);

            // assert
            // sut.IsClosed.Should().Be(true);
        }
Пример #14
0
        public async Task RunExiftoolForVersionAndImageErrorTest()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());

            sut.Initialize();

            // act
            var         getMetadataNonExistingImageTask = sut.ExecuteAsync(image + "does not exist");
            Func <Task> act     = async() => await getMetadataNonExistingImageTask;
            var         version = await sut.GetVersionAsync().ConfigureAwait(false);

            // assert
            act.Should().Throw <Exception>();
            version.Should().NotBeNullOrEmpty();

            await sut.DisposeAsync().ConfigureAwait(false);
        }
Пример #15
0
        public async Task DisposeAsyncShouldCancelAllPendingRequestsTest()
        {
            // arrange
            var       tasks = new Task <string> [Repeat];
            Stopwatch sw;

#if NETCOREAPP3_0
            await using (var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create()))
#else
            using (var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create()))
#endif
            {
                sw = Stopwatch.StartNew();
                sut.Initialize();
                sw.Stop();
                output.WriteLine($"It took {sw.Elapsed.ToString()} to Initialize exiftool");

                // act
                sw.Reset();
                sw.Start();
                for (var i = 0; i < Repeat; i++)
                {
                    tasks[i] = sut.GetVersionAsync();
                }
                sw.Stop();
            }

            // assert
            var countCancelled = 0;
            foreach (var t in tasks)
            {
                try
                {
                    output.WriteLine(await t.ConfigureAwait(false));
                }
                catch (TaskCanceledException)
                {
                    countCancelled++;
                }
            }

            countCancelled.Should().BeGreaterOrEqualTo(Repeat / 2).And.NotBe(Repeat);
            output.WriteLine($"It took {sw.Elapsed.ToString()} to retrieve exiftool version {Repeat - countCancelled} times");
        }
Пример #16
0
        public async Task RunExiftoolForVersionAndImageTest()
        {
            // arrange
            var sut = new AsyncExifTool(AsyncExifToolConfigurationFactory.Create());

            sut.Initialize();

            // act
            var version = await sut.GetVersionAsync().ConfigureAwait(false);

            var result = await sut.ExecuteAsync(image).ConfigureAwait(false);

            // assert
            version.Should().NotBeNullOrEmpty();
            result.Should().NotBeNullOrEmpty();

            await sut.DisposeAsync().ConfigureAwait(false);

            // just for fun
            output.WriteLine(version);
            output.WriteLine(result);
        }
Пример #17
0
        static void Main(string[] args)
        {
            if (args.Count() < 1)
            {
                Console.WriteLine("Include a file name or multiple file names as parameters");
                return;
            }

            var location   = Path.GetDirectoryName(Assembly.GetEntryAssembly().GetFiles()[0].Name);
            var homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var options    = ReadOptions(".imagedetailscataloger_options.json", homeFolder);

            if (options == null)
            {
                // Fall-back to the default options.
                Console.WriteLine("Using default options, user options not found");
                options = ReadOptions("options.json", location);
                if (options == null)
                {
                    Console.Error.WriteLine("Cannot find the Options JSON file in the application folder");
                }
            }

            var databaseLocation = Path.Combine(options.UseHomeFolder ? homeFolder : location, "ImageDetails.sqlite");

            var exifToolPath           = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"exiftool.exe" : @"exiftool";
            var exifToolResultEncoding = Encoding.UTF8;
            var config        = new AsyncExifToolConfiguration(exifToolPath, exifToolResultEncoding, null);
            var asyncExifTool = new AsyncExifTool(config);

            asyncExifTool.Initialize();

            if (!File.Exists(databaseLocation))
            {
                Console.WriteLine("Creating SQLite DB");

                SQLiteConnection.CreateFile(databaseLocation);
            }
            var sqlite = new SQLiteConnection("Data Source='" + databaseLocation + "'");

            sqlite.Open();

            var command1 = new SQLiteCommand("CREATE TABLE IF NOT EXISTS image_details (id integer PRIMARY KEY, file TEXT NOT NULL UNIQUE);", sqlite);

            command1.ExecuteNonQuery();

            var data       = new Dictionary <string, Dictionary <string, ExifData> >();
            var statistics = new Statistics();

            foreach (var arg in args)
            {
                if (Directory.Exists(arg))
                {
                    var searchOptions = options.RecursiveFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
                    var files         = Directory.GetFiles(arg, "*.*", searchOptions);
                    Array.Sort(files, StringComparer.OrdinalIgnoreCase);
                    foreach (var filePath in files)
                    {
                        if (options.FolderSearchExtensions.Any(extension => string.Equals(Path.GetExtension(filePath), extension, StringComparison.OrdinalIgnoreCase)))
                        {
                            ParseImageFile(filePath, asyncExifTool, data);
                            if (data.Keys.Count >= options.FilesInBatch)
                            {
                                if (options.RecycleExifTool)
                                {
                                    asyncExifTool.DisposeAsync().AsTask().Wait();
                                }

                                // To avoid memory issues, write to the DB every so many files.
                                WriteDataToDB(sqlite, data, statistics);

                                if (options.RecycleExifTool)
                                {
                                    asyncExifTool = new AsyncExifTool(config);
                                    asyncExifTool.Initialize();
                                }
                            }
                        }
                    }
                }
                else if (File.Exists(arg))
                {
                    ParseImageFile(arg, asyncExifTool, data);
                }
                else
                {
                    Console.WriteLine("Could not load file {0}...", arg);
                }
            }


            WriteDataToDB(sqlite, data, statistics);

            sqlite.Close();

            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine(" Added {0} files to the database", statistics.Added);
            Console.WriteLine(" Updated {0} files in the database", statistics.Updated);
            Console.WriteLine(" Added {0} columns to the database", statistics.ColumnsAdded);
            Console.WriteLine("--------------------------------------------------------------");
        }
Пример #18
0
 /// <summary>
 /// Get running ExifTool version.
 /// </summary>
 /// <param name="this">Instance of <see cref="AsyncExifTool"/> to use to execute this command. Cannot be <c>null</c>.</param>
 /// <param name="ct">Cancellation token. Optional. Defaults to <see cref="CancellationToken.None"/>.</param>
 /// <returns>ExifTool result containing the version information.</returns>
 /// <exception cref="ArgumentNullException">Thrown when <paramref name="this"/> is <c>null</c>.</exception>
 public static Task <string> GetVersionAsync([NotNull] this AsyncExifTool @this, CancellationToken ct = default)
 {
     return(ExecuteAsync(@this, ExifToolArguments.Version, ct));
 }
Пример #19
0
        public static async Task Main()
        {
            ConfigureNLog();
            var nlogLogger = LogManager.GetCurrentClassLogger(typeof(AsyncExifTool));

            Console.WriteLine("Sample application using AsyncExifTool in combination with NLog");

            // AsyncExifTool configuration. Please make sure exiftool.exe is accessible.
            var commonArgs = new List <string>();
            var asyncExifToolConfiguration = new AsyncExifToolConfiguration(
                "exiftool.exe",
                Encoding.UTF8,
                commonArgs);

            // Create a logger for AsyncExifTool. AsyncExifTool does not require any logging framework. You have to write your own adapter.
            var logger = new AsyncExifToolToNLogAdapter(nlogLogger);

            // Create AsyncExifTool instance. You can also do this without a logger.
            // ie:
            // await using var exiftool = new AsyncExifTool(asyncExifToolConfiguration);
            await using var exiftool = new AsyncExifTool(asyncExifToolConfiguration, logger);
            try
            {
                // initialize. At this point the exiftool process is started.
                // this call might throw an exception.
                exiftool.Initialize();
            }
            catch (AsyncExifToolInitialisationException e)
            {
                Console.WriteLine(e);
                Console.WriteLine("press enter to exit");
                Console.ReadKey();
                return;
            }

            // Just some calls to ExifTool (using an extension method)
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(await exiftool.GetVersionAsync());
            }

            try
            {
                var result = await exiftool.ExecuteAsync("dummy command");

                Console.WriteLine("dummy command result: " + result);
            }
            catch (Exception e)
            {
                Console.WriteLine("dummy command result exception: " + e.Message);
            }

            var file = @"1.jpg";

            try
            {
                Console.WriteLine("Add person to existing image.");
                var result = await exiftool.ExecuteAsync(new[] { "-Xmp:PersonInImage+=\"Test person\"", file });

                Console.WriteLine($"RESULT: {result}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"ERROR MSG: {e.Message}");
            }

            Console.WriteLine(string.Empty);

            try
            {
                Console.WriteLine("Add person to NON existing image.");
                var result = await exiftool.ExecuteAsync(new[] { "-Xmp:PersonInImage+=\"Test person\"", file + @"xxx" });

                Console.WriteLine($"RESULT: {result}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"ERROR MSG: {e.Message}");
            }
            Console.WriteLine(string.Empty);

            try
            {
                Console.WriteLine("Get person information from image.");
                var result = await exiftool.ExecuteAsync(new[] { "-Xmp:PersonInImage", file });

                Console.WriteLine($"RESULT: {result}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"ERROR MSG: {e.Message}");
            }

            Console.WriteLine(string.Empty);

            // we are done
            Console.WriteLine("press enter to exit");
            Console.ReadLine();
        }