// --------------------------------------------------------------------------------------------------------------------
//
// This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
//
//
// Handles the importing of Chapter information from CSV files
//
// --------------------------------------------------------------------------------------------------------------------
namespace HandBrakeWPF.Utilities.Input
{
using System;
using System.Collections.Generic;
using HandBrakeWPF.Exceptions;
using HandBrakeWPF.Properties;
using Microsoft.VisualBasic.FileIO;
///
/// Handles the importing of Chapter information from CSV files
///
internal class ChapterImporterCsv
{
///
/// The file filter value for the OpenFileDialog
///
public static string FileFilter => "CSV files (*.csv;*.tsv)|*.csv;*.tsv";
///
/// Imports all chapter information from the given into the dictionary.
///
///
/// The full path and filename of the chapter marker file to import
///
///
/// The imported Chapters.
///
public static void Import(string filename, ref Dictionary> importedChapters)
{
using (TextFieldParser csv = new TextFieldParser(filename)
{
CommentTokens = new[] { "#" }, // Comment lines
Delimiters = new[] { ",", "\t", ";", ":" }, // Support all of these common delimeter types
HasFieldsEnclosedInQuotes = true, // Assume that our data will be properly escaped
TextFieldType = FieldType.Delimited,
TrimWhiteSpace = true // Remove excess whitespace from ends of imported values
})
{
while (!csv.EndOfData)
{
try
{
// Only read the first two columns, anything else will be ignored but will not raise an error
var row = csv.ReadFields();
if (row == null || row.Length < 2) // null condition happens if the file is somehow corrupt during reading
throw new MalformedLineException(Resources.ChaptersViewModel_UnableToImportChaptersLineDoesNotHaveAtLeastTwoColumns, csv.LineNumber);
int chapterNumber;
if (!int.TryParse(row[0], out chapterNumber))
throw new MalformedLineException(Resources.ChaptersViewModel_UnableToImportChaptersFirstColumnMustContainOnlyIntegerNumber, csv.LineNumber);
// Store the chapter name at the correct index
importedChapters[chapterNumber] = new Tuple(row[1]?.Trim(), TimeSpan.Zero);
}
catch (MalformedLineException mlex)
{
throw new GeneralApplicationException(
Resources.ChaptersViewModel_UnableToImportChaptersWarning,
string.Format(Resources.ChaptersViewModel_UnableToImportChaptersMalformedLineMsg, mlex.LineNumber),
mlex);
}
}
}
}
}
}