Compare commits
No commits in common. "0d4a31c192250da882abb883469edb99eac8ab1a" and "696509c077aa77c4af2e6ab3f255303800549a12" have entirely different histories.
0d4a31c192
...
696509c077
@ -1,102 +0,0 @@
|
||||
using Microsoft.Graph;
|
||||
using Microsoft.Identity.Client;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Image_Sorter
|
||||
{
|
||||
public class AuthenticationHelper
|
||||
{
|
||||
// The Client ID is used by the application to uniquely identify itself to the v2.0 authentication endpoint.
|
||||
static string clientId = Program.MsaClientId;
|
||||
public static string[] Scopes = { "Files.Read.All" };
|
||||
public static IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId).WithRedirectUri("http://localhost:8192/oauth2callback/").Build();
|
||||
//public static PublicClientApplicationBuilder IdentityClientApp = PublicClientApplicationBuilder.Create(clientId);// new PublicClientApplication(clientId);
|
||||
|
||||
public static string AccessToken = null;
|
||||
public static IAccount UserAccount = null;
|
||||
|
||||
public static DateTimeOffset Expiration;
|
||||
|
||||
private static GraphServiceClient graphClient = null;
|
||||
|
||||
// Get an access token for the given context and resourceId. An attempt is first made to
|
||||
// acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
|
||||
public static GraphServiceClient GetAuthenticatedClient()
|
||||
{
|
||||
if (graphClient == null)
|
||||
{
|
||||
// Create Microsoft Graph client.
|
||||
try
|
||||
{
|
||||
graphClient = new GraphServiceClient(
|
||||
"https://graph.microsoft.com/v1.0",
|
||||
new DelegateAuthenticationProvider(
|
||||
async (requestMessage) =>
|
||||
{
|
||||
var token = await GetTokenForUserAsync();
|
||||
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
|
||||
// This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
|
||||
//requestMessage.Headers.Add("SampleID", "uwp-csharp-apibrowser-sample");
|
||||
|
||||
}));
|
||||
return graphClient;
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Could not create a graph client: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return graphClient;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Get Token for User.
|
||||
/// </summary>
|
||||
/// <returns>Token for user.</returns>
|
||||
public static async Task<string> GetTokenForUserAsync()
|
||||
{
|
||||
AuthenticationResult authResult;
|
||||
/*try
|
||||
{
|
||||
authResult = await app.AcquireTokenInteractive(null).WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount).ExecuteAsync();
|
||||
AccessToken = authResult.AccessToken;
|
||||
UserAccount = authResult.Account;
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
//Console.WriteLine(e);
|
||||
}*/
|
||||
// Attempt to aquire an existing token. If we're already authed, the existing account will be valid
|
||||
try
|
||||
{
|
||||
authResult = await app.AcquireTokenSilent(Scopes, UserAccount).ExecuteAsync();
|
||||
AccessToken = authResult.AccessToken;
|
||||
UserAccount = authResult.Account;
|
||||
}
|
||||
|
||||
catch (Exception)
|
||||
{
|
||||
if (AccessToken == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
|
||||
{
|
||||
authResult = await app.AcquireTokenInteractive(null).WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount).ExecuteAsync();
|
||||
|
||||
AccessToken = authResult.AccessToken;
|
||||
UserAccount = authResult.Account;
|
||||
Expiration = authResult.ExpiresOn;
|
||||
}
|
||||
}
|
||||
|
||||
return AccessToken;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,20 +1,82 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{6739EA9D-6361-4B5B-B687-07C30FB82B3B}</ProjectGuid>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0-windows</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<StartupObject>Image_Sorter.Program</StartupObject>
|
||||
<DisableWinExeOutputInference>true</DisableWinExeOutputInference>
|
||||
<RootNamespace>Image_Sorter</RootNamespace>
|
||||
<AssemblyName>Image Sorter</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Properties\" />
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="WindowsBase" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Graph" Version="3.29.0" />
|
||||
<PackageReference Include="Microsoft.Graph.Core" Version="1.25.1" />
|
||||
<PackageReference Include="Microsoft.Identity.Client" Version="4.29.0" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 and x64%29</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
@ -4,50 +4,24 @@ using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Microsoft.Graph;
|
||||
using Directory = System.IO.Directory;
|
||||
using File = System.IO.File;
|
||||
using FileSystemInfo = System.IO.FileSystemInfo;
|
||||
|
||||
namespace Image_Sorter
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static readonly List<string> DNGTypes = new List<string> {"raw", "cr2", "dng"};
|
||||
static readonly List<string> ImagePrefixes = new List<string> { "", "Screenshot_", "VID"};
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Worker(args);
|
||||
Console.ReadLine();
|
||||
}
|
||||
public const string MsaClientId = "";
|
||||
//public const string MsaReturnUrl = "urn:ietf:wg:oauth:2.0:oob";
|
||||
private static GraphServiceClient graphClient { get; set; }
|
||||
|
||||
|
||||
// Threading synchronisation
|
||||
static volatile SemaphoreSlim folderCreateMarshall = new(1);
|
||||
// Store created folders in a lookup
|
||||
static volatile Dictionary<string, DriveItem> CreatedFolderItems = new();
|
||||
|
||||
static readonly List<string> DNGTypes = new List<string> { "raw", "cr2", "dng" };
|
||||
static readonly List<string> ImagePrefixes = new List<string> { "", "Screenshot_", "VID" };
|
||||
static async void Worker(string[] args)
|
||||
{
|
||||
Console.WriteLine("Image Sorter {0} (C) 2021 Brychan Dempsey");
|
||||
Console.WriteLine("Image Sorter {0} (C)2019 Brychan Dempsey");
|
||||
Console.WriteLine("Moves images from the source folder and arranges them by date (from metadata) in the destination folder");
|
||||
string SourceDir = "";
|
||||
string DestinationDir = "";
|
||||
|
||||
string OneDriveSourceDir = "";
|
||||
string OneDriveDestinationDir = "";
|
||||
|
||||
DriveItem OneDriveSourceItem = null;
|
||||
DriveItem OneDriveDestItem = null;
|
||||
|
||||
bool copyFiles = false;
|
||||
if (args.Length > 0 && args[0].ToLower() == "\\s")
|
||||
if (args.Length > 0 && args[0].ToLower() == "\\s")
|
||||
{
|
||||
int sourceDirSpecified = Array.IndexOf(args, "\\d");
|
||||
if (sourceDirSpecified != -1)
|
||||
@ -92,6 +66,7 @@ namespace Image_Sorter
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Console.WriteLine("Enter the source directory:");
|
||||
SourceDir = Console.ReadLine();
|
||||
Console.WriteLine("Enter the destionation directory:");
|
||||
@ -107,348 +82,97 @@ namespace Image_Sorter
|
||||
}
|
||||
Console.WriteLine("Scanning the source directory...");
|
||||
List<string> SourceFiles = GetFiles(SourceDir);
|
||||
Console.WriteLine("Found {0} files", SourceFiles.Count);
|
||||
string OneDriveLoc = "";
|
||||
//Drive contextDrive = null;
|
||||
if (SourceDir.ToLower().Contains("onedrive"))
|
||||
{
|
||||
OneDriveLoc = SourceDir[0..(SourceDir.ToLower().IndexOf("onedrive\\") + "onedrive\\".Length)];
|
||||
}
|
||||
|
||||
bool OneDriveLogin = false;
|
||||
if ((File.GetAttributes(SourceDir).HasFlag(FileAttributes.Offline) || SourceDir.Contains("OneDrive") || SourceFiles.Any((x) => File.GetAttributes(SourceDir + x).HasFlag(FileAttributes.Offline))) && DestinationDir.Contains(OneDriveLoc))
|
||||
{
|
||||
Console.WriteLine("Source and target folders seem to be inside a OneDrive folder.\nWould you like to sign-in to OneDrive and manage files online?");
|
||||
string tRead = Console.ReadLine();
|
||||
if (tRead.Trim().ToLower().Equals("y"))
|
||||
{
|
||||
// Do a OneDrive login
|
||||
if (SourceDir.ToLower().Split("onedrive").Length > 2)
|
||||
{
|
||||
throw new ArgumentException("Cannot identify OneDrive source folder");
|
||||
}
|
||||
try
|
||||
{
|
||||
graphClient = AuthenticationHelper.GetAuthenticatedClient();
|
||||
// The user isn't yet logged in - formulate a request:
|
||||
User me = await graphClient.Me.Request().GetAsync();
|
||||
//contextDrive = await graphClient.Drives.Request().GetAsync();
|
||||
Console.WriteLine("Authentication of {0} successful. Welcome {1}.", AuthenticationHelper.UserAccount.Username, me.DisplayName);
|
||||
OneDriveLogin = true;
|
||||
OneDriveSourceDir = SourceDir.Replace(OneDriveLoc, "").Replace('\\', '/');
|
||||
OneDriveDestinationDir = DestinationDir.Replace(OneDriveLoc, "").Replace('\\', '/');
|
||||
if (!OneDriveSourceDir.StartsWith('/'))
|
||||
{
|
||||
OneDriveSourceDir = '/' + OneDriveSourceDir;
|
||||
}
|
||||
if (!OneDriveDestinationDir.StartsWith('/'))
|
||||
{
|
||||
OneDriveDestinationDir = '/' + OneDriveDestinationDir;
|
||||
}
|
||||
// Finally, evaluate the base source and destination folders
|
||||
OneDriveDestItem = await graphClient.Drive.Root.ItemWithPath(OneDriveDestinationDir).Request().GetAsync();
|
||||
OneDriveSourceItem = await graphClient.Drive.Root.ItemWithPath(OneDriveSourceDir).Request().GetAsync();
|
||||
}
|
||||
catch (ServiceException exception)
|
||||
{
|
||||
Console.WriteLine(exception);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
// Check if the folder is a OneDrive folder
|
||||
// Do Login if not already complete
|
||||
Console.WriteLine("Found {0} files", SourceFiles.Count());
|
||||
|
||||
int processedCount = 0;
|
||||
object countLock = new();
|
||||
|
||||
object folderLock = new();
|
||||
|
||||
|
||||
Task updateFilesTask = new(() =>
|
||||
object countLock = new object();
|
||||
Task updateFilesTask = new Task(() =>
|
||||
{
|
||||
_ = Parallel.ForEach(SourceFiles, async (filepath) =>
|
||||
{
|
||||
uint fab = (uint)File.GetAttributes(SourceDir + filepath);
|
||||
// It seems that FileAttributes.Offline is no longer used to store on-demand OneDrive file status.
|
||||
// One undefined flag - 1048576 - is set
|
||||
// As well as defined - 4194304 - FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS
|
||||
// We will check initially for the presense of both
|
||||
bool fileState = ((uint)fab & 1048576) == 1048576 && (fab & 4194304) == 4194304;
|
||||
if (OneDriveLogin && fileState)
|
||||
{
|
||||
Parallel.ForEach(SourceFiles, (filepath) =>
|
||||
{
|
||||
string fileDestination = "";
|
||||
DateTime photoDate = new DateTime();
|
||||
bool hasMetadata = true;
|
||||
using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
bool ruleMatch = false;
|
||||
Dictionary<string, string> imgMetadata = GetMetaData(fs);
|
||||
if (imgMetadata.ContainsKey("date"))
|
||||
{
|
||||
photoDate = DateTime.Parse(imgMetadata["date"]);
|
||||
ruleMatch = true;
|
||||
}
|
||||
// If the file is a negative, it may have a conjugate image file
|
||||
else if (DNGTypes.Contains(Path.GetExtension(filepath).TrimStart('.')))
|
||||
{
|
||||
List<string> matches = SourceFiles.FindAll((x) => Path.GetFileNameWithoutExtension(x).Equals(Path.GetFileNameWithoutExtension(filepath)) && !Path.GetExtension(x).Equals(Path.GetExtension(filepath)));
|
||||
if (matches.Count == 1)
|
||||
{
|
||||
using (FileStream tfs = new FileStream(matches[0], FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
imgMetadata = GetMetaData(tfs);
|
||||
}
|
||||
if (imgMetadata.ContainsKey("date"))
|
||||
{
|
||||
photoDate = DateTime.Parse(imgMetadata["date"]);
|
||||
Console.WriteLine(" Conjugate file found - " + Path.GetFileName(filepath));
|
||||
ruleMatch = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Try parsing a date by the rules set in ImagePrefixes, using the first if found
|
||||
else if (ImagePrefixes.Exists((x) => TryParseDate(Path.GetFileNameWithoutExtension(filepath).TrimStart(x.ToCharArray()), out photoDate)))
|
||||
{
|
||||
Console.WriteLine(" Date successfully parsed from file: {0} - Parsed Date: {1} ", Path.GetFileName(filepath), photoDate.ToString("dd-MM-yyyy"));
|
||||
ruleMatch = true;
|
||||
}
|
||||
// Failsafe to avoid implausable dates (Greater than system year + 10, < 1990)
|
||||
if (ruleMatch && (photoDate.Year > DateTime.Now.Year + 10 || photoDate.Year < 1990))
|
||||
{
|
||||
ruleMatch = false;
|
||||
}
|
||||
// Finally, resort to the least of the file creation time && file modified time
|
||||
if (!ruleMatch)
|
||||
{
|
||||
FileSystemInfo fileInfo = new FileInfo(filepath);
|
||||
photoDate = fileInfo.CreationTime < fileInfo.LastWriteTime ? fileInfo.CreationTime : fileInfo.LastWriteTime;
|
||||
}
|
||||
}
|
||||
fileDestination = "\\" + photoDate.Year;
|
||||
fileDestination += "\\" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(photoDate.Month);
|
||||
Directory.CreateDirectory(DestinationDir + fileDestination + "\\");
|
||||
fileDestination += "\\" + filepath.Remove(0, filepath.LastIndexOf("\\"));
|
||||
if (copyFiles)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(filepath, DestinationDir + fileDestination);
|
||||
filepath = DestinationDir + fileDestination;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.WriteLine("Failed to copy {0}", Path.GetFileName(filepath));
|
||||
}
|
||||
|
||||
// File is online-only, process via OneDrive API
|
||||
DriveItem file = null;
|
||||
DriveItem newFolder = null;
|
||||
DriveItem subFolder = null;
|
||||
try
|
||||
{
|
||||
file = await graphClient.Drive.Root.ItemWithPath(OneDriveSourceDir + filepath.Replace('\\', '/')).Request().GetAsync();
|
||||
}
|
||||
catch (ServiceException ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(filepath, DestinationDir + fileDestination);
|
||||
filepath = DestinationDir + fileDestination;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.WriteLine("Failed to move {0}", Path.GetFileName(filepath));
|
||||
}
|
||||
|
||||
// Folder creation will cause a race condition (which modifies the base object),
|
||||
// Need to intelligently handle this; threads that are simultaneously trying to create the same folder
|
||||
// must wait; if the folder exists, we don't need to create it.
|
||||
|
||||
// Therefore, a semaphore must be used to determine the current state of access
|
||||
|
||||
// To handle this smartly, we create a boolean that suggests if the folder is being created (Marshalled by a semaphore)
|
||||
// The first thread to reach it will set it to true, then check if it exists asynchronously
|
||||
DateTime fileTime = DateTime.MinValue;
|
||||
if (file.Photo.TakenDateTime != null)
|
||||
{
|
||||
DateTimeOffset dateTimeOffset = (DateTimeOffset)file.Photo.TakenDateTime;
|
||||
fileTime = dateTimeOffset.LocalDateTime;
|
||||
}
|
||||
else
|
||||
{
|
||||
fileTime = file.FileSystemInfo.CreatedDateTime < file.FileSystemInfo.LastModifiedDateTime ? file.FileSystemInfo.CreatedDateTime.Value.LocalDateTime : file.FileSystemInfo.LastModifiedDateTime.Value.LocalDateTime;
|
||||
}
|
||||
|
||||
|
||||
if (fileTime != DateTime.MinValue)
|
||||
{
|
||||
// Get the destination folder. If
|
||||
if (folderCreateMarshall.CurrentCount > 0 && CreatedFolderItems.ContainsKey(fileTime.Year.ToString()))
|
||||
{
|
||||
newFolder = CreatedFolderItems[fileTime.Year.ToString()];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create a folder object and wait
|
||||
|
||||
DriveItem tempNewFolder = new()
|
||||
{
|
||||
Name = fileTime.Year.ToString(),
|
||||
Folder = new Folder(),
|
||||
AdditionalData = new Dictionary<string, object>
|
||||
{
|
||||
{ "@microsoft.graph.conflictBehavior", "fail" }
|
||||
}
|
||||
};
|
||||
// Wait for our turn to create the object
|
||||
await folderCreateMarshall.WaitAsync();
|
||||
try
|
||||
{
|
||||
// Check the folder wasn't surprise created
|
||||
if (CreatedFolderItems.ContainsKey(fileTime.Year.ToString()))
|
||||
{
|
||||
newFolder = CreatedFolderItems[fileTime.Year.ToString()];
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Creating Folder");
|
||||
// Folder doesn't exist or wasn't added; create and add
|
||||
newFolder = await graphClient.Drive.Root.ItemWithPath(OneDriveDestinationDir)
|
||||
.Children.Request().AddAsync(tempNewFolder);
|
||||
CreatedFolderItems.Add(fileTime.Year.ToString(), newFolder);
|
||||
}
|
||||
|
||||
}
|
||||
catch (ServiceException ex)
|
||||
{
|
||||
// TODO: Handle the existing item
|
||||
if (ex.StatusCode == System.Net.HttpStatusCode.Conflict)
|
||||
{
|
||||
try
|
||||
{
|
||||
newFolder = await graphClient.Drive.Root.ItemWithPath(OneDriveDestinationDir + "/" + fileTime.Year.ToString()).Request().GetAsync();
|
||||
CreatedFolderItems.Add(fileTime.Year.ToString(), newFolder);
|
||||
}
|
||||
catch (ServiceException exNF)
|
||||
{
|
||||
Console.WriteLine(exNF);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
folderCreateMarshall.Release();
|
||||
}
|
||||
}
|
||||
|
||||
if (folderCreateMarshall.CurrentCount > 0 && CreatedFolderItems.ContainsKey(fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month)))
|
||||
{
|
||||
subFolder = CreatedFolderItems[fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month)];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create a folder and wait
|
||||
DriveItem tempNewFolder = new()
|
||||
{
|
||||
Name = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month),
|
||||
Folder = new Folder(),
|
||||
AdditionalData = new Dictionary<string, object>
|
||||
{
|
||||
{ "@microsoft.graph.conflictBehavior", "fail" }
|
||||
}
|
||||
};
|
||||
await folderCreateMarshall.WaitAsync();
|
||||
try
|
||||
{
|
||||
// Check the folder wasn't surprise created
|
||||
if (CreatedFolderItems.ContainsKey(fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month)))
|
||||
{
|
||||
subFolder = CreatedFolderItems[fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month)];
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("Creating Subfolder");
|
||||
// Folder doesn't exist or wasn't added; create and add
|
||||
subFolder = await graphClient.Drive.Root.ItemWithPath(OneDriveDestinationDir + "/" + fileTime.Year.ToString())
|
||||
.Children.Request().AddAsync(tempNewFolder);
|
||||
CreatedFolderItems.Add(fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month), subFolder);
|
||||
}
|
||||
|
||||
}
|
||||
catch (ServiceException ex)
|
||||
{
|
||||
if (ex.StatusCode == System.Net.HttpStatusCode.Conflict)
|
||||
{
|
||||
try
|
||||
{
|
||||
subFolder = await graphClient.Drive.Root.ItemWithPath(OneDriveDestinationDir + "/" + fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month)).Request().GetAsync();
|
||||
CreatedFolderItems.Add(fileTime.Year.ToString() + "/" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(fileTime.Month), subFolder);
|
||||
}
|
||||
catch (ServiceException exNF)
|
||||
{
|
||||
Console.WriteLine(exNF);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
folderCreateMarshall.Release();
|
||||
}
|
||||
}
|
||||
// Finally, get the resulting files
|
||||
ItemReference parentReference = new()
|
||||
{
|
||||
Id = subFolder.Id
|
||||
};
|
||||
try
|
||||
{
|
||||
// Fail-fast, copy item first
|
||||
if (await graphClient.Me.Drive.Items[file.Id].Copy(null, parentReference).Request().PostAsync() != file && !copyFiles)
|
||||
{
|
||||
// Only if the returned file is not a duplicate, and we aren't copying, shall we remove the old file
|
||||
await graphClient.Drive.Items[file.Id].Request().DeleteAsync();
|
||||
}
|
||||
}
|
||||
catch (ServiceException ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
string fileDestination = "";
|
||||
DateTime photoDate = new();
|
||||
bool hasMetadata = true;
|
||||
using (FileStream fs = new(SourceDir + filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
// If the file is online-only, allow a large amount of time to download
|
||||
if (fileState)
|
||||
{
|
||||
fs.ReadTimeout = (int)TimeSpan.FromMinutes(60).TotalMilliseconds; // Allow about 60 minutes for a download; should be enough for even large concurrent downloads
|
||||
}
|
||||
bool ruleMatch = false;
|
||||
Dictionary<string, string> imgMetadata = GetMetaData(fs);
|
||||
if (imgMetadata.ContainsKey("date"))
|
||||
{
|
||||
photoDate = DateTime.Parse(imgMetadata["date"]);
|
||||
ruleMatch = true;
|
||||
}
|
||||
// If the file is a negative, it may have a conjugate image file
|
||||
else if (DNGTypes.Contains(Path.GetExtension(filepath).TrimStart('.')))
|
||||
{
|
||||
List<string> matches = SourceFiles.FindAll((x) => Path.GetFileNameWithoutExtension(x).Equals(Path.GetFileNameWithoutExtension(SourceDir + filepath)) && !Path.GetExtension(x).Equals(Path.GetExtension(SourceDir + filepath)));
|
||||
if (matches.Count == 1)
|
||||
{
|
||||
using (FileStream tfs = new(matches[0], FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
imgMetadata = GetMetaData(tfs);
|
||||
}
|
||||
if (imgMetadata.ContainsKey("date"))
|
||||
{
|
||||
photoDate = DateTime.Parse(imgMetadata["date"]);
|
||||
Console.WriteLine(" Conjugate file found - " + Path.GetFileName(SourceDir + filepath));
|
||||
ruleMatch = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Try parsing a date by the rules set in ImagePrefixes, using the first if found
|
||||
else if (ImagePrefixes.Exists((x) => TryParseDate(Path.GetFileNameWithoutExtension(SourceDir + filepath).TrimStart(x.ToCharArray()), out photoDate)))
|
||||
{
|
||||
Console.WriteLine(" Date successfully parsed from file: {0} - Parsed Date: {1} ", Path.GetFileName(SourceDir + filepath), photoDate.ToString("dd-MM-yyyy"));
|
||||
ruleMatch = true;
|
||||
}
|
||||
// Failsafe to avoid implausable dates (Greater than system year + 10, < 1990)
|
||||
if (ruleMatch && (photoDate.Year > DateTime.Now.Year + 10 || photoDate.Year < 1990))
|
||||
{
|
||||
ruleMatch = false;
|
||||
}
|
||||
// Finally, resort to the least of the file creation time && file modified time
|
||||
if (!ruleMatch)
|
||||
{
|
||||
FileSystemInfo fileInfo = new FileInfo(SourceDir + filepath);
|
||||
photoDate = fileInfo.CreationTime < fileInfo.LastWriteTime ? fileInfo.CreationTime : fileInfo.LastWriteTime;
|
||||
}
|
||||
}
|
||||
fileDestination = "\\" + photoDate.Year;
|
||||
fileDestination += "\\" + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(photoDate.Month);
|
||||
Directory.CreateDirectory(DestinationDir + fileDestination + "\\");
|
||||
fileDestination += "\\" + filepath[filepath.LastIndexOf('\\')..];
|
||||
if (copyFiles)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(SourceDir + filepath, DestinationDir + fileDestination);
|
||||
filepath = DestinationDir + fileDestination;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.WriteLine("Failed to copy {0}", Path.GetFileName(SourceDir + filepath));
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Move(SourceDir + filepath, DestinationDir + fileDestination);
|
||||
filepath = DestinationDir + fileDestination;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Console.WriteLine("Failed to move {0}", Path.GetFileName(SourceDir + filepath));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
lock (countLock)
|
||||
{
|
||||
processedCount++;
|
||||
}
|
||||
});
|
||||
}
|
||||
lock (countLock)
|
||||
{
|
||||
processedCount++;
|
||||
}
|
||||
});
|
||||
});
|
||||
int lastProcessed = 0;
|
||||
updateFilesTask.Start();
|
||||
@ -468,9 +192,10 @@ namespace Image_Sorter
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
Console.ReadLine();
|
||||
|
||||
}
|
||||
|
||||
static Dictionary<string, string> GetMetaData(FileStream fileStream)
|
||||
static Dictionary<string,string> GetMetaData(FileStream fileStream)
|
||||
{
|
||||
|
||||
Dictionary<string, string> Metadata = new Dictionary<string, string>();
|
||||
@ -491,12 +216,9 @@ namespace Image_Sorter
|
||||
return Metadata;
|
||||
}
|
||||
|
||||
|
||||
static List<string> GetFiles(string SourceDirectory)
|
||||
{
|
||||
// Get the files, remove the source
|
||||
// This gives us a source list with relative pathing. This allows OneDrive files to be easily incorporated
|
||||
List<string> foundFiles = Directory.GetFiles(SourceDirectory, "*", SearchOption.TopDirectoryOnly).Select((s) => s.Replace(SourceDirectory, "")).ToList();
|
||||
List<string> foundFiles = Directory.GetFiles(SourceDirectory, "*", SearchOption.TopDirectoryOnly).ToList();
|
||||
foreach (var subDirectory in Directory.GetDirectories(SourceDirectory))
|
||||
{
|
||||
foundFiles.AddRange(GetFiles(subDirectory));
|
||||
@ -547,7 +269,7 @@ namespace Image_Sorter
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (result.Year <= DateTime.Now.Year + 10 && result.Year >= 1980)
|
||||
if (result.Year <= DateTime.Now.Year+10 && result.Year >= 1980)
|
||||
{
|
||||
// Falls within an acceptable date range, so try use it as a date
|
||||
dt = result;
|
||||
|
36
Image Sorter/Properties/AssemblyInfo.cs
Normal file
36
Image Sorter/Properties/AssemblyInfo.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("Image Sorter")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("Image Sorter")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2019")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("6739ea9d-6361-4b5b-b687-07c30fb82b3b")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Loading…
x
Reference in New Issue
Block a user