aboutsummaryrefslogtreecommitdiff
path: root/src/Commands/ExtractCommand.cs
blob: 5872fd6ba83779ee005e8c117a9f2d5ec1dbee8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.CommandLineUtils;

namespace iPhotoExtractor.Commands
{
    public class ExtractCommand : ICommand
    {
        public static void Configure(CommandLineApplication command)
        {
            command.HelpOption("-h|--help");
            command.Description = "Copy photos from their original locations to a directory " +
                "structure mirroring the event albums within iPhoto.";

            var libPathArgument = command.Argument(
                "library_dir",
                "Path to the iPhoto library directory.");

            var outputDirArgument = command.Argument(
                "[output_dir]",
                "Path to the directory where the extracted photos will be copied.");

            command.OnExecute(() =>
            {
                (new ExtractCommand(libPathArgument.Value, outputDirArgument.Value)).Run();
                return 0;
            });
        }

        private readonly string _libraryDir;
        private readonly string _outputDir;

        public ExtractCommand(string libraryDir, string outputDir)
        {
            _libraryDir = libraryDir;
            _outputDir = outputDir;
        }

        public void Run()
        {
            var libraryDir = String.IsNullOrWhiteSpace(_libraryDir) ?
                Directory.GetCurrentDirectory() :
                _libraryDir;

            var outputDir = String.IsNullOrWhiteSpace(_outputDir) ?
                Path.Combine(Directory.GetCurrentDirectory(), "Extracted Photos") :
                _outputDir;

            var dbPath = Path.Combine(libraryDir, "iPhotoMain.db");

            if (!File.Exists(dbPath))
            {
                Console.WriteLine($"File '{dbPath}' not found.");
                return;
            }

            if (Directory.Exists(outputDir))
            {
                Console.Write($"Warning: directory '{outputDir}' already exists. Continue (y/n)? ");
                var response = Console.ReadLine().Trim().ToLower();

                if (response != "y" && response != "yes")
                    return;
            }

            Directory.CreateDirectory(outputDir);

            var photoStore = new PhotoStore(dbPath);
            List<Photo> photos = photoStore.GetAllPhotos();

            Dictionary<string, List<Photo>> albums = photos
                .GroupBy(p => p.AlbumName)
                .ToDictionary(g => g.Key, g => g.ToList());

            Console.WriteLine($"Found {albums.Keys.Count} albums.");
            var counter = 1;

            foreach (string album in albums.Keys)
            {
                var albumPhotos = albums[album];
                var s = albumPhotos.Count == 1 ? "" : "s";

                Console.WriteLine($"[{counter}/{albums.Keys.Count}] Extracting album '{album}' " +
                    $"({albumPhotos.Count} photo{s})...");

                ExtractAlbum(libraryDir, outputDir, album, albumPhotos);
                counter++;
            }

            Console.WriteLine("Done.");
        }

        private void ExtractAlbum(
            string libraryDir,
            string outputDir,
            string albumName,
            List<Photo> photos)
        {
            string albumDir = String.IsNullOrWhiteSpace(albumName) ?
                Path.Combine(outputDir, "Untitled Album") :
                Path.Combine(outputDir, albumName);

            if (!Directory.Exists(albumDir))
                Directory.CreateDirectory(albumDir);

            var hasModified = photos.Any(p => p.HasModifiedVersion());
            string originalsDir = Path.Combine(albumDir, "Originals");

            if (hasModified && !Directory.Exists(originalsDir))
                Directory.CreateDirectory(originalsDir);

            foreach (var photo in photos)
            {
                List<string> paths = photo.GetUniquePaths(PhotoPathType.Modified);
                bool isModified = false;

                if (paths.Any())
                {
                    isModified = true;

                    foreach (string path in paths)
                    {
                        CopyPhoto(libraryDir, albumDir, path);
                    }
                }

                paths = photo.GetUniquePaths(PhotoPathType.Original);
                string destDir = isModified ? originalsDir : albumDir;

                foreach (string path in paths)
                {
                    CopyPhoto(libraryDir, destDir, path);
                }
            }
        }

        private void CopyPhoto(string libraryDir, string destDir, string relativePhotoPath)
        {
            string fileName = Path.GetFileNameWithoutExtension(relativePhotoPath);
            string extension = Path.GetExtension(relativePhotoPath);
            string destFileName = $"{fileName}{extension}";
            var suffix = 2;

            while (File.Exists(Path.Combine(destDir, destFileName)))
            {
                destFileName = $"{fileName} ({suffix}){extension}";
                suffix++;
            }

            string sourcePath = Path.Combine(libraryDir, relativePhotoPath);
            string destPath = Path.Combine(destDir, destFileName);

            File.Copy(sourcePath, destPath);
        }
    }
}