Update DB Schema, Change Artist Slugs, Rework SubtitleFiles to LyricFiles

pull/6/head
Qstick 7 years ago
parent 6718d82432
commit f1b1904e07

@ -35,7 +35,7 @@ function EpisodeStatus(props) {
{...queueItem}
progressBar={
<ProgressBar
title={`Episode is downloading - ${progress.toFixed(1)}% ${queueItem.title}`}
title={`Album is downloading - ${progress.toFixed(1)}% ${queueItem.title}`}
progress={progress}
kind={kinds.PURPLE}
size={sizes.MEDIUM}
@ -51,7 +51,7 @@ function EpisodeStatus(props) {
<div className={styles.center}>
<Icon
name={icons.DOWNLOADING}
title="Episode is downloading"
title="Album is downloading"
/>
</div>
);
@ -67,7 +67,7 @@ function EpisodeStatus(props) {
quality={quality}
size={trackFile.size}
isCutoffNotMet={isCutoffNotMet}
title="Episode Downloaded"
title="Track Downloaded"
/>
</div>
);
@ -89,7 +89,7 @@ function EpisodeStatus(props) {
<div className={styles.center}>
<Icon
name={icons.UNMONITORED}
title="Episode is not monitored"
title="Album is not monitored"
/>
</div>
);
@ -100,7 +100,7 @@ function EpisodeStatus(props) {
<div className={styles.center}>
<Icon
name={icons.MISSING}
title="Episode missing from disk"
title="Track missing from disk"
/>
</div>
);
@ -110,7 +110,7 @@ function EpisodeStatus(props) {
<div className={styles.center}>
<Icon
name={icons.NOT_AIRED}
title="Episode has not aired"
title="Album has not aired"
/>
</div>
);

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.DataAugmentation.Scene;
using NzbDrone.Core.Datastore.Events;
using NzbDrone.Core.MediaCover;
using NzbDrone.Core.MediaFiles;

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.10
VisualStudioVersion = 15.0.27004.2002
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{57A04B72-8088-4F75-A582-1158CF8291F7}"
EndProject

@ -1,33 +0,0 @@
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.DataAugmentation.Scene;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Test.Common.Categories;
namespace NzbDrone.Core.Test.DataAugmentation.Scene
{
[TestFixture]
[IntegrationTest]
public class SceneMappingProxyFixture : CoreTest<SceneMappingProxy>
{
[SetUp]
public void Setup()
{
UseRealHttp();
}
[Test]
public void fetch_should_return_list_of_mappings()
{
var mappings = Subject.Fetch();
mappings.Should().NotBeEmpty();
mappings.Should().NotContain(c => c.SearchTerm.IsNullOrWhiteSpace());
mappings.Should().NotContain(c => c.Title.IsNullOrWhiteSpace());
mappings.Should().Contain(c => c.SeasonNumber > 0);
}
}
}

@ -1,338 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using NzbDrone.Core.DataAugmentation.Scene;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Test.Common;
using FluentAssertions;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.DataAugmentation;
namespace NzbDrone.Core.Test.DataAugmentation.Scene
{
[TestFixture]
public class SceneMappingServiceFixture : CoreTest<SceneMappingService>
{
private List<SceneMapping> _fakeMappings;
private Mock<ISceneMappingProvider> _provider1;
private Mock<ISceneMappingProvider> _provider2;
[SetUp]
public void Setup()
{
_fakeMappings = Builder<SceneMapping>.CreateListOfSize(5).BuildListOfNew();
_fakeMappings[0].SearchTerm = "Words";
_fakeMappings[1].SearchTerm = "That";
_fakeMappings[2].SearchTerm = "Can";
_fakeMappings[3].SearchTerm = "Be";
_fakeMappings[4].SearchTerm = "Cleaned";
_fakeMappings[0].ParseTerm = "Words";
_fakeMappings[1].ParseTerm = "That";
_fakeMappings[2].ParseTerm = "Can";
_fakeMappings[3].ParseTerm = "Be";
_fakeMappings[4].ParseTerm = "Cleaned";
_provider1 = new Mock<ISceneMappingProvider>();
_provider1.Setup(s => s.GetSceneMappings()).Returns(_fakeMappings);
_provider2 = new Mock<ISceneMappingProvider>();
_provider2.Setup(s => s.GetSceneMappings()).Returns(_fakeMappings);
}
private void GivenProviders(IEnumerable<Mock<ISceneMappingProvider>> providers)
{
Mocker.SetConstant<IEnumerable<ISceneMappingProvider>>(providers.Select(s => s.Object));
}
[Test]
public void should_purge_existing_mapping_and_add_new_ones()
{
GivenProviders(new [] { _provider1 });
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(_fakeMappings);
Subject.Execute(new UpdateSceneMappingCommand());
AssertMappingUpdated();
}
[Test]
public void should_not_delete_if_fetch_fails()
{
GivenProviders(new[] { _provider1 });
_provider1.Setup(c => c.GetSceneMappings()).Throws(new WebException());
Subject.Execute(new UpdateSceneMappingCommand());
AssertNoUpdate();
ExceptionVerification.ExpectedErrors(1);
}
[Test]
public void should_not_delete_if_fetch_returns_empty_list()
{
GivenProviders(new[] { _provider1 });
_provider1.Setup(c => c.GetSceneMappings()).Returns(new List<SceneMapping>());
Subject.Execute(new UpdateSceneMappingCommand());
AssertNoUpdate();
ExceptionVerification.ExpectedWarns(1);
}
[Test]
public void should_get_mappings_for_all_providers()
{
GivenProviders(new[] { _provider1, _provider2 });
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(_fakeMappings);
Subject.Execute(new UpdateSceneMappingCommand());
_provider1.Verify(c => c.GetSceneMappings(), Times.Once());
_provider2.Verify(c => c.GetSceneMappings(), Times.Once());
}
[Test]
public void should_refresh_cache_if_cache_is_empty_when_looking_for_tvdb_id()
{
Subject.FindTvdbId("title");
Mocker.GetMock<ISceneMappingRepository>()
.Verify(v => v.All(), Times.Once());
}
[Test]
public void should_not_refresh_cache_if_cache_is_not_empty_when_looking_for_tvdb_id()
{
GivenProviders(new[] { _provider1 });
Mocker.GetMock<ISceneMappingRepository>()
.Setup(s => s.All())
.Returns(Builder<SceneMapping>.CreateListOfSize(1).Build());
Subject.Execute(new UpdateSceneMappingCommand());
Mocker.GetMock<ISceneMappingRepository>()
.Verify(v => v.All(), Times.Once());
Subject.FindTvdbId("title");
Mocker.GetMock<ISceneMappingRepository>()
.Verify(v => v.All(), Times.Once());
}
[Test]
public void should_not_add_mapping_with_blank_title()
{
GivenProviders(new[] { _provider1 });
var fakeMappings = Builder<SceneMapping>.CreateListOfSize(2)
.TheLast(1)
.With(m => m.Title = null)
.Build()
.ToList();
_provider1.Setup(s => s.GetSceneMappings()).Returns(fakeMappings);
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(_fakeMappings);
Subject.Execute(new UpdateSceneMappingCommand());
Mocker.GetMock<ISceneMappingRepository>().Verify(c => c.InsertMany(It.Is<IList<SceneMapping>>(m => !m.Any(s => s.Title.IsNullOrWhiteSpace()))), Times.Once());
ExceptionVerification.ExpectedWarns(1);
}
[Test]
public void should_not_add_mapping_with_blank_search_title()
{
GivenProviders(new[] { _provider1 });
var fakeMappings = Builder<SceneMapping>.CreateListOfSize(2)
.TheLast(1)
.With(m => m.SearchTerm = null)
.Build()
.ToList();
_provider1.Setup(s => s.GetSceneMappings()).Returns(fakeMappings);
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(_fakeMappings);
Subject.Execute(new UpdateSceneMappingCommand());
Mocker.GetMock<ISceneMappingRepository>().Verify(c => c.InsertMany(It.Is<IList<SceneMapping>>(m => !m.Any(s => s. SearchTerm.IsNullOrWhiteSpace()))), Times.Once());
ExceptionVerification.ExpectedWarns(1);
}
[TestCase("Working!!", "Working!!", 1)]
[TestCase("Working`!!", "Working`!!", 2)]
[TestCase("Working!!!", "Working!!!", 3)]
[TestCase("Working!!!!", "Working!!!", 3)]
[TestCase("Working !!", "Working!!", 1)]
public void should_return_single_match(string parseTitle, string title, int expectedSeasonNumber)
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Working!!", ParseTerm = "working", SearchTerm = "Working!!", TvdbId = 100, SceneSeasonNumber = 1 },
new SceneMapping { Title = "Working`!!", ParseTerm = "working", SearchTerm = "Working`!!", TvdbId = 100, SceneSeasonNumber = 2 },
new SceneMapping { Title = "Working!!!", ParseTerm = "working", SearchTerm = "Working!!!", TvdbId = 100, SceneSeasonNumber = 3 },
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
var tvdbId = Subject.FindTvdbId(parseTitle);
var seasonNumber = Subject.GetSceneSeasonNumber(parseTitle);
tvdbId.Should().Be(100);
seasonNumber.Should().Be(expectedSeasonNumber);
}
[Test]
public void should_return_alternate_title_for_global_season()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fudanshi Koukou Seikatsu 1", ParseTerm = "fudanshikoukouseikatsu1", SearchTerm = "Fudanshi Koukou Seikatsu 1", TvdbId = 100, SeasonNumber = null, SceneSeasonNumber = null },
new SceneMapping { Title = "Fudanshi Koukou Seikatsu 2", ParseTerm = "fudanshikoukouseikatsu2", SearchTerm = "Fudanshi Koukou Seikatsu 2", TvdbId = 100, SeasonNumber = -1, SceneSeasonNumber = null },
new SceneMapping { Title = "Fudanshi Koukou Seikatsu 3", ParseTerm = "fudanshikoukouseikatsu3", SearchTerm = "Fudanshi Koukou Seikatsu 3", TvdbId = 100, SeasonNumber = null, SceneSeasonNumber = -1 },
new SceneMapping { Title = "Fudanshi Koukou Seikatsu 4", ParseTerm = "fudanshikoukouseikatsu4", SearchTerm = "Fudanshi Koukou Seikatsu 4", TvdbId = 100, SeasonNumber = -1, SceneSeasonNumber = -1 },
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
var names = Subject.GetSceneNames(100, new List<int> { 10 }, new List<int> { 10 });
names.Should().HaveCount(4);
}
[Test]
public void should_return_alternate_title_for_season()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fudanshi Koukou Seikatsu", ParseTerm = "fudanshikoukouseikatsu", SearchTerm = "Fudanshi Koukou Seikatsu", TvdbId = 100, SeasonNumber = 1, SceneSeasonNumber = null }
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
var names = Subject.GetSceneNames(100, new List<int> { 1 }, new List<int> { 10 });
names.Should().HaveCount(1);
}
[Test]
public void should_not_return_alternate_title_for_season()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fudanshi Koukou Seikatsu", ParseTerm = "fudanshikoukouseikatsu", SearchTerm = "Fudanshi Koukou Seikatsu", TvdbId = 100, SeasonNumber = 1, SceneSeasonNumber = null }
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
var names = Subject.GetSceneNames(100, new List<int> { 2 }, new List<int> { 10 });
names.Should().BeEmpty();
}
[Test]
public void should_return_alternate_title_for_sceneseason()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fudanshi Koukou Seikatsu", ParseTerm = "fudanshikoukouseikatsu", SearchTerm = "Fudanshi Koukou Seikatsu", TvdbId = 100, SeasonNumber = null, SceneSeasonNumber = 1 }
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
var names = Subject.GetSceneNames(100, new List<int> { 10 }, new List<int> { 1 });
names.Should().HaveCount(1);
}
[Test]
public void should_not_return_alternate_title_for_sceneseason()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fudanshi Koukou Seikatsu", ParseTerm = "fudanshikoukouseikatsu", SearchTerm = "Fudanshi Koukou Seikatsu", TvdbId = 100, SeasonNumber = null, SceneSeasonNumber = 1 }
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
var names = Subject.GetSceneNames(100, new List<int> { 10 }, new List<int> { 2 });
names.Should().BeEmpty();
}
[Test]
public void should_return_alternate_title_for_fairy_tail()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fairy Tail S2", ParseTerm = "fairytails2", SearchTerm = "Fairy Tail S2", TvdbId = 100, SeasonNumber = null, SceneSeasonNumber = 2 }
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
Subject.GetSceneNames(100, new List<int> { 4 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 5 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 6 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 7 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 20 }, new List<int> { 1 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 20 }, new List<int> { 2 }).Should().NotBeEmpty();
Subject.GetSceneNames(100, new List<int> { 20 }, new List<int> { 3 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 20 }, new List<int> { 4 }).Should().BeEmpty();
}
[Test]
public void should_return_alternate_title_for_fudanshi()
{
var mappings = new List<SceneMapping>
{
new SceneMapping { Title = "Fudanshi Koukou Seikatsu", ParseTerm = "fudanshikoukouseikatsu", SearchTerm = "Fudanshi Koukou Seikatsu", TvdbId = 100, SeasonNumber = null, SceneSeasonNumber = 1 }
};
Mocker.GetMock<ISceneMappingRepository>().Setup(c => c.All()).Returns(mappings);
Subject.GetSceneNames(100, new List<int> { 1 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 2 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 3 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 4 }, new List<int> { 20 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 1 }, new List<int> { 1 }).Should().NotBeEmpty();
Subject.GetSceneNames(100, new List<int> { 2 }, new List<int> { 2 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 3 }, new List<int> { 3 }).Should().BeEmpty();
Subject.GetSceneNames(100, new List<int> { 4 }, new List<int> { 4 }).Should().BeEmpty();
}
private void AssertNoUpdate()
{
_provider1.Verify(c => c.GetSceneMappings(), Times.Once());
Mocker.GetMock<ISceneMappingRepository>().Verify(c => c.Clear(It.IsAny<string>()), Times.Never());
Mocker.GetMock<ISceneMappingRepository>().Verify(c => c.InsertMany(_fakeMappings), Times.Never());
}
private void AssertMappingUpdated()
{
_provider1.Verify(c => c.GetSceneMappings(), Times.Once());
Mocker.GetMock<ISceneMappingRepository>().Verify(c => c.Clear(It.IsAny<string>()), Times.Once());
Mocker.GetMock<ISceneMappingRepository>().Verify(c => c.InsertMany(_fakeMappings), Times.Once());
foreach (var sceneMapping in _fakeMappings)
{
Subject.GetSceneNames(sceneMapping.TvdbId, _fakeMappings.Select(m => m.SeasonNumber.Value).Distinct().ToList(), new List<int>()).Should().Contain(sceneMapping.SearchTerm);
Subject.FindTvdbId(sceneMapping.ParseTerm).Should().Be(sceneMapping.TvdbId);
}
}
}
}

@ -1,102 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class delay_profileFixture : MigrationTest<delay_profile>
{
[Test]
public void should_migrate_old_delays()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
GrabDelay = 1,
Name = "OneHour",
Cutoff = 0,
Items = "[]"
});
c.Insert.IntoTable("Profiles").Row(new
{
GrabDelay = 2,
Name = "TwoHours",
Cutoff = "{}",
Items = "[]"
});
});
var allProfiles = db.Query<DelayProfile70>("SELECT * FROM DelayProfiles");
allProfiles.Should().HaveCount(3);
allProfiles.Should().OnlyContain(c => c.PreferredProtocol == 1);
allProfiles.Should().OnlyContain(c => c.TorrentDelay == 0);
allProfiles.Should().Contain(c => c.UsenetDelay == 60);
allProfiles.Should().Contain(c => c.UsenetDelay == 120);
}
[Test]
public void should_create_tag_for_delay_profile()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
GrabDelay = 1,
Name = "OneHour",
Cutoff = 0,
Items = "[]"
});
});
var tags = db.Query<Tag69>("SELECT * FROM Tags");
tags.Should().HaveCount(1);
tags.First().Label.Should().Be("delay-60");
}
[Test]
public void should_add_tag_to_series_that_had_a_profile_with_delay_attached()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
GrabDelay = 1,
Name = "OneHour",
Cutoff = 0,
Items = "[]"
});
c.Insert.IntoTable("Series").Row(new
{
TvdbId = 0,
TvRageId = 0,
Title = "Series",
TitleSlug = "series",
CleanTitle = "series",
Status = 0,
Images = "[]",
Path = @"C:\Test\Series",
Monitored = 1,
SeasonFolder = 1,
RunTime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
Tags = "[1]"
});
});
var tag = db.Query<Tag69>("SELECT Id, Label FROM Tags").Single();
var series = db.Query<Series69>("SELECT Tags FROM Series");
series.Should().HaveCount(1);
series.First().Tags.Should().BeEquivalentTo(tag.Id);
}
}
}

@ -1,35 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class unknown_quality_in_profileFixture : MigrationTest<unknown_quality_in_profile>
{
[Test]
public void should_add_unknown_to_old_profile()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Id = 0,
Name = "SDTV",
Cutoff = 1,
Items = "[ { \"quality\": 1, \"allowed\": true } ]",
Language = 1
});
});
var profiles = db.Query<Profile70>("SELECT Items FROM Profiles LIMIT 1");
var items = profiles.First().Items;
items.Should().HaveCount(2);
items.First().Quality.Should().Be(0);
items.First().Allowed.Should().Be(false);
}
}
}

@ -1,106 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using FluentMigrator;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class history_downloadIdFixture : MigrationTest<history_downloadId>
{
[Test]
public void should_move_grab_id_from_date_to_columns()
{
var db = WithMigrationTestDb(c =>
{
InsertHistory(c, new Dictionary<string, string>
{
{"indexer","test"},
{"downloadClientId","123"}
});
InsertHistory(c, new Dictionary<string, string>
{
{"indexer","test"},
{"downloadClientId","abc"}
});
});
var history = db.Query<History72>("SELECT DownloadId, Data FROM History");
history.Should().HaveCount(2);
history.Should().NotContain(c => c.Data.ContainsKey("downloadClientId"));
history.Should().Contain(c => c.DownloadId == "123");
history.Should().Contain(c => c.DownloadId == "abc");
}
[Test]
public void should_leave_items_with_no_grabid()
{
var db = WithMigrationTestDb(c =>
{
InsertHistory(c, new Dictionary<string, string>
{
{"indexer","test"},
{"downloadClientId","123"}
});
InsertHistory(c, new Dictionary<string, string>
{
{"indexer","test"}
});
});
var history = db.Query<History72>("SELECT DownloadId, Data FROM History");
history.Should().HaveCount(2);
history.Should().NotContain(c => c.Data.ContainsKey("downloadClientId"));
history.Should().Contain(c => c.DownloadId == "123");
history.Should().Contain(c => c.DownloadId == null);
}
[Test]
public void should_leave_other_data()
{
var db = WithMigrationTestDb(c =>
{
InsertHistory(c, new Dictionary<string, string>
{
{"indexer","test"},
{"group","test2"},
{"downloadClientId","123"}
});
});
var history = db.Query<History72>("SELECT DownloadId, Data FROM History").Single();
history.Data.Should().NotContainKey("downloadClientId");
history.Data.Should().Contain(new KeyValuePair<string, string>("indexer", "test"));
history.Data.Should().Contain(new KeyValuePair<string, string>("group", "test2"));
history.DownloadId.Should().Be("123");
}
private void InsertHistory(MigrationBase migrationBase, Dictionary<string, string> data)
{
migrationBase.Insert.IntoTable("History").Row(new
{
EpisodeId = 1,
SeriesId = 1,
SourceTitle = "Test",
Date = DateTime.Now,
Quality = "{}",
Data = data.ToJson(),
EventType = 1
});
}
}
}

@ -1,108 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Datastore.Migration;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class force_lib_updateFixture : MigrationTest<force_lib_update>
{
[Test]
public void should_not_fail_on_empty_db()
{
var db = WithMigrationTestDb();
db.Query("SELECT * FROM ScheduledTasks").Should().BeEmpty();
db.Query("SELECT * FROM Series").Should().BeEmpty();
}
[Test]
public void should_reset_job_last_execution_time()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("ScheduledTasks").Row(new
{
TypeName = "NzbDrone.Core.Tv.Commands.RefreshSeriesCommand",
Interval = 10,
LastExecution = "2000-01-01 00:00:00"
});
c.Insert.IntoTable("ScheduledTasks").Row(new
{
TypeName = "NzbDrone.Core.Backup.BackupCommand",
Interval = 10,
LastExecution = "2000-01-01 00:00:00"
});
});
var jobs = db.Query<ScheduledTasks75>("SELECT TypeName, LastExecution FROM ScheduledTasks");
jobs.Single(c => c.TypeName == "NzbDrone.Core.Tv.Commands.RefreshSeriesCommand")
.LastExecution.Year.Should()
.Be(2014);
jobs.Single(c => c.TypeName == "NzbDrone.Core.Backup.BackupCommand")
.LastExecution.Year.Should()
.Be(2000);
}
[Test]
public void should_reset_series_last_sync_time()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Name = "Profile1",
CutOff = 0,
Items = "[]",
Language = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 1,
TvRageId = 1,
Title = "Title1",
CleanTitle = "CleanTitle1",
Status = 1,
Images = "",
Path = "c:\\test",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
ProfileId = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 2,
TvRageId = 2,
Title = "Title2",
CleanTitle = "CleanTitle2",
Status = 1,
Images = "",
Path = "c:\\test2",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
ProfileId = 1
});
});
var series = db.Query<Series69>("SELECT LastInfoSync FROM Series");
series.Should().OnlyContain(c => c.LastInfoSync.Value.Year == 2014);
}
}
}

@ -1,244 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class dedupe_tagsFixture : MigrationTest<dedupe_tags>
{
[Test]
public void should_not_fail_if_series_tags_are_null()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Name = "Profile1",
CutOff = 0,
Items = "[]",
Language = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 1,
TvRageId = 1,
Title = "Title1",
CleanTitle = "CleanTitle1",
Status = 1,
Images = "",
Path = "c:\\test",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
ProfileId = 1
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
});
var tags = db.Query<Tag69>("SELECT * FROM Tags");
tags.Should().HaveCount(1);
}
[Test]
public void should_not_fail_if_series_tags_are_empty()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Name = "Profile1",
CutOff = 0,
Items = "[]",
Language = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 1,
TvRageId = 1,
Title = "Title1",
CleanTitle = "CleanTitle1",
Status = 1,
Images = "",
Path = "c:\\test",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
Tags = "[]",
ProfileId = 1
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
});
var tags = db.Query<Tag69>("SELECT * FROM Tags");
tags.Should().HaveCount(1);
}
[Test]
public void should_remove_duplicate_labels_from_tags()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
});
var tags = db.Query<Tag69>("SELECT * FROM Tags");
tags.Should().HaveCount(1);
}
[Test]
public void should_not_allow_duplicate_tag_to_be_inserted()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
});
Assert.That(() => db.Query("INSERT INTO Tags (Label) VALUES ('test')"), Throws.Exception);
}
[Test]
public void should_replace_duplicated_tag_with_proper_tag()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Name = "Profile1",
CutOff = 0,
Items = "[]",
Language = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 1,
TvRageId = 1,
Title = "Title1",
CleanTitle = "CleanTitle1",
Status = 1,
Images = "",
Path = "c:\\test",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
Tags = "[2]",
ProfileId = 1
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
});
var series = db.Query<Series69>("SELECT Tags FROM Series WHERE Id = 1").Single();
series.Tags.First().Should().Be(1);
}
[Test]
public void should_only_update_affected_series()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Name = "Profile1",
CutOff = 0,
Items = "[]",
Language = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 1,
TvRageId = 1,
Title = "Title1",
CleanTitle = "CleanTitle1",
Status = 1,
Images = "",
Path = "c:\\test",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
Tags = "[2]",
ProfileId = 1
});
c.Insert.IntoTable("Series").Row(new
{
Tvdbid = 2,
TvRageId = 2,
Title = "Title2",
CleanTitle = "CleanTitle2",
Status = 1,
Images = "",
Path = "c:\\test",
Monitored = 1,
SeasonFolder = 1,
Runtime = 0,
SeriesType = 0,
UseSceneNumbering = 0,
LastInfoSync = "2000-01-01 00:00:00",
Tags = "[]",
ProfileId = 1
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
c.Insert.IntoTable("Tags").Row(new
{
Label = "test"
});
});
var series = db.Query<Series69>("SELECT Tags FROM Series WHERE Id = 2").Single();
series.Tags.Should().BeEmpty();
}
}
}

@ -1,88 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Datastore.Migration;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class move_dot_prefix_to_transmission_categoryFixture : MigrationTest<move_dot_prefix_to_transmission_category>
{
[Test]
public void should_not_fail_if_no_transmission()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("DownloadClients").Row(new
{
Enable = 1,
Name = "Sab",
Implementation = "Sabnzbd",
Settings = new
{
Host = "127.0.0.1",
TvCategory = "abc"
}.ToJson(),
ConfigContract = "SabnzbdSettings"
});
});
var downloadClients = db.Query<DownloadClientDefinition81>("SELECT Settings FROM DownloadClients");
downloadClients.Should().HaveCount(1);
downloadClients.First().Settings.ToObject<SabnzbdSettings81>().TvCategory.Should().Be("abc");
}
[Test]
public void should_be_updated_for_transmission()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("DownloadClients").Row(new
{
Enable = 1,
Name = "Trans",
Implementation = "Transmission",
Settings = new
{
Host = "127.0.0.1",
TvCategory = "abc"
}.ToJson(),
ConfigContract = "TransmissionSettings"
});
});
var downloadClients = db.Query<DownloadClientDefinition81>("SELECT Settings FROM DownloadClients");
downloadClients.Should().HaveCount(1);
downloadClients.First().Settings.ToObject<TransmissionSettings81>().TvCategory.Should().Be(".abc");
}
[Test]
public void should_leave_empty_category_untouched()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("DownloadClients").Row(new
{
Enable = 1,
Name = "Trans",
Implementation = "Transmission",
Settings = new
{
Host = "127.0.0.1",
TvCategory = ""
}.ToJson(),
ConfigContract = "TransmissionSettings"
});
});
var downloadClients = db.Query<DownloadClientDefinition81>("SELECT Settings FROM DownloadClients");
downloadClients.Should().HaveCount(1);
downloadClients.First().Settings.ToObject<TransmissionSettings81>().TvCategory.Should().Be("");
}
}
}

@ -1,96 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class update_quality_minmax_sizeFixture : MigrationTest<update_quality_minmax_size>
{
[Test]
public void should_not_fail_if_empty()
{
var db = WithMigrationTestDb();
var qualityDefinitions = db.Query<QualityDefinition84>("SELECT * FROM QualityDefinitions");
qualityDefinitions.Should().BeEmpty();
}
[Test]
public void should_set_rawhd_to_null()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("QualityDefinitions").Row(new
{
Quality = 1,
Title = "SDTV",
MinSize = 0,
MaxSize = 100
})
.Row(new
{
Quality = 10,
Title = "RawHD",
MinSize = 0,
MaxSize = 100
});
});
var qualityDefinitions = db.Query<QualityDefinition84>("SELECT * FROM QualityDefinitions");
qualityDefinitions.Should().HaveCount(2);
qualityDefinitions.First(v => v.Quality == 10).MaxSize.Should().NotHaveValue();
}
[Test]
public void should_set_zero_maxsize_to_null()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("QualityDefinitions").Row(new
{
Quality = 1,
Title = "SDTV",
MinSize = 0,
MaxSize = 0
});
});
var qualityDefinitions = db.Query<QualityDefinition84>("SELECT * FROM QualityDefinitions");
qualityDefinitions.Should().HaveCount(1);
qualityDefinitions.First(v => v.Quality == 1).MaxSize.Should().NotHaveValue();
}
[Test]
public void should_preserve_values()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("QualityDefinitions").Row(new
{
Quality = 1,
Title = "SDTV",
MinSize = 0,
MaxSize = 100
})
.Row(new
{
Quality = 10,
Title = "RawHD",
MinSize = 0,
MaxSize = 100
});
});
var qualityDefinitions = db.Query<QualityDefinition84>("SELECT * FROM QualityDefinitions");
qualityDefinitions.Should().HaveCount(2);
qualityDefinitions.First(v => v.Quality == 1).MaxSize.Should().Be(100);
}
}
}

@ -1,90 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class expand_transmission_urlbaseFixture : MigrationTest<expand_transmission_urlbase>
{
[Test]
public void should_not_fail_if_no_transmission()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("DownloadClients").Row(new
{
Enable = 1,
Name = "Deluge",
Implementation = "Deluge",
Settings = new DelugeSettings85
{
Host = "127.0.0.1",
TvCategory = "abc",
UrlBase = "/my/"
}.ToJson(),
ConfigContract = "DelugeSettings"
});
});
var items = db.Query<DownloadClientDefinition81>("SELECT * FROM DownloadClients");
items.Should().HaveCount(1);
items.First().Settings.ToObject<DelugeSettings85>().UrlBase.Should().Be("/my/");
}
[Test]
public void should_be_updated_for_transmission()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("DownloadClients").Row(new
{
Enable = 1,
Name = "Trans",
Implementation = "Transmission",
Settings = new TransmissionSettings81
{
Host = "127.0.0.1",
TvCategory = "abc"
}.ToJson(),
ConfigContract = "TransmissionSettings"
});
});
var items = db.Query<DownloadClientDefinition81>("SELECT * FROM DownloadClients");
items.Should().HaveCount(1);
items.First().Settings.ToObject<TransmissionSettings81>().UrlBase.Should().Be("/transmission/");
}
[Test]
public void should_be_append_to_existing_urlbase()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("DownloadClients").Row(new
{
Enable = 1,
Name = "Trans",
Implementation = "Transmission",
Settings = new TransmissionSettings81
{
Host = "127.0.0.1",
TvCategory = "abc",
UrlBase = "/my/url/"
}.ToJson(),
ConfigContract = "TransmissionSettings"
});
});
var items = db.Query<DownloadClientDefinition81>("SELECT * FROM DownloadClients");
items.Should().HaveCount(1);
items.First().Settings.ToObject<TransmissionSettings81>().UrlBase.Should().Be("/my/url/transmission/");
}
}
}

@ -1,89 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class pushbullet_device_idsFixture : MigrationTest<pushbullet_device_ids>
{
[Test]
public void should_not_fail_if_no_pushbullet()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Notifications").Row(new
{
OnGrab = false,
OnDownload = false,
OnUpgrade = false,
Name = "Pushover",
Implementation = "Pushover",
Settings = "{}",
ConfigContract = "PushoverSettings"
});
});
var items = db.Query<Notification86>("SELECT * FROM Notifications");
items.Should().HaveCount(1);
}
[Test]
public void should_not_fail_if_deviceId_is_not_set()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Notifications").Row(new
{
OnGrab = false,
OnDownload = false,
OnUpgrade = false,
Name = "PushBullet",
Implementation = "PushBullet",
Settings = new
{
ApiKey = "my_api_key"
}.ToJson(),
ConfigContract = "PushBulletSettings"
});
});
var items = db.Query<Notification86>("SELECT * FROM Notifications");
items.Should().HaveCount(1);
}
[Test]
public void should_add_deviceIds_setting_matching_deviceId()
{
var deviceId = "device_id";
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Notifications").Row(new
{
OnGrab = false,
OnDownload = false,
OnUpgrade = false,
Name = "PushBullet",
Implementation = "PushBullet",
Settings = new
{
ApiKey = "my_api_key",
DeviceId = deviceId
}.ToJson(),
ConfigContract = "PushBulletSettings"
});
});
var items = db.Query<Notification86>("SELECT * FROM Notifications");
items.Should().HaveCount(1);
items.First().Settings.ToObject<PushBulletSettings86>().DeviceIds.First().Should().Be(deviceId);
}
}
}

@ -1,40 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class pushbullet_devices_channels_listFixture : MigrationTest<pushbullet_devices_channels_list>
{
[Test]
public void should_convert_comma_separted_string_to_list()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Notifications").Row(new
{
OnGrab = false,
OnDownload = false,
OnUpgrade = false,
Name = "PushBullet",
Implementation = "PushBullet",
Settings = new
{
ApiKey = "my_api_key",
ChannelTags = "channel1,channel2"
}.ToJson(),
ConfigContract = "PushBulletSettings"
});
});
var items = db.Query<Notification86>("SELECT * FROM Notifications");
items.Should().HaveCount(1);
items.First().Settings.ToObject<PushBulletSettings88>().ChannelTags.Should().HaveCount(2);
}
}
}

@ -1,64 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class update_kickass_url_migration_fixture : MigrationTest<update_kickass_url>
{
[TestCase("http://kickass.so")]
[TestCase("https://kickass.so")]
[TestCase("http://kickass.to")]
[TestCase("https://kickass.to")]
[TestCase("http://kat.cr")]
// [TestCase("HTTP://KICKASS.SO")] Not sure if there is an easy way to do this, not sure if worth it.
public void should_replace_old_url(string oldUrl)
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Indexers").Row(new
{
Name = "Kickass_wrong_url",
Implementation = "KickassTorrents",
Settings = new KickassTorrentsSettings90
{
BaseUrl = oldUrl
}.ToJson(),
ConfigContract = "KickassTorrentsSettings"
});
});
var items = db.Query<IndexerDefinition90>("SELECT * FROM Indexers");
items.Should().HaveCount(1);
items.First().Settings.ToObject<KickassTorrentsSettings90>().BaseUrl.Should().Be("https://kat.cr");
}
[Test]
public void should_not_replace_other_indexers()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Indexers").Row(new
{
Name = "not_kickass",
Implementation = "NotKickassTorrents",
Settings = new KickassTorrentsSettings90
{
BaseUrl = "kickass.so",
}.ToJson(),
ConfigContract = "KickassTorrentsSettings"
});
});
var items = db.Query<IndexerDefinition90>("SELECT * FROM Indexers");
items.Should().HaveCount(1);
items.First().Settings.ToObject<KickassTorrentsSettings90>().BaseUrl.Should().Be("kickass.so");
}
}
}

@ -1,54 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class metadata_files_extensionFixture : MigrationTest<extra_and_subtitle_files>
{
[Test]
public void should_set_extension_using_relative_path()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("MetadataFiles").Row(new
{
SeriesId = 1,
RelativePath = "banner.jpg",
LastUpdated = "2016-05-30 20:23:02.3725923",
Type = 3,
Consumer = "XbmcMetadata"
});
c.Insert.IntoTable("MetadataFiles").Row(new
{
SeriesId = 1,
SeasonNumber = 1,
EpisodeFileId = 1,
RelativePath = "Series.Title.S01E01.jpg",
LastUpdated = "2016-05-30 20:23:02.3725923",
Type = 5,
Consumer = "XbmcMetadata"
});
c.Insert.IntoTable("MetadataFiles").Row(new
{
SeriesId = 1,
RelativePath = "Series Title",
LastUpdated = "2016-05-30 20:23:02.3725923",
Type = 3,
Consumer = "RoksboxMetadata"
});
});
var items = db.Query<MetadataFile99>("SELECT * FROM MetadataFiles");
items.Should().HaveCount(2);
items.First().Extension.Should().Be(".jpg");
items.Last().Extension.Should().Be(".jpg");
}
}
}

@ -1,35 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class add_ultrahd_quality_in_profilesFixture : MigrationTest<add_ultrahd_quality_in_profiles>
{
[Test]
public void should_add_ultrahd_to_old_profile()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Profiles").Row(new
{
Id = 0,
Name = "SDTV",
Cutoff = 1,
Items = "[ { \"quality\": 1, \"allowed\": true } ]",
Language = 1
});
});
var profiles = db.Query<Profile70>("SELECT Items FROM Profiles LIMIT 1");
var items = profiles.First().Items;
items.Should().HaveCount(4);
items.Select(v => v.Quality).Should().BeEquivalentTo(1, 16, 18, 19);
items.Select(v => v.Allowed).Should().BeEquivalentTo(true, false, false, false);
}
}
}

@ -1,36 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class fix_metadata_file_extensionsFixture : MigrationTest<fix_metadata_file_extensions>
{
[Test]
public void should_fix_extension_when_relative_path_contained_multiple_periods()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("MetadataFiles").Row(new
{
SeriesId = 1,
SeasonNumber = 1,
EpisodeFileId = 1,
RelativePath = "Series.Title.S01E01.jpg",
LastUpdated = "2016-05-30 20:23:02.3725923",
Type = 5,
Consumer = "XbmcMetadata",
Extension = ".S01E01.jpg"
});
});
var items = db.Query<MetadataFile99>("SELECT * FROM MetadataFiles");
items.Should().HaveCount(1);
items.First().Extension.Should().Be(".jpg");
}
}
}

@ -1,62 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class update_btn_url_migration_fixture : MigrationTest<update_btn_url>
{
[TestCase("http://api.btnapps.net")]
[TestCase("https://api.btnapps.net")]
[TestCase("http://api.btnapps.net/")]
[TestCase("https://api.btnapps.net/")]
public void should_replace_old_url(string oldUrl)
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Indexers").Row(new
{
Name = "btn_old_url",
Implementation = "BroadcastheNet",
Settings = new BroadcastheNetSettings106
{
BaseUrl = oldUrl
}.ToJson(),
ConfigContract = "BroadcastheNetSettings"
});
});
var items = db.Query<IndexerDefinition90>("SELECT * FROM Indexers");
items.Should().HaveCount(1);
items.First().Settings.ToObject<BroadcastheNetSettings106>().BaseUrl.Should().Contain("api.broadcasthe.net");
}
[Test]
public void should_not_replace_other_indexers()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Indexers").Row(new
{
Name = "not_btn",
Implementation = "NotBroadcastheNet",
Settings = new BroadcastheNetSettings106
{
BaseUrl = "http://api.btnapps.net",
}.ToJson(),
ConfigContract = "BroadcastheNetSettings"
});
});
var items = db.Query<IndexerDefinition90>("SELECT * FROM Indexers");
items.Should().HaveCount(1);
items.First().Settings.ToObject<BroadcastheNetSettings106>().BaseUrl.Should().Be("http://api.btnapps.net");
}
}
}

@ -1,84 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Parser;
using NzbDrone.Core.Languages;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class fix_extra_file_extensionsFixture : MigrationTest<fix_extra_file_extension>
{
[Test]
public void should_extra_files_that_do_not_have_an_extension()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("ExtraFiles").Row(new
{
SeriesId = 1,
SeasonNumber = 1,
EpisodeFileId = 1,
RelativePath = "Series.Title.S01E01",
Added = "2016-05-30 20:23:02.3725923",
LastUpdated = "2016-05-30 20:23:02.3725923",
Extension = ""
});
});
var items = db.Query("Select * from ExtraFiles");
items.Should().BeEmpty();
}
[Test]
public void should_fix_double_extension()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("SubtitleFiles").Row(new
{
SeriesId = 1,
SeasonNumber = 1,
EpisodeFileId = 1,
RelativePath = "Series.Title.S01E01.en.srt",
Added = "2016-05-30 20:23:02.3725923",
LastUpdated = "2016-05-30 20:23:02.3725923",
Language = Core.Languages.Language.English,
Extension = "en.srt"
});
});
var items = db.Query("Select * from SubtitleFiles");
items.Should().HaveCount(1);
items.First()["Extension"].Should().Be(".srt");
}
[Test]
public void should_fix_extension_missing_a_leading_period()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("ExtraFiles").Row(new
{
SeriesId = 1,
SeasonNumber = 1,
EpisodeFileId = 1,
RelativePath = "Series.Title.S01E01.nfo-orig",
Added = "2016-05-30 20:23:02.3725923",
LastUpdated = "2016-05-30 20:23:02.3725923",
Extension = "nfo-orig"
});
});
var items = db.Query("Select * from ExtraFiles");
items.Should().HaveCount(1);
items.First()["Extension"].Should().Be(".nfo-orig");
}
}
}

@ -1,54 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Parser;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class import_extra_files_configFixture : MigrationTest<import_extra_files>
{
[Test]
public void should_not_insert_if_missing()
{
var db = WithMigrationTestDb();
var items = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
items.Should().BeNull();
}
[Test]
public void should_not_insert_if_empty()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "extrafileextensions",
Value = ""
});
});
var items = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
items.Should().BeNull();
}
[Test]
public void should_insert_True_if_configured()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "extrafileextensions",
Value = "srt"
});
});
var items = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
items.Should().Be("True");
}
}
}

@ -1,133 +0,0 @@
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.Datastore.Migration;
using NzbDrone.Core.Parser;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.Datastore.Migration
{
[TestFixture]
public class fix_extra_files_configFixture : MigrationTest<fix_extra_files_config>
{
[Test]
public void should_not_update_importextrafiles_disabled()
{
var db = WithMigrationTestDb();
var itemEnabled = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
itemEnabled.Should().BeNull();
}
[Test]
public void should_fix_importextrafiles_if_wrong()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "importextrafiles",
Value = 1
});
});
var itemEnabled = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
itemEnabled.Should().Be("True");
}
[Test]
public void should_fill_in_default_extensions()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "importextrafiles",
Value = "False"
});
c.Insert.IntoTable("Config").Row(new
{
Key = "extrafileextensions",
Value = ""
});
});
var itemEnabled = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
itemEnabled.Should().Be("False");
var itemExtensions = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'extrafileextensions'");
itemExtensions.Should().Be("srt");
}
[Test]
public void should_not_fill_in_default_extensions()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "importextrafiles",
Value = "True"
});
c.Insert.IntoTable("Config").Row(new
{
Key = "extrafileextensions",
Value = ""
});
});
var itemEnabled = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
itemEnabled.Should().Be("True");
var itemExtensions = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'extrafileextensions'");
itemExtensions.Should().Be("");
}
[Test]
public void should_not_fill_in_default_extensions_if_not_defined()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "importextrafiles",
Value = "False"
});
});
var itemEnabled = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
itemEnabled.Should().Be("False");
var itemExtensions = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'extrafileextensions'");
itemExtensions.Should().BeNull();
}
[Test]
public void should_not_fill_in_default_extensions_if_already_defined()
{
var db = WithMigrationTestDb(c =>
{
c.Insert.IntoTable("Config").Row(new
{
Key = "importextrafiles",
Value = "False"
});
c.Insert.IntoTable("Config").Row(new
{
Key = "extrafileextensions",
Value = "sub"
});
});
var itemEnabled = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'importextrafiles'");
itemEnabled.Should().Be("False");
var itemExtensions = db.QueryScalar<string>("SELECT Value FROM Config WHERE Key = 'extrafileextensions'");
itemExtensions.Should().Be("sub");
}
}
}

@ -44,7 +44,7 @@ namespace NzbDrone.Core.Test.Download.Pending.PendingReleaseServiceTests
{
Mocker.GetMock<IIndexerStatusService>()
.Setup(v => v.GetBlockedIndexers())
.Returns(new List<IndexerStatus> { new IndexerStatus { IndexerId = 1, DisabledTill = DateTime.UtcNow.AddHours(2) } });
.Returns(new List<IndexerStatus> { new IndexerStatus { ProviderId = 1, DisabledTill = DateTime.UtcNow.AddHours(2) } });
GivenPendingRelease();

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
@ -40,7 +40,7 @@ namespace NzbDrone.Core.Test.HealthCheck.Checks
{
_blockedIndexers.Add(new IndexerStatus
{
IndexerId = id,
ProviderId = id,
InitialFailure = DateTime.UtcNow.AddHours(-failureHours),
MostRecentFailure = DateTime.UtcNow.AddHours(-0.1),
EscalationLevel = 5,

@ -28,7 +28,7 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers
public void should_delete_orphaned_indexerstatus()
{
var status = Builder<IndexerStatus>.CreateNew()
.With(h => h.IndexerId = _indexer.Id)
.With(h => h.ProviderId = _indexer.Id)
.BuildNew();
Db.Insert(status);
@ -42,13 +42,13 @@ namespace NzbDrone.Core.Test.Housekeeping.Housekeepers
GivenIndexer();
var status = Builder<IndexerStatus>.CreateNew()
.With(h => h.IndexerId = _indexer.Id)
.With(h => h.ProviderId = _indexer.Id)
.BuildNew();
Db.Insert(status);
Subject.Clean();
AllStoredModels.Should().HaveCount(1);
AllStoredModels.Should().Contain(h => h.IndexerId == _indexer.Id);
AllStoredModels.Should().Contain(h => h.ProviderId == _indexer.Id);
}
}
}

@ -104,8 +104,6 @@
<Compile Include="BulkImport\BulkImportFixture.cs" />
<Compile Include="Configuration\ConfigCachingFixture.cs" />
<Compile Include="Configuration\ConfigServiceFixture.cs" />
<Compile Include="DataAugmentation\Scene\SceneMappingProxyFixture.cs" />
<Compile Include="DataAugmentation\Scene\SceneMappingServiceFixture.cs" />
<Compile Include="DataAugmentation\DailySeries\DailySeriesDataProxyFixture.cs" />
<Compile Include="Datastore\BasicRepositoryFixture.cs" />
<Compile Include="Datastore\Converters\ProviderSettingConverterFixture.cs" />
@ -113,24 +111,6 @@
<Compile Include="Datastore\DatabaseRelationshipFixture.cs" />
<Compile Include="Datastore\MappingExtentionFixture.cs" />
<Compile Include="Datastore\MarrDataLazyLoadingFixture.cs" />
<Compile Include="Datastore\Migration\108_fix_metadata_file_extensionsFixture.cs" />
<Compile Include="Datastore\Migration\109_import_extra_files_configFixture.cs" />
<Compile Include="Datastore\Migration\110_fix_extra_files_configFixture.cs" />
<Compile Include="Datastore\Migration\106_update_btn_urlFixture.cs" />
<Compile Include="Datastore\Migration\103_fix_metadata_file_extensionsFixture.cs" />
<Compile Include="Datastore\Migration\099_extra_and_subtitle_filesFixture.cs" />
<Compile Include="Datastore\Migration\101_add_ultrahd_quality_in_profilesFixture.cs" />
<Compile Include="Datastore\Migration\071_unknown_quality_in_profileFixture.cs" />
<Compile Include="Datastore\Migration\072_history_downloadIdFixture.cs" />
<Compile Include="Datastore\Migration\070_delay_profileFixture.cs" />
<Compile Include="Datastore\Migration\088_pushbullet_devices_channels_listFixture.cs" />
<Compile Include="Datastore\Migration\086_pushbullet_device_idsFixture.cs" />
<Compile Include="Datastore\Migration\085_expand_transmission_urlbaseFixture.cs" />
<Compile Include="Datastore\Migration\084_update_quality_minmax_sizeFixture.cs" />
<Compile Include="Datastore\Migration\081_move_dot_prefix_to_transmission_categoryFixture.cs" />
<Compile Include="Datastore\Migration\079_dedupe_tagsFixture.cs" />
<Compile Include="Datastore\Migration\075_force_lib_updateFixture.cs" />
<Compile Include="Datastore\Migration\090_update_kickass_urlFixture.cs" />
<Compile Include="Datastore\ObjectDatabaseFixture.cs" />
<Compile Include="Datastore\PagingSpecExtensionsTests\PagingOffsetFixture.cs" />
<Compile Include="Datastore\PagingSpecExtensionsTests\ToSortDirectionFixture.cs" />
@ -537,6 +517,7 @@
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="Datastore\Migration\" />
<Folder Include="InstrumentationTests\" />
<Folder Include="Providers\" />
<Folder Include="ProviderTests\UpdateProviderTests\" />

@ -1,9 +0,0 @@
using System.Collections.Generic;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public interface ISceneMappingProvider
{
List<SceneMapping> GetSceneMappings();
}
}

@ -1,22 +0,0 @@
using Newtonsoft.Json;
using NzbDrone.Core.Datastore;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public class SceneMapping : ModelBase
{
public string Title { get; set; }
public string ParseTerm { get; set; }
[JsonProperty("searchTitle")]
public string SearchTerm { get; set; }
public int TvdbId { get; set; }
[JsonProperty("season")]
public int? SeasonNumber { get; set; }
public int? SceneSeasonNumber { get; set; }
public string Type { get; set; }
}
}

@ -1,32 +0,0 @@
using System.Collections.Generic;
using NzbDrone.Common.Cloud;
using NzbDrone.Common.Http;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public interface ISceneMappingProxy
{
List<SceneMapping> Fetch();
}
public class SceneMappingProxy : ISceneMappingProxy
{
private readonly IHttpClient _httpClient;
private readonly IHttpRequestBuilderFactory _requestBuilder;
public SceneMappingProxy(IHttpClient httpClient, ILidarrCloudRequestBuilder requestBuilder)
{
_httpClient = httpClient;
_requestBuilder = requestBuilder.Services;
}
public List<SceneMapping> Fetch()
{
var request = _requestBuilder.Create()
.Resource("/scenemapping")
.Build();
return _httpClient.Get<List<SceneMapping>>(request).Resource;
}
}
}

@ -1,31 +0,0 @@
using NzbDrone.Core.Datastore;
using NzbDrone.Core.Messaging.Events;
using System.Collections.Generic;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public interface ISceneMappingRepository : IBasicRepository<SceneMapping>
{
List<SceneMapping> FindByTvdbid(int tvdbId);
void Clear(string type);
}
public class SceneMappingRepository : BasicRepository<SceneMapping>, ISceneMappingRepository
{
public SceneMappingRepository(IMainDatabase database, IEventAggregator eventAggregator)
: base(database, eventAggregator)
{
}
public List<SceneMapping> FindByTvdbid(int tvdbId)
{
return Query.Where(x => x.TvdbId == tvdbId);
}
public void Clear(string type)
{
Delete(s => s.Type == type);
}
}
}

@ -1,252 +0,0 @@
using System;
using System.Linq;
using NLog;
using NzbDrone.Common.Cache;
using NzbDrone.Common.Extensions;
using NzbDrone.Core.Messaging.Commands;
using NzbDrone.Core.Messaging.Events;
using NzbDrone.Core.Parser;
using System.Collections.Generic;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public interface ISceneMappingService
{
List<string> GetSceneNames(int tvdbId, List<int> seasonNumbers, List<int> sceneSeasonNumbers);
int? FindTvdbId(string title);
List<SceneMapping> FindByTvdbId(int tvdbId);
SceneMapping FindSceneMapping(string title);
int? GetSceneSeasonNumber(string title);
int? GetTvdbSeasonNumber(string title);
int? GetSceneSeasonNumber(int tvdbId, int seasonNumber);
}
public class SceneMappingService : ISceneMappingService,
// IHandle<SeriesRefreshStartingEvent>,
IExecute<UpdateSceneMappingCommand>
{
private readonly ISceneMappingRepository _repository;
private readonly IEnumerable<ISceneMappingProvider> _sceneMappingProviders;
private readonly IEventAggregator _eventAggregator;
private readonly Logger _logger;
private readonly ICachedDictionary<List<SceneMapping>> _getTvdbIdCache;
private readonly ICachedDictionary<List<SceneMapping>> _findByTvdbIdCache;
public SceneMappingService(ISceneMappingRepository repository,
ICacheManager cacheManager,
IEnumerable<ISceneMappingProvider> sceneMappingProviders,
IEventAggregator eventAggregator,
Logger logger)
{
_repository = repository;
_sceneMappingProviders = sceneMappingProviders;
_eventAggregator = eventAggregator;
_logger = logger;
_getTvdbIdCache = cacheManager.GetCacheDictionary<List<SceneMapping>>(GetType(), "tvdb_id");
_findByTvdbIdCache = cacheManager.GetCacheDictionary<List<SceneMapping>>(GetType(), "find_tvdb_id");
}
public List<string> GetSceneNames(int tvdbId, List<int> seasonNumbers, List<int> sceneSeasonNumbers)
{
var mappings = FindByTvdbId(tvdbId);
if (mappings == null)
{
return new List<string>();
}
var names = mappings.Where(n => n.SeasonNumber.HasValue && seasonNumbers.Contains(n.SeasonNumber.Value) ||
n.SceneSeasonNumber.HasValue && sceneSeasonNumbers.Contains(n.SceneSeasonNumber.Value) ||
(n.SeasonNumber ?? -1) == -1 && (n.SceneSeasonNumber ?? -1) == -1)
.Select(n => n.SearchTerm).Distinct().ToList();
return FilterNonEnglish(names);
}
public int? FindTvdbId(string title)
{
var mapping = FindMapping(title);
if (mapping == null)
return null;
return mapping.TvdbId;
}
public List<SceneMapping> FindByTvdbId(int tvdbId)
{
if (_findByTvdbIdCache.Count == 0)
{
RefreshCache();
}
var mappings = _findByTvdbIdCache.Find(tvdbId.ToString());
if (mappings == null)
{
return new List<SceneMapping>();
}
return mappings;
}
public SceneMapping FindSceneMapping(string title)
{
return FindMapping(title);
}
public int? GetSceneSeasonNumber(string title)
{
var mapping = FindMapping(title);
if (mapping == null)
{
return null;
}
return mapping.SceneSeasonNumber;
}
public int? GetTvdbSeasonNumber(string title)
{
var mapping = FindMapping(title);
if (mapping == null)
{
return null;
}
return mapping.SeasonNumber;
}
public int? GetSceneSeasonNumber(int tvdbId, int seasonNumber)
{
var mappings = FindByTvdbId(tvdbId);
if (mappings == null)
{
return null;
}
var mapping = mappings.FirstOrDefault(e => e.SeasonNumber == seasonNumber && e.SceneSeasonNumber.HasValue);
if (mapping == null)
{
return null;
}
return mapping.SceneSeasonNumber;
}
private void UpdateMappings()
{
_logger.Info("Updating Scene mappings");
foreach (var sceneMappingProvider in _sceneMappingProviders)
{
try
{
var mappings = sceneMappingProvider.GetSceneMappings();
if (mappings.Any())
{
_repository.Clear(sceneMappingProvider.GetType().Name);
mappings.RemoveAll(sceneMapping =>
{
if (sceneMapping.Title.IsNullOrWhiteSpace() ||
sceneMapping.SearchTerm.IsNullOrWhiteSpace())
{
_logger.Warn("Invalid scene mapping found for: {0}, skipping", sceneMapping.TvdbId);
return true;
}
return false;
});
foreach (var sceneMapping in mappings)
{
sceneMapping.ParseTerm = sceneMapping.Title.CleanSeriesTitle();
sceneMapping.Type = sceneMappingProvider.GetType().Name;
}
_repository.InsertMany(mappings.ToList());
}
else
{
_logger.Warn("Received empty list of mapping. will not update.");
}
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to Update Scene Mappings.");
}
}
RefreshCache();
_eventAggregator.PublishEvent(new SceneMappingsUpdatedEvent());
}
private SceneMapping FindMapping(string title)
{
if (_getTvdbIdCache.Count == 0)
{
RefreshCache();
}
var candidates = _getTvdbIdCache.Find(title.CleanSeriesTitle());
if (candidates == null)
{
return null;
}
if (candidates.Count == 1)
{
return candidates.First();
}
var exactMatch = candidates.OrderByDescending(v => v.SeasonNumber)
.FirstOrDefault(v => v.Title == title);
if (exactMatch != null)
{
return exactMatch;
}
var closestMatch = candidates.OrderBy(v => title.LevenshteinDistance(v.Title, 10, 1, 10))
.ThenByDescending(v => v.SeasonNumber)
.First();
return closestMatch;
}
private void RefreshCache()
{
var mappings = _repository.All().ToList();
_getTvdbIdCache.Update(mappings.GroupBy(v => v.ParseTerm).ToDictionary(v => v.Key, v => v.ToList()));
_findByTvdbIdCache.Update(mappings.GroupBy(v => v.TvdbId).ToDictionary(v => v.Key.ToString(), v => v.ToList()));
}
private List<string> FilterNonEnglish(List<string> titles)
{
return titles.Where(title => title.All(c => c <= 255)).ToList();
}
//public void Handle(SeriesRefreshStartingEvent message)
//{
// if (message.ManualTrigger && _findByTvdbIdCache.IsExpired(TimeSpan.FromMinutes(1)))
// {
// UpdateMappings();
// }
//}
public void Execute(UpdateSceneMappingCommand message)
{
UpdateMappings();
}
}
}

@ -1,8 +0,0 @@
using NzbDrone.Common.Messaging;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public class SceneMappingsUpdatedEvent : IEvent
{
}
}

@ -1,19 +0,0 @@
using System.Collections.Generic;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public class ServicesProvider : ISceneMappingProvider
{
private readonly ISceneMappingProxy _sceneMappingProxy;
public ServicesProvider(ISceneMappingProxy sceneMappingProxy)
{
_sceneMappingProxy = sceneMappingProxy;
}
public List<SceneMapping> GetSceneMappings()
{
return _sceneMappingProxy.Fetch();
}
}
}

@ -1,9 +0,0 @@
using NzbDrone.Core.Messaging.Commands;
namespace NzbDrone.Core.DataAugmentation.Scene
{
public class UpdateSceneMappingCommand : Command
{
}
}

@ -1,4 +1,4 @@
using FluentMigrator;
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
@ -15,127 +15,297 @@ namespace NzbDrone.Core.Datastore.Migration
Create.TableForModel("RootFolders")
.WithColumn("Path").AsString().Unique();
Create.TableForModel("Series")
.WithColumn("TvdbId").AsInt32().Unique()
.WithColumn("TvRageId").AsInt32().Unique()
.WithColumn("ImdbId").AsString().Unique()
.WithColumn("Title").AsString()
.WithColumn("TitleSlug").AsString().Unique()
.WithColumn("CleanTitle").AsString()
Create.TableForModel("Artists")
.WithColumn("ForeignArtistId").AsString().Unique()
.WithColumn("MBId").AsString().Nullable()
.WithColumn("AMId").AsString().Nullable()
.WithColumn("TADBId").AsInt32().Nullable()
.WithColumn("DiscogsId").AsInt32().Nullable()
.WithColumn("Name").AsString()
.WithColumn("NameSlug").AsString().Nullable().Unique()
.WithColumn("CleanName").AsString().Indexed()
.WithColumn("Status").AsInt32()
.WithColumn("Overview").AsString().Nullable()
.WithColumn("AirTime").AsString().Nullable()
.WithColumn("Images").AsString()
.WithColumn("Path").AsString()
.WithColumn("Path").AsString().Indexed()
.WithColumn("Monitored").AsBoolean()
.WithColumn("QualityProfileId").AsInt32()
.WithColumn("SeasonFolder").AsBoolean()
.WithColumn("AlbumFolder").AsBoolean()
.WithColumn("LastInfoSync").AsDateTime().Nullable()
.WithColumn("LastDiskSync").AsDateTime().Nullable()
.WithColumn("Runtime").AsInt32()
.WithColumn("SeriesType").AsInt32()
.WithColumn("BacklogSetting").AsInt32()
.WithColumn("Network").AsString().Nullable()
.WithColumn("CustomStartDate").AsDateTime().Nullable()
.WithColumn("UseSceneNumbering").AsBoolean()
.WithColumn("FirstAired").AsDateTime().Nullable()
.WithColumn("NextAiring").AsDateTime().Nullable();
Create.TableForModel("Seasons")
.WithColumn("SeriesId").AsInt32()
.WithColumn("SeasonNumber").AsInt32()
.WithColumn("Ignored").AsBoolean();
Create.TableForModel("Episodes")
.WithColumn("TvDbEpisodeId").AsInt32().Unique()
.WithColumn("SeriesId").AsInt32()
.WithColumn("SeasonNumber").AsInt32()
.WithColumn("EpisodeNumber").AsInt32()
.WithColumn("Title").AsString().Nullable()
.WithColumn("DateFormed").AsDateTime().Nullable()
.WithColumn("Members").AsString().Nullable()
.WithColumn("Ratings").AsString().Nullable()
.WithColumn("Genres").AsString().Nullable()
.WithColumn("SortName").AsString().Nullable()
.WithColumn("ProfileId").AsInt32().Nullable()
.WithColumn("Tags").AsString().Nullable()
.WithColumn("Added").AsDateTime().Nullable()
.WithColumn("AddOptions").AsString().Nullable()
.WithColumn("LanguageProfileId").AsInt32().WithDefaultValue(1)
.WithColumn("Links").AsString().Nullable()
.WithColumn("ArtistType").AsString().Nullable()
.WithColumn("Disambiguation").AsString().Nullable()
.WithColumn("PrimaryAlbumTypes").AsString().Nullable()
.WithColumn("SecondaryAlbumTypes").AsString().Nullable();
Create.TableForModel("Albums")
.WithColumn("ForeignAlbumId").AsString().Unique()
.WithColumn("ArtistId").AsInt32()
.WithColumn("MBId").AsString().Nullable().Indexed()
.WithColumn("AMId").AsString().Nullable()
.WithColumn("TADBId").AsInt32().Nullable().Indexed()
.WithColumn("DiscogsId").AsInt32().Nullable()
.WithColumn("Title").AsString()
.WithColumn("TitleSlug").AsString().Nullable().Unique()
.WithColumn("CleanTitle").AsString().Indexed()
.WithColumn("Overview").AsString().Nullable()
.WithColumn("Ignored").AsBoolean().Nullable()
.WithColumn("EpisodeFileId").AsInt32().Nullable()
.WithColumn("AirDate").AsDateTime().Nullable()
.WithColumn("AbsoluteEpisodeNumber").AsInt32().Nullable()
.WithColumn("SceneAbsoluteEpisodeNumber").AsInt32().Nullable()
.WithColumn("SceneSeasonNumber").AsInt32().Nullable()
.WithColumn("SceneEpisodeNumber").AsInt32().Nullable();
Create.TableForModel("EpisodeFiles")
.WithColumn("SeriesId").AsInt32()
.WithColumn("Path").AsString().Unique()
.WithColumn("Quality").AsString()
.WithColumn("Size").AsInt64()
.WithColumn("DateAdded").AsDateTime()
.WithColumn("SeasonNumber").AsInt32()
.WithColumn("SceneName").AsString().Nullable()
.WithColumn("ReleaseGroup").AsString().Nullable();
.WithColumn("Images").AsString()
.WithColumn("Path").AsString().Indexed()
.WithColumn("Monitored").AsBoolean()
.WithColumn("LastInfoSync").AsDateTime().Nullable()
.WithColumn("LastDiskSync").AsDateTime().Nullable()
.WithColumn("ReleaseDate").AsDateTime().Nullable()
.WithColumn("Ratings").AsString().Nullable()
.WithColumn("Genres").AsString().Nullable()
.WithColumn("Label").AsString().Nullable()
.WithColumn("SortTitle").AsString().Nullable()
.WithColumn("ProfileId").AsInt32().Nullable()
.WithColumn("Tags").AsString().Nullable()
.WithColumn("Added").AsDateTime().Nullable()
.WithColumn("AlbumType").AsString()
.WithColumn("AddOptions").AsString().Nullable()
.WithColumn("Duration").AsInt32().WithDefaultValue(0);
Create.TableForModel("Tracks")
.WithColumn("ForeignTrackId").AsString().Unique()
.WithColumn("ArtistId").AsInt32().Indexed()
.WithColumn("AlbumId").AsInt32()
.WithColumn("TrackNumber").AsInt32()
.WithColumn("Title").AsString().Nullable()
.WithColumn("Explicit").AsBoolean()
.WithColumn("Compilation").AsBoolean()
.WithColumn("DiscNumber").AsInt32().Nullable()
.WithColumn("TrackFileId").AsInt32().Nullable().Indexed()
.WithColumn("Monitored").AsBoolean()
.WithColumn("Ratings").AsString().Nullable()
.WithColumn("Duration").AsInt32().WithDefaultValue(0);
Create.Index().OnTable("Tracks").OnColumn("ArtistId").Ascending()
.OnColumn("AlbumId").Ascending()
.OnColumn("TrackNumber").Ascending();
Create.TableForModel("TrackFiles")
.WithColumn("ArtistId").AsInt32().Indexed()
.WithColumn("AlbumId").AsInt32().Indexed()
.WithColumn("Quality").AsString()
.WithColumn("Size").AsInt64()
.WithColumn("SceneName").AsString().Nullable()
.WithColumn("DateAdded").AsDateTime()
.WithColumn("ReleaseGroup").AsString().Nullable()
.WithColumn("MediaInfo").AsString().Nullable()
.WithColumn("RelativePath").AsString().Nullable()
.WithColumn("Language").AsInt32().WithDefaultValue(0);
Create.TableForModel("History")
.WithColumn("EpisodeId").AsInt32()
.WithColumn("SeriesId").AsInt32()
.WithColumn("NzbTitle").AsString()
.WithColumn("Date").AsDateTime()
.WithColumn("Quality").AsString()
.WithColumn("Indexer").AsString()
.WithColumn("NzbInfoUrl").AsString().Nullable()
.WithColumn("ReleaseGroup").AsString().Nullable();
.WithColumn("SourceTitle").AsString()
.WithColumn("Date").AsDateTime().Indexed()
.WithColumn("Quality").AsString()
.WithColumn("Data").AsString()
.WithColumn("EventType").AsInt32().Nullable().Indexed()
.WithColumn("DownloadId").AsString().Nullable().Indexed()
.WithColumn("Language").AsInt32().NotNullable().WithDefaultValue(0)
.WithColumn("ArtistId").AsInt32().WithDefaultValue(0)
.WithColumn("AlbumId").AsInt32().Indexed().WithDefaultValue(0)
.WithColumn("TrackId").AsInt32().WithDefaultValue(0);
Create.TableForModel("Notifications")
.WithColumn("Name").AsString()
.WithColumn("OnGrab").AsBoolean()
.WithColumn("OnDownload").AsBoolean()
.WithColumn("Settings").AsString()
.WithColumn("Implementation").AsString();
.WithColumn("Name").AsString()
.WithColumn("OnGrab").AsBoolean()
.WithColumn("OnDownload").AsBoolean()
.WithColumn("Settings").AsString()
.WithColumn("Implementation").AsString()
.WithColumn("ConfigContract").AsString().Nullable()
.WithColumn("OnUpgrade").AsBoolean().Nullable()
.WithColumn("Tags").AsString().Nullable()
.WithColumn("OnRename").AsBoolean().NotNullable();
Create.TableForModel("ScheduledTasks")
.WithColumn("TypeName").AsString().Unique()
.WithColumn("Interval").AsInt32()
.WithColumn("LastExecution").AsDateTime();
.WithColumn("TypeName").AsString().Unique()
.WithColumn("Interval").AsInt32()
.WithColumn("LastExecution").AsDateTime();
Create.TableForModel("Indexers")
.WithColumn("Enable").AsBoolean()
.WithColumn("Name").AsString().Unique()
.WithColumn("Implementation").AsString()
.WithColumn("Settings").AsString().Nullable();
.WithColumn("Name").AsString().Unique()
.WithColumn("Implementation").AsString()
.WithColumn("Settings").AsString().Nullable()
.WithColumn("ConfigContract").AsString().Nullable()
.WithColumn("EnableRss").AsBoolean().Nullable()
.WithColumn("EnableSearch").AsBoolean().Nullable();
Create.TableForModel("Profiles")
.WithColumn("Name").AsString().Unique()
.WithColumn("Cutoff").AsInt32()
.WithColumn("Items").AsString().NotNullable();
Create.TableForModel("QualityProfiles")
.WithColumn("Name").AsString().Unique()
.WithColumn("Cutoff").AsInt32()
.WithColumn("Allowed").AsString();
Create.TableForModel("QualityDefinitions")
.WithColumn("Quality").AsInt32().Unique()
.WithColumn("Title").AsString().Unique()
.WithColumn("MinSize").AsDouble().Nullable()
.WithColumn("MaxSize").AsDouble().Nullable();
Create.TableForModel("QualitySizes")
.WithColumn("QualityId").AsInt32().Unique()
.WithColumn("Name").AsString().Unique()
.WithColumn("MinSize").AsInt32()
.WithColumn("MaxSize").AsInt32();
Create.TableForModel("NamingConfig")
.WithColumn("ReplaceIllegalCharacters").AsBoolean().WithDefaultValue(true)
.WithColumn("ArtistFolderFormat").AsString().Nullable()
.WithColumn("RenameTracks").AsBoolean().Nullable()
.WithColumn("StandardTrackFormat").AsString().Nullable()
.WithColumn("AlbumFolderFormat").AsString().Nullable();
Create.TableForModel("SceneMappings")
.WithColumn("CleanTitle").AsString()
.WithColumn("SceneName").AsString()
.WithColumn("TvdbId").AsInt32()
.WithColumn("SeasonNumber").AsInt32();
Create.TableForModel("Blacklist")
.WithColumn("SourceTitle").AsString()
.WithColumn("Quality").AsString()
.WithColumn("Date").AsDateTime()
.WithColumn("PublishedDate").AsDateTime().Nullable()
.WithColumn("Size").AsInt64().Nullable()
.WithColumn("Protocol").AsInt32().Nullable()
.WithColumn("Indexer").AsString().Nullable()
.WithColumn("Message").AsString().Nullable()
.WithColumn("TorrentInfoHash").AsString().Nullable()
.WithColumn("Language").AsInt32().NotNullable().WithDefaultValue(0)
.WithColumn("ArtistId").AsInt32().WithDefaultValue(0)
.WithColumn("AlbumIds").AsString().WithDefaultValue("");
Create.TableForModel("Metadata")
.WithColumn("Enable").AsBoolean().NotNullable()
.WithColumn("Name").AsString().NotNullable()
.WithColumn("Implementation").AsString().NotNullable()
.WithColumn("Settings").AsString().NotNullable()
.WithColumn("ConfigContract").AsString().NotNullable();
Create.TableForModel("NamingConfig")
.WithColumn("UseSceneName").AsBoolean()
.WithColumn("Separator").AsString()
.WithColumn("NumberStyle").AsInt32()
.WithColumn("IncludeSeriesTitle").AsBoolean()
.WithColumn("MultiEpisodeStyle").AsInt32()
.WithColumn("IncludeEpisodeTitle").AsBoolean()
.WithColumn("IncludeQuality").AsBoolean()
.WithColumn("ReplaceSpaces").AsBoolean()
.WithColumn("SeasonFolderFormat").AsString();
Create.TableForModel("MetadataFiles")
.WithColumn("ArtistId").AsInt32().NotNullable()
.WithColumn("Consumer").AsString().NotNullable()
.WithColumn("Type").AsInt32().NotNullable()
.WithColumn("RelativePath").AsString().NotNullable()
.WithColumn("LastUpdated").AsDateTime().NotNullable()
.WithColumn("AlbumId").AsInt32().Nullable()
.WithColumn("TrackFileId").AsInt32().Nullable()
.WithColumn("Hash").AsString().Nullable()
.WithColumn("Added").AsDateTime().Nullable()
.WithColumn("Extension").AsString().NotNullable();
Create.TableForModel("DownloadClients")
.WithColumn("Enable").AsBoolean().NotNullable()
.WithColumn("Name").AsString().NotNullable()
.WithColumn("Implementation").AsString().NotNullable()
.WithColumn("Settings").AsString().NotNullable()
.WithColumn("ConfigContract").AsString().NotNullable();
Create.TableForModel("PendingReleases")
.WithColumn("Title").AsString()
.WithColumn("Added").AsDateTime()
.WithColumn("Release").AsString()
.WithColumn("ArtistId").AsInt32().WithDefaultValue(0)
.WithColumn("ParsedAlbumInfo").AsString().WithDefaultValue("");
Create.TableForModel("RemotePathMappings")
.WithColumn("Host").AsString()
.WithColumn("RemotePath").AsString()
.WithColumn("LocalPath").AsString();
Create.TableForModel("Tags")
.WithColumn("Label").AsString().Unique();
Create.TableForModel("Restrictions")
.WithColumn("Required").AsString().Nullable()
.WithColumn("Preferred").AsString().Nullable()
.WithColumn("Ignored").AsString().Nullable()
.WithColumn("Tags").AsString().NotNullable();
Create.TableForModel("DelayProfiles")
.WithColumn("EnableUsenet").AsBoolean().NotNullable()
.WithColumn("EnableTorrent").AsBoolean().NotNullable()
.WithColumn("PreferredProtocol").AsInt32().NotNullable()
.WithColumn("UsenetDelay").AsInt32().NotNullable()
.WithColumn("TorrentDelay").AsInt32().NotNullable()
.WithColumn("Order").AsInt32().NotNullable()
.WithColumn("Tags").AsString().NotNullable();
Create.TableForModel("Users")
.WithColumn("Identifier").AsString().NotNullable().Unique()
.WithColumn("Username").AsString().NotNullable().Unique()
.WithColumn("Password").AsString().NotNullable();
Create.TableForModel("Commands")
.WithColumn("Name").AsString().NotNullable()
.WithColumn("Body").AsString().NotNullable()
.WithColumn("Priority").AsInt32().NotNullable()
.WithColumn("Status").AsInt32().NotNullable()
.WithColumn("QueuedAt").AsDateTime().NotNullable()
.WithColumn("StartedAt").AsDateTime().Nullable()
.WithColumn("EndedAt").AsDateTime().Nullable()
.WithColumn("Duration").AsString().Nullable()
.WithColumn("Exception").AsString().Nullable()
.WithColumn("Trigger").AsInt32().NotNullable();
Create.TableForModel("IndexerStatus")
.WithColumn("ProviderId").AsInt32().NotNullable().Unique()
.WithColumn("InitialFailure").AsDateTime().Nullable()
.WithColumn("MostRecentFailure").AsDateTime().Nullable()
.WithColumn("EscalationLevel").AsInt32().NotNullable()
.WithColumn("DisabledTill").AsDateTime().Nullable()
.WithColumn("LastRssSyncReleaseInfo").AsString().Nullable();
Create.TableForModel("ExtraFiles")
.WithColumn("ArtistId").AsInt32().NotNullable()
.WithColumn("AlbumId").AsInt32().NotNullable()
.WithColumn("TrackFileId").AsInt32().NotNullable()
.WithColumn("RelativePath").AsString().NotNullable()
.WithColumn("Extension").AsString().NotNullable()
.WithColumn("Added").AsDateTime().NotNullable()
.WithColumn("LastUpdated").AsDateTime().NotNullable();
Create.TableForModel("LyricFiles")
.WithColumn("ArtistId").AsInt32().NotNullable()
.WithColumn("AlbumId").AsInt32().NotNullable()
.WithColumn("TrackFileId").AsInt32().NotNullable()
.WithColumn("RelativePath").AsString().NotNullable()
.WithColumn("Extension").AsString().NotNullable()
.WithColumn("Added").AsDateTime().NotNullable()
.WithColumn("LastUpdated").AsDateTime().NotNullable()
.WithColumn("Language").AsInt32().NotNullable();
Create.TableForModel("LanguageProfiles")
.WithColumn("Name").AsString().Unique()
.WithColumn("Languages").AsString()
.WithColumn("Cutoff").AsInt32();
Create.TableForModel("DownloadClientStatus")
.WithColumn("ProviderId").AsInt32().NotNullable().Unique()
.WithColumn("InitialFailure").AsDateTime().Nullable()
.WithColumn("MostRecentFailure").AsDateTime().Nullable()
.WithColumn("EscalationLevel").AsInt32().NotNullable()
.WithColumn("DisabledTill").AsDateTime().Nullable();
Insert.IntoTable("DelayProfiles").Row(new
{
EnableUsenet = 1,
EnableTorrent = 1,
PreferredProtocol = 1,
UsenetDelay = 0,
TorrentDelay = 0,
Order = int.MaxValue,
Tags = "[]"
});
}
protected override void LogDbUpgrade()
{
Create.TableForModel("Logs")
.WithColumn("Message").AsString()
.WithColumn("Time").AsDateTime()
.WithColumn("Time").AsDateTime().Indexed()
.WithColumn("Logger").AsString()
.WithColumn("Method").AsString().Nullable()
.WithColumn("Exception").AsString().Nullable()
.WithColumn("ExceptionType").AsString().Nullable()
.WithColumn("Level").AsString();

@ -1,15 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(2)]
public class remove_tvrage_imdb_unique_constraint : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Index().OnTable("Series").OnColumn("TvRageId");
Delete.Index().OnTable("Series").OnColumn("ImdbId");
}
}
}

@ -1,20 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(3)]
public class remove_renamed_scene_mapping_columns : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Table("SceneMappings");
Create.TableForModel("SceneMappings")
.WithColumn("TvdbId").AsInt32()
.WithColumn("SeasonNumber").AsInt32()
.WithColumn("SearchTerm").AsString()
.WithColumn("ParseTerm").AsString();
}
}
}

@ -1,23 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(4)]
public class updated_history : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Table("History");
Create.TableForModel("History")
.WithColumn("EpisodeId").AsInt32()
.WithColumn("SeriesId").AsInt32()
.WithColumn("SourceTitle").AsString()
.WithColumn("Date").AsDateTime()
.WithColumn("Quality").AsString()
.WithColumn("Data").AsString();
}
}
}

@ -1,17 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(5)]
public class added_eventtype_to_history : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("History")
.AddColumn("EventType")
.AsInt32()
.Nullable();
}
}
}

@ -1,23 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(6)]
public class add_index_to_log_time : NzbDroneMigrationBase
{
protected override void LogDbUpgrade()
{
Delete.Table("Logs");
Create.TableForModel("Logs")
.WithColumn("Message").AsString()
.WithColumn("Time").AsDateTime().Indexed()
.WithColumn("Logger").AsString()
.WithColumn("Method").AsString().Nullable()
.WithColumn("Exception").AsString().Nullable()
.WithColumn("ExceptionType").AsString().Nullable()
.WithColumn("Level").AsString();
}
}
}

@ -1,19 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(7)]
public class add_renameEpisodes_to_naming : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("NamingConfig")
.AddColumn("RenameEpisodes")
.AsBoolean()
.Nullable();
Execute.Sql("UPDATE NamingConfig SET RenameEpisodes =~ UseSceneName");
}
}
}

@ -1,15 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(8)]
public class remove_backlog : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("BacklogSetting").FromTable("Series");
Delete.Column("UseSceneName").FromTable("NamingConfig");
}
}
}

@ -1,17 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(9)]
public class fix_rename_episodes : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("SeasonFolderFormat").FromTable("NamingConfig");
Execute.Sql("UPDATE NamingConfig SET RenameEpisodes = 1 WHERE RenameEpisodes = -1");
Execute.Sql("UPDATE NamingConfig SET RenameEpisodes = 0 WHERE RenameEpisodes = -2");
}
}
}

@ -1,21 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(10)]
public class add_monitored : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Episodes").AddColumn("Monitored").AsBoolean().Nullable();
Alter.Table("Seasons").AddColumn("Monitored").AsBoolean().Nullable();
Execute.Sql("UPDATE Episodes SET Monitored = 1 WHERE Ignored = 0");
Execute.Sql("UPDATE Episodes SET Monitored = 0 WHERE Ignored = 1");
Execute.Sql("UPDATE Seasons SET Monitored = 1 WHERE Ignored = 0");
Execute.Sql("UPDATE Seasons SET Monitored = 0 WHERE Ignored = 1");
}
}
}

@ -1,15 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(11)]
public class remove_ignored : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("Ignored").FromTable("Seasons");
Delete.Column("Ignored").FromTable("Episodes");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(12)]
public class remove_custom_start_date : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("CustomStartDate").FromTable("Series");
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(13)]
public class add_air_date_utc : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Episodes").AddColumn("AirDateUtc").AsDateTime().Nullable();
Execute.Sql("UPDATE Episodes SET AirDateUtc = AirDate");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(14)]
public class drop_air_date : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("AirDate").FromTable("Episodes");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(15)]
public class add_air_date_as_string : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Episodes").AddColumn("AirDate").AsString().Nullable();
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(16)]
public class updated_imported_history_item : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql(@"UPDATE HISTORY SET Data = replace( Data, '""Path""', '""ImportedPath""' ) WHERE EventType=3");
}
}
}

@ -1,15 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(17)]
public class reset_scene_names : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
//we were storing new file name as scene name.
Execute.Sql(@"UPDATE EpisodeFiles SET SceneName = NULL where SceneName != NULL");
}
}
}

@ -1,99 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
using System.Linq;
using System.Data;
using System.Collections.Generic;
using System;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(18)]
public class remove_duplicates : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.WithConnection(RemoveDuplicates);
}
private void RemoveDuplicates(IDbConnection conn, IDbTransaction tran)
{
RemoveDuplicateSeries<int>(conn, tran, "TvdbId");
RemoveDuplicateSeries<string>(conn, tran, "TitleSlug");
var duplicatedEpisodes = GetDuplicates<int>(conn, tran, "Episodes", "TvDbEpisodeId");
foreach (var duplicate in duplicatedEpisodes)
{
foreach (var episodeId in duplicate.OrderBy(c => c.Key).Skip(1).Select(c => c.Key))
{
RemoveEpisodeRows(conn, tran, episodeId);
}
}
}
private IEnumerable<IGrouping<T, KeyValuePair<int, T>>> GetDuplicates<T>(IDbConnection conn, IDbTransaction tran, string tableName, string columnName)
{
var getDuplicates = conn.CreateCommand();
getDuplicates.Transaction = tran;
getDuplicates.CommandText = string.Format("select id, {0} from {1}", columnName, tableName);
var result = new List<KeyValuePair<int, T>>();
using (var reader = getDuplicates.ExecuteReader())
{
while (reader.Read())
{
result.Add(new KeyValuePair<int, T>(reader.GetInt32(0), (T)Convert.ChangeType(reader[1], typeof(T))));
}
}
return result.GroupBy(c => c.Value).Where(g => g.Count() > 1);
}
private void RemoveDuplicateSeries<T>(IDbConnection conn, IDbTransaction tran, string field)
{
var duplicatedSeries = GetDuplicates<T>(conn, tran, "Series", field);
foreach (var duplicate in duplicatedSeries)
{
foreach (var seriesId in duplicate.OrderBy(c => c.Key).Skip(1).Select(c => c.Key))
{
RemoveSeriesRows(conn, tran, seriesId);
}
}
}
private void RemoveSeriesRows(IDbConnection conn, IDbTransaction tran, int seriesId)
{
var deleteCmd = conn.CreateCommand();
deleteCmd.Transaction = tran;
deleteCmd.CommandText = string.Format("DELETE FROM Series WHERE Id = {0}", seriesId.ToString());
deleteCmd.ExecuteNonQuery();
deleteCmd.CommandText = string.Format("DELETE FROM Episodes WHERE SeriesId = {0}", seriesId.ToString());
deleteCmd.ExecuteNonQuery();
deleteCmd.CommandText = string.Format("DELETE FROM Seasons WHERE SeriesId = {0}", seriesId.ToString());
deleteCmd.ExecuteNonQuery();
deleteCmd.CommandText = string.Format("DELETE FROM History WHERE SeriesId = {0}", seriesId.ToString());
deleteCmd.ExecuteNonQuery();
deleteCmd.CommandText = string.Format("DELETE FROM EpisodeFiles WHERE SeriesId = {0}", seriesId.ToString());
deleteCmd.ExecuteNonQuery();
}
private void RemoveEpisodeRows(IDbConnection conn, IDbTransaction tran, int episodeId)
{
var deleteCmd = conn.CreateCommand();
deleteCmd.Transaction = tran;
deleteCmd.CommandText = string.Format("DELETE FROM Episodes WHERE Id = {0}", episodeId.ToString());
deleteCmd.ExecuteNonQuery();
deleteCmd.CommandText = string.Format("DELETE FROM History WHERE EpisodeId = {0}", episodeId.ToString());
deleteCmd.ExecuteNonQuery();
}
}
}

@ -1,22 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(19)]
public class restore_unique_constraints : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
// During an earlier version of drone, the indexes weren't recreated during alter table.
Execute.Sql("DROP INDEX IF EXISTS \"IX_Series_TvdbId\"");
Execute.Sql("DROP INDEX IF EXISTS \"IX_Series_TitleSlug\"");
Execute.Sql("DROP INDEX IF EXISTS \"IX_Episodes_TvDbEpisodeId\"");
Create.Index().OnTable("Series").OnColumn("TvdbId").Unique();
Create.Index().OnTable("Series").OnColumn("TitleSlug").Unique();
Create.Index().OnTable("Episodes").OnColumn("TvDbEpisodeId").Unique();
}
}
}

@ -1,68 +0,0 @@
using System.Collections.Generic;
using System.Data;
using FluentMigrator;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(20)]
public class add_year_and_seasons_to_series : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Series").AddColumn("Year").AsInt32().Nullable();
Alter.Table("Series").AddColumn("Seasons").AsString().Nullable();
Execute.WithConnection(ConvertSeasons);
}
private void ConvertSeasons(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand allSeriesCmd = conn.CreateCommand())
{
allSeriesCmd.Transaction = tran;
allSeriesCmd.CommandText = @"SELECT Id FROM Series";
using (IDataReader allSeriesReader = allSeriesCmd.ExecuteReader())
{
while (allSeriesReader.Read())
{
int seriesId = allSeriesReader.GetInt32(0);
var seasons = new List<dynamic>();
using (IDbCommand seasonsCmd = conn.CreateCommand())
{
seasonsCmd.Transaction = tran;
seasonsCmd.CommandText = string.Format(@"SELECT SeasonNumber, Monitored FROM Seasons WHERE SeriesId = {0}", seriesId);
using (IDataReader seasonReader = seasonsCmd.ExecuteReader())
{
while (seasonReader.Read())
{
int seasonNumber = seasonReader.GetInt32(0);
bool monitored = seasonReader.GetBoolean(1);
if (seasonNumber == 0)
{
monitored = false;
}
seasons.Add(new { seasonNumber, monitored });
}
}
}
using (IDbCommand updateCmd = conn.CreateCommand())
{
var text = string.Format("UPDATE Series SET Seasons = '{0}' WHERE Id = {1}", seasons.ToJson() , seriesId);
updateCmd.Transaction = tran;
updateCmd.CommandText = text;
updateCmd.ExecuteNonQuery();
}
}
}
}
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(21)]
public class drop_seasons_table : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Table("Seasons");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(22)]
public class move_indexer_to_generic_provider : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Indexers").AddColumn("ConfigContract").AsString().Nullable();
}
}
}

@ -1,19 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(23)]
public class add_config_contract_to_indexers : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Update.Table("Indexers").Set(new { ConfigContract = "NewznabSettings" }).Where(new { Implementation = "Newznab" });
Update.Table("Indexers").Set(new { ConfigContract = "OmgwtfnzbsSettings" }).Where(new { Implementation = "Omgwtfnzbs" });
Update.Table("Indexers").Set(new { ConfigContract = "NullConfig" }).Where(new { Implementation = "Wombles" });
Update.Table("Indexers").Set(new { ConfigContract = "NullConfig" }).Where(new { Implementation = "Eztv" });
Delete.FromTable("Indexers").IsNull("ConfigContract");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(24)]
public class drop_tvdb_episodeid : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("TvDbEpisodeId").FromTable("Episodes");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(25)]
public class move_notification_to_generic_provider : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Notifications").AddColumn("ConfigContract").AsString().Nullable();
}
}
}

@ -1,24 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(26)]
public class add_config_contract_to_notifications : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Update.Table("Notifications").Set(new { ConfigContract = "EmailSettings" }).Where(new { Implementation = "Email" });
Update.Table("Notifications").Set(new { ConfigContract = "GrowlSettings" }).Where(new { Implementation = "Growl" });
Update.Table("Notifications").Set(new { ConfigContract = "NotifyMyAndroidSettings" }).Where(new { Implementation = "NotifyMyAndroid" });
Update.Table("Notifications").Set(new { ConfigContract = "PlexClientSettings" }).Where(new { Implementation = "PlexClient" });
Update.Table("Notifications").Set(new { ConfigContract = "PlexServerSettings" }).Where(new { Implementation = "PlexServer" });
Update.Table("Notifications").Set(new { ConfigContract = "ProwlSettings" }).Where(new { Implementation = "Prowl" });
Update.Table("Notifications").Set(new { ConfigContract = "PushBulletSettings" }).Where(new { Implementation = "PushBullet" });
Update.Table("Notifications").Set(new { ConfigContract = "PushoverSettings" }).Where(new { Implementation = "Pushover" });
Update.Table("Notifications").Set(new { ConfigContract = "XbmcSettings" }).Where(new { Implementation = "Xbmc" });
Delete.FromTable("Notifications").IsNull("ConfigContract");
}
}
}

@ -1,24 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(27)]
public class fix_omgwtfnzbs : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Update.Table("Indexers")
.Set(new {ConfigContract = "OmgwtfnzbsSettings"})
.Where(new {Implementation = "Omgwtfnzbs"});
Update.Table("Indexers")
.Set(new {Settings = "{}"})
.Where(new {Implementation = "Omgwtfnzbs", Settings = (string) null});
Update.Table("Indexers")
.Set(new { Settings = "{}" })
.Where(new { Implementation = "Omgwtfnzbs", Settings = "" });
}
}
}

@ -1,19 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(28)]
public class add_blacklist_table : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.TableForModel("Blacklist")
.WithColumn("SeriesId").AsInt32()
.WithColumn("EpisodeIds").AsString()
.WithColumn("SourceTitle").AsString()
.WithColumn("Quality").AsString()
.WithColumn("Date").AsDateTime();
}
}
}

@ -1,154 +0,0 @@
using System.Collections.Generic;
using System.Data;
using System.Linq;
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(29)]
public class add_formats_to_naming_config : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("NamingConfig").AddColumn("StandardEpisodeFormat").AsString().Nullable();
Alter.Table("NamingConfig").AddColumn("DailyEpisodeFormat").AsString().Nullable();
Execute.WithConnection(ConvertConfig);
}
private void ConvertConfig(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand namingConfigCmd = conn.CreateCommand())
{
namingConfigCmd.Transaction = tran;
namingConfigCmd.CommandText = @"SELECT * FROM NamingConfig LIMIT 1";
using (IDataReader namingConfigReader = namingConfigCmd.ExecuteReader())
{
var separatorIndex = namingConfigReader.GetOrdinal("Separator");
var numberStyleIndex = namingConfigReader.GetOrdinal("NumberStyle");
var includeSeriesTitleIndex = namingConfigReader.GetOrdinal("IncludeSeriesTitle");
var includeEpisodeTitleIndex = namingConfigReader.GetOrdinal("IncludeEpisodeTitle");
var includeQualityIndex = namingConfigReader.GetOrdinal("IncludeQuality");
var replaceSpacesIndex = namingConfigReader.GetOrdinal("ReplaceSpaces");
while (namingConfigReader.Read())
{
var separator = namingConfigReader.GetString(separatorIndex);
var numberStyle = namingConfigReader.GetInt32(numberStyleIndex);
var includeSeriesTitle = namingConfigReader.GetBoolean(includeSeriesTitleIndex);
var includeEpisodeTitle = namingConfigReader.GetBoolean(includeEpisodeTitleIndex);
var includeQuality = namingConfigReader.GetBoolean(includeQualityIndex);
var replaceSpaces = namingConfigReader.GetBoolean(replaceSpacesIndex);
//Output settings
var seriesTitlePattern = "";
var episodeTitlePattern = "";
var dailyEpisodePattern = "{Air-Date}";
var qualityFormat = " [{Quality Title}]";
if (includeSeriesTitle)
{
if (replaceSpaces)
{
seriesTitlePattern = "{Series.Title}";
}
else
{
seriesTitlePattern = "{Series Title}";
}
seriesTitlePattern += separator;
}
if (includeEpisodeTitle)
{
episodeTitlePattern = separator;
if (replaceSpaces)
{
episodeTitlePattern += "{Episode.Title}";
}
else
{
episodeTitlePattern += "{Episode Title}";
}
}
var standardEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern,
GetNumberStyle(numberStyle).Pattern,
episodeTitlePattern);
var dailyEpisodeFormat = string.Format("{0}{1}{2}", seriesTitlePattern,
dailyEpisodePattern,
episodeTitlePattern);
if (includeQuality)
{
if (replaceSpaces)
{
qualityFormat = ".[{Quality.Title}]";
}
standardEpisodeFormat += qualityFormat;
dailyEpisodeFormat += qualityFormat;
}
using (IDbCommand updateCmd = conn.CreateCommand())
{
var text = string.Format("UPDATE NamingConfig " +
"SET StandardEpisodeFormat = '{0}', " +
"DailyEpisodeFormat = '{1}'",
standardEpisodeFormat,
dailyEpisodeFormat);
updateCmd.Transaction = tran;
updateCmd.CommandText = text;
updateCmd.ExecuteNonQuery();
}
}
}
}
}
private static readonly List<dynamic> NumberStyles = new List<dynamic>
{
new
{
Id = 0,
Name = "1x05",
Pattern = "{season}x{episode:00}",
EpisodeSeparator = "x"
},
new
{
Id = 1,
Name = "01x05",
Pattern = "{season:00}x{episode:00}",
EpisodeSeparator = "x"
},
new
{
Id = 2,
Name = "S01E05",
Pattern = "S{season:00}E{episode:00}",
EpisodeSeparator = "E"
},
new
{
Id = 3,
Name = "s01e05",
Pattern = "s{season:00}e{episode:00}",
EpisodeSeparator = "e"
}
};
private static dynamic GetNumberStyle(int id)
{
return NumberStyles.Single(s => s.Id == id);
}
}
}

@ -1,55 +0,0 @@
using System.Data;
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(30)]
public class add_season_folder_format_to_naming_config : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("NamingConfig").AddColumn("SeasonFolderFormat").AsString().Nullable();
Execute.WithConnection(ConvertConfig);
Execute.Sql("DELETE FROM Config WHERE [Key] = 'seasonfolderformat'");
Execute.Sql("DELETE FROM Config WHERE [Key] = 'useseasonfolder'");
}
private void ConvertConfig(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand namingConfigCmd = conn.CreateCommand())
{
namingConfigCmd.Transaction = tran;
namingConfigCmd.CommandText = @"SELECT [Value] FROM Config WHERE [Key] = 'seasonfolderformat'";
var seasonFormat = "Season {season}";
using (IDataReader namingConfigReader = namingConfigCmd.ExecuteReader())
{
while (namingConfigReader.Read())
{
//only getting one column, so its index is 0
seasonFormat = namingConfigReader.GetString(0);
seasonFormat = seasonFormat.Replace("%sn", "{Series Title}")
.Replace("%s.n", "{Series.Title}")
.Replace("%s", "{season}")
.Replace("%0s", "{season:00}")
.Replace("%e", "{episode}")
.Replace("%0e", "{episode:00}");
}
}
using (IDbCommand updateCmd = conn.CreateCommand())
{
var text = string.Format("UPDATE NamingConfig " +
"SET SeasonFolderFormat = '{0}'",
seasonFormat);
updateCmd.Transaction = tran;
updateCmd.CommandText = text;
updateCmd.ExecuteNonQuery();
}
}
}
}
}

@ -1,20 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(31)]
public class delete_old_naming_config_columns : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("Separator")
.Column("NumberStyle")
.Column("IncludeSeriesTitle")
.Column("IncludeEpisodeTitle")
.Column("IncludeQuality")
.Column("ReplaceSpaces")
.FromTable("NamingConfig");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(32)]
public class set_default_release_group : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE EpisodeFiles SET ReleaseGroup = 'DRONE' WHERE ReleaseGroup IS NULL");
}
}
}

@ -1,66 +0,0 @@
using System.Data;
using FluentMigrator;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(33)]
public class add_api_key_to_pushover : NzbDroneMigrationBase
{
private const string API_KEY = "yz9b4U215iR4vrKFRfjNXP24NMNPKJ";
protected override void MainDbUpgrade()
{
Execute.WithConnection(UpdatePushoverSettings);
}
private void UpdatePushoverSettings(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand selectCommand = conn.CreateCommand())
{
selectCommand.Transaction = tran;
selectCommand.CommandText = @"SELECT * FROM Notifications WHERE ConfigContract = 'PushoverSettings'";
using (IDataReader reader = selectCommand.ExecuteReader())
{
while (reader.Read())
{
var idIndex = reader.GetOrdinal("Id");
var settingsIndex = reader.GetOrdinal("Settings");
var id = reader.GetInt32(idIndex);
var settings = Json.Deserialize<PushoverSettingsForV33>(reader.GetString(settingsIndex));
settings.ApiKey = API_KEY;
//Set priority to high if its currently emergency
if (settings.Priority == 2)
{
settings.Priority = 1;
}
using (IDbCommand updateCmd = conn.CreateCommand())
{
var text = string.Format("UPDATE Notifications " +
"SET Settings = '{0}'" +
"WHERE Id = {1}",
settings.ToJson(), id
);
updateCmd.Transaction = tran;
updateCmd.CommandText = text;
updateCmd.ExecuteNonQuery();
}
}
}
}
}
private class PushoverSettingsForV33
{
public string ApiKey { get; set; }
public string UserKey { get; set; }
public int Priority { get; set; }
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(34)]
public class remove_series_contraints : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Series")
.AlterColumn("ImdbId").AsString().Nullable()
.AlterColumn("TitleSlug").AsString().Nullable();
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(35)]
public class add_series_folder_format_to_naming_config : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("NamingConfig").AddColumn("SeriesFolderFormat").AsString().Nullable();
Execute.Sql("UPDATE NamingConfig SET SeriesFolderFormat = '{Series Title}'");
}
}
}

@ -1,129 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
using System.Data;
using System.Linq;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Profiles.Qualities;
using NzbDrone.Core.Qualities;
using System.Collections.Generic;
using NzbDrone.Core.Datastore.Converters;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(36)]
public class update_with_quality_converters : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
if (!Schema.Table("QualityProfiles").Column("Items").Exists())
{
Alter.Table("QualityProfiles").AddColumn("Items").AsString().Nullable();
}
Execute.WithConnection(ConvertQualityProfiles);
Execute.WithConnection(ConvertQualityModels);
}
private void ConvertQualityProfiles(IDbConnection conn, IDbTransaction tran)
{
var qualityProfileItemConverter = new EmbeddedDocumentConverter(new QualityIntConverter());
// Convert 'Allowed' column in QualityProfiles from Json List<object> to Json List<int> (int = Quality)
using (IDbCommand qualityProfileCmd = conn.CreateCommand())
{
qualityProfileCmd.Transaction = tran;
qualityProfileCmd.CommandText = @"SELECT Id, Allowed FROM QualityProfiles";
using (IDataReader qualityProfileReader = qualityProfileCmd.ExecuteReader())
{
while (qualityProfileReader.Read())
{
var id = qualityProfileReader.GetInt32(0);
var allowedJson = qualityProfileReader.GetString(1);
var allowed = Json.Deserialize<List<Quality>>(allowedJson);
var items = Quality.DefaultQualityDefinitions.OrderBy(v => v.Weight).Select(v => new ProfileQualityItem { Quality = v.Quality, Allowed = allowed.Contains(v.Quality) }).ToList();
var allowedNewJson = qualityProfileItemConverter.ToDB(items);
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE QualityProfiles SET Items = ? WHERE Id = ?";
updateCmd.AddParameter(allowedNewJson);
updateCmd.AddParameter(id);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
private void ConvertQualityModels(IDbConnection conn, IDbTransaction tran)
{
// Converts the QualityModel JSON objects to their new format (only storing the QualityId instead of the entire object)
ConvertQualityModel(conn, tran, "Blacklist");
ConvertQualityModel(conn, tran, "EpisodeFiles");
ConvertQualityModel(conn, tran, "History");
}
private void ConvertQualityModel(IDbConnection conn, IDbTransaction tran, string tableName)
{
var qualityModelConverter = new EmbeddedDocumentConverter(new QualityIntConverter());
using (IDbCommand qualityModelCmd = conn.CreateCommand())
{
qualityModelCmd.Transaction = tran;
qualityModelCmd.CommandText = @"SELECT Distinct Quality FROM " + tableName;
using (IDataReader qualityModelReader = qualityModelCmd.ExecuteReader())
{
while (qualityModelReader.Read())
{
var qualityJson = qualityModelReader.GetString(0);
SourceQualityModel036 sourceQuality;
if (!Json.TryDeserialize<SourceQualityModel036>(qualityJson, out sourceQuality))
{
continue;
}
var qualityNewJson = qualityModelConverter.ToDB(new DestinationQualityModel036
{
Quality = sourceQuality.Quality.Id,
Proper = sourceQuality.Proper
});
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE " + tableName + " SET Quality = ? WHERE Quality = ?";
updateCmd.AddParameter(qualityNewJson);
updateCmd.AddParameter(qualityJson);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
private class DestinationQualityModel036
{
public int Quality { get; set; }
public bool Proper { get; set; }
}
private class SourceQualityModel036
{
public SourceQuality036 Quality { get; set; }
public bool Proper { get; set; }
}
private class SourceQuality036
{
public int Id { get; set; }
}
}
}

@ -1,64 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
using System.Data;
using System.Linq;
using NzbDrone.Core.Qualities;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(37)]
public class add_configurable_qualities : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("Allowed").FromTable("QualityProfiles");
Alter.Column("Items").OnTable("QualityProfiles").AsString().NotNullable();
Create.TableForModel("QualityDefinitions")
.WithColumn("Quality").AsInt32().Unique()
.WithColumn("Title").AsString().Unique()
.WithColumn("Weight").AsInt32().Unique()
.WithColumn("MinSize").AsInt32()
.WithColumn("MaxSize").AsInt32();
Execute.WithConnection(ConvertQualities);
Delete.Table("QualitySizes");
}
private void ConvertQualities(IDbConnection conn, IDbTransaction tran)
{
// Convert QualitySizes to a more generic QualityDefinitions table.
using (IDbCommand qualitySizeCmd = conn.CreateCommand())
{
qualitySizeCmd.Transaction = tran;
qualitySizeCmd.CommandText = @"SELECT QualityId, MinSize, MaxSize FROM QualitySizes";
using (IDataReader qualitySizeReader = qualitySizeCmd.ExecuteReader())
{
while (qualitySizeReader.Read())
{
var qualityId = qualitySizeReader.GetInt32(0);
var minSize = qualitySizeReader.GetInt32(1);
var maxSize = qualitySizeReader.GetInt32(2);
var defaultConfig = Quality.DefaultQualityDefinitions.Single(p => (int)p.Quality == qualityId);
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "INSERT INTO QualityDefinitions (Quality, Title, Weight, MinSize, MaxSize) VALUES (?, ?, ?, ?, ?)";
updateCmd.AddParameter(qualityId);
updateCmd.AddParameter(defaultConfig.Title);
updateCmd.AddParameter(defaultConfig.Weight);
updateCmd.AddParameter(minSize);
updateCmd.AddParameter(maxSize);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(38)]
public class add_on_upgrade_to_notifications : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Notifications").AddColumn("OnUpgrade").AsBoolean().Nullable();
Execute.Sql("UPDATE Notifications SET OnUpgrade = OnDownload");
}
}
}

@ -1,28 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(39)]
public class add_metadata_tables : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.TableForModel("Metadata")
.WithColumn("Enable").AsBoolean().NotNullable()
.WithColumn("Name").AsString().NotNullable()
.WithColumn("Implementation").AsString().NotNullable()
.WithColumn("Settings").AsString().NotNullable()
.WithColumn("ConfigContract").AsString().NotNullable();
Create.TableForModel("MetadataFiles")
.WithColumn("SeriesId").AsInt32().NotNullable()
.WithColumn("Consumer").AsString().NotNullable()
.WithColumn("Type").AsInt32().NotNullable()
.WithColumn("RelativePath").AsString().NotNullable()
.WithColumn("LastUpdated").AsDateTime().NotNullable()
.WithColumn("SeasonNumber").AsInt32().Nullable()
.WithColumn("EpisodeFileId").AsInt32().Nullable();
}
}
}

@ -1,22 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(40)]
public class add_metadata_to_episodes_and_series : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Series")
.AddColumn("Actors").AsString().Nullable()
.AddColumn("Ratings").AsString().Nullable()
.AddColumn("Genres").AsString().Nullable()
.AddColumn("Certification").AsString().Nullable();
Alter.Table("Episodes")
.AddColumn("Ratings").AsString().Nullable()
.AddColumn("Images").AsString().Nullable();
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(41)]
public class fix_xbmc_season_images_metadata : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE MetadataFiles SET Type = 4 WHERE Consumer = 'XbmcMetadata' AND SeasonNumber IS NOT NULL");
}
}
}

@ -1,20 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(42)]
public class add_download_clients_table : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.TableForModel("DownloadClients")
.WithColumn("Enable").AsBoolean().NotNullable()
.WithColumn("Name").AsString().NotNullable()
.WithColumn("Implementation").AsString().NotNullable()
.WithColumn("Settings").AsString().NotNullable()
.WithColumn("ConfigContract").AsString().NotNullable()
.WithColumn("Protocol").AsInt32().NotNullable();
}
}
}

@ -1,197 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(43)]
public class convert_config_to_download_clients : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.WithConnection(ConvertToThingyProvder);
}
private void ConvertToThingyProvder(IDbConnection conn, IDbTransaction tran)
{
var config = new Dictionary<string, string>();
using (IDbCommand configCmd = conn.CreateCommand())
{
configCmd.Transaction = tran;
configCmd.CommandText = @"SELECT * FROM Config";
using (IDataReader configReader = configCmd.ExecuteReader())
{
var keyIndex = configReader.GetOrdinal("Key");
var valueIndex = configReader.GetOrdinal("Value");
while (configReader.Read())
{
var key = configReader.GetString(keyIndex);
var value = configReader.GetString(valueIndex);
config.Add(key.ToLowerInvariant(), value);
}
}
}
var client = GetConfigValue(config, "DownloadClient", "");
if (string.IsNullOrWhiteSpace(client))
{
return;
}
if (client.Equals("sabnzbd", StringComparison.InvariantCultureIgnoreCase))
{
var settings = new ClientSettingsForMigration
{
Host = GetConfigValue(config, "SabHost", "localhost"),
Port = GetConfigValue(config, "SabPort", 8080),
ApiKey = GetConfigValue(config, "SabApiKey", ""),
Username = GetConfigValue(config, "SabUsername", ""),
Password = GetConfigValue(config, "SabPassword", ""),
TvCategory = GetConfigValue(config, "SabTvCategory", "tv"),
RecentTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetRecentTvPriority", "Default")),
OlderTvPriority = GetSabnzbdPriority(GetConfigValue(config, "NzbgetOlderTvPriority", "Default")),
UseSsl = GetConfigValue(config, "SabUseSsl", false)
};
AddDownloadClient(conn, tran, "Sabnzbd", "Sabnzbd", settings.ToJson(), "SabnzbdSettings", 1);
}
else if (client.Equals("nzbget", StringComparison.InvariantCultureIgnoreCase))
{
var settings = new ClientSettingsForMigration
{
Host = GetConfigValue(config, "NzbGetHost", "localhost"),
Port = GetConfigValue(config, "NzbgetPort", 6789),
Username = GetConfigValue(config, "NzbgetUsername", "nzbget"),
Password = GetConfigValue(config, "NzbgetPassword", ""),
TvCategory = GetConfigValue(config, "NzbgetTvCategory", "tv"),
RecentTvPriority = GetNzbgetPriority(GetConfigValue(config, "NzbgetRecentTvPriority", "Normal")),
OlderTvPriority = GetNzbgetPriority(GetConfigValue(config, "NzbgetOlderTvPriority", "Normal")),
};
AddDownloadClient(conn, tran, "Nzbget", "Nzbget", settings.ToJson(), "NzbgetSettings", 1);
}
else if (client.Equals("pneumatic", StringComparison.InvariantCultureIgnoreCase))
{
var settings = new FolderSettingsForMigration
{
Folder = GetConfigValue(config, "PneumaticFolder", "")
};
AddDownloadClient(conn, tran, "Pneumatic", "Pneumatic", settings.ToJson(), "FolderSettings", 1);
}
else if (client.Equals("blackhole", StringComparison.InvariantCultureIgnoreCase))
{
var settings = new FolderSettingsForMigration
{
Folder = GetConfigValue(config, "BlackholeFolder", "")
};
AddDownloadClient(conn, tran, "Blackhole", "Blackhole", settings.ToJson(), "FolderSettings", 1);
}
DeleteOldConfigValues(conn, tran);
}
private T GetConfigValue<T>(Dictionary<string, string> config, string key, T defaultValue)
{
key = key.ToLowerInvariant();
if (config.ContainsKey(key))
{
return (T) Convert.ChangeType(config[key], typeof (T));
}
return defaultValue;
}
private void AddDownloadClient(IDbConnection conn, IDbTransaction tran, string name, string implementation, string settings,
string configContract, int protocol)
{
using (IDbCommand updateCmd = conn.CreateCommand())
{
var text = string.Format("INSERT INTO DownloadClients (Enable, Name, Implementation, Settings, ConfigContract, Protocol) VALUES (1, ?, ?, ?, ?, ?)");
updateCmd.AddParameter(name);
updateCmd.AddParameter(implementation);
updateCmd.AddParameter(settings);
updateCmd.AddParameter(configContract);
updateCmd.AddParameter(protocol);
updateCmd.Transaction = tran;
updateCmd.CommandText = text;
updateCmd.ExecuteNonQuery();
}
}
private void DeleteOldConfigValues(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand updateCmd = conn.CreateCommand())
{
var text = "DELETE FROM Config WHERE [KEY] IN ('nzbgetusername', 'nzbgetpassword', 'nzbgethost', 'nzbgetport', " +
"'nzbgettvcategory', 'nzbgetrecenttvpriority', 'nzbgetoldertvpriority', 'sabhost', 'sabport', " +
"'sabapikey', 'sabusername', 'sabpassword', 'sabtvcategory', 'sabrecenttvpriority', " +
"'saboldertvpriority', 'sabusessl', 'downloadclient', 'blackholefolder', 'pneumaticfolder')";
updateCmd.Transaction = tran;
updateCmd.CommandText = text;
updateCmd.ExecuteNonQuery();
}
}
private int GetSabnzbdPriority(string priority)
{
return (int)Enum.Parse(typeof(SabnzbdPriorityForMigration), priority, true);
}
private int GetNzbgetPriority(string priority)
{
return (int)Enum.Parse(typeof(NzbGetPriorityForMigration), priority, true);
}
private class ClientSettingsForMigration
{
public string Host { get; set; }
public int Port { get; set; }
public string ApiKey { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string TvCategory { get; set; }
public int RecentTvPriority { get; set; }
public int OlderTvPriority { get; set; }
public bool UseSsl { get; set; }
}
private class FolderSettingsForMigration
{
public string Folder { get; set; }
}
private enum SabnzbdPriorityForMigration
{
Default = -100,
Paused = -2,
Low = -1,
Normal = 0,
High = 1,
Force = 2
}
private enum NzbGetPriorityForMigration
{
VeryLow = -100,
Low = -50,
Normal = 0,
High = 50,
VeryHigh = 100
}
}
}

@ -1,27 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(44)]
public class fix_xbmc_episode_metadata : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
//Convert Episode Metadata to proper type
Execute.Sql("UPDATE MetadataFiles " +
"SET Type = 2 " +
"WHERE Consumer = 'XbmcMetadata' " +
"AND EpisodeFileId IS NOT NULL " +
"AND Type = 4 " +
"AND RelativePath LIKE '%.nfo'");
//Convert Episode Images to proper type
Execute.Sql("UPDATE MetadataFiles " +
"SET Type = 5 " +
"WHERE Consumer = 'XbmcMetadata' " +
"AND EpisodeFileId IS NOT NULL " +
"AND Type = 4");
}
}
}

@ -1,26 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(45)]
public class add_indexes : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.Index().OnTable("Blacklist").OnColumn("SeriesId");
Create.Index().OnTable("EpisodeFiles").OnColumn("SeriesId");
Create.Index().OnTable("Episodes").OnColumn("EpisodeFileId");
Create.Index().OnTable("Episodes").OnColumn("SeriesId");
Create.Index().OnTable("History").OnColumn("EpisodeId");
Create.Index().OnTable("History").OnColumn("Date");
Create.Index().OnTable("Series").OnColumn("Path");
Create.Index().OnTable("Series").OnColumn("CleanTitle");
Create.Index().OnTable("Series").OnColumn("TvRageId");
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(46)]
public class fix_nzb_su_url : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE Indexers SET Settings = replace(Settings, '//nzb.su', '//api.nzb.su')" +
"WHERE Implementation = 'Newznab'" +
"AND Settings LIKE '%//nzb.su%'");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(47)]
public class add_temporary_blacklist_columns : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Blacklist").AddColumn("PublishedDate").AsDateTime().Nullable();
}
}
}

@ -1,14 +0,0 @@
using NzbDrone.Core.Datastore.Migration.Framework;
using FluentMigrator;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(48)]
public class add_title_to_scenemappings : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("SceneMappings").AddColumn("Title").AsString().Nullable();
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(49)]
public class fix_dognzb_url : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE Indexers SET Settings = replace(Settings, '//dognzb.cr', '//api.dognzb.cr')" +
"WHERE Implementation = 'Newznab'" +
"AND Settings LIKE '%//dognzb.cr%'");
}
}
}

@ -1,14 +0,0 @@
using NzbDrone.Core.Datastore.Migration.Framework;
using FluentMigrator;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(50)]
public class add_hash_to_metadata_files : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("MetadataFiles").AddColumn("Hash").AsString().Nullable();
}
}
}

@ -1,243 +0,0 @@
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using FluentMigrator;
using Newtonsoft.Json;
using NzbDrone.Common.Extensions;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration.Framework;
using System.IO;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(51)]
public class download_client_import : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.WithConnection(EnableCompletedDownloadHandlingForNewUsers);
Execute.WithConnection(ConvertFolderSettings);
Execute.WithConnection(AssociateImportedHistoryItems);
}
private void EnableCompletedDownloadHandlingForNewUsers(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.Transaction = tran;
cmd.CommandText = @"SELECT Value FROM Config WHERE Key = 'downloadedepisodesfolder'";
var result = cmd.ExecuteScalar();
if (result == null)
{
cmd.CommandText = @"INSERT INTO Config (Key, Value) VALUES ('enablecompleteddownloadhandling', 'True')";
cmd.ExecuteNonQuery();
}
}
}
private void ConvertFolderSettings(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand downloadClientsCmd = conn.CreateCommand())
{
downloadClientsCmd.Transaction = tran;
downloadClientsCmd.CommandText = @"SELECT Value FROM Config WHERE Key = 'downloadedepisodesfolder'";
var downloadedEpisodesFolder = downloadClientsCmd.ExecuteScalar() as string;
downloadClientsCmd.Transaction = tran;
downloadClientsCmd.CommandText = @"SELECT Id, Implementation, Settings, ConfigContract FROM DownloadClients WHERE ConfigContract = 'FolderSettings'";
using (IDataReader downloadClientReader = downloadClientsCmd.ExecuteReader())
{
while (downloadClientReader.Read())
{
var id = downloadClientReader.GetInt32(0);
var implementation = downloadClientReader.GetString(1);
var settings = downloadClientReader.GetString(2);
var configContract = downloadClientReader.GetString(3);
var settingsJson = JsonConvert.DeserializeObject(settings) as Newtonsoft.Json.Linq.JObject;
if (implementation == "Blackhole")
{
var newSettings = new
{
NzbFolder = settingsJson.Value<string>("folder"),
WatchFolder = downloadedEpisodesFolder
}.ToJson();
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE DownloadClients SET Implementation = ?, Settings = ?, ConfigContract = ? WHERE Id = ?";
updateCmd.AddParameter("UsenetBlackhole");
updateCmd.AddParameter(newSettings);
updateCmd.AddParameter("UsenetBlackholeSettings");
updateCmd.AddParameter(id);
updateCmd.ExecuteNonQuery();
}
}
else if (implementation == "Pneumatic")
{
var newSettings = new
{
NzbFolder = settingsJson.Value<string>("folder")
}.ToJson();
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE DownloadClients SET Settings = ?, ConfigContract = ? WHERE Id = ?";
updateCmd.AddParameter(newSettings);
updateCmd.AddParameter("PneumaticSettings");
updateCmd.AddParameter(id);
updateCmd.ExecuteNonQuery();
}
}
else
{
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "DELETE FROM DownloadClients WHERE Id = ?";
updateCmd.AddParameter(id);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
}
private sealed class MigrationHistoryItem
{
public int Id { get; set; }
public int EpisodeId { get; set; }
public int SeriesId { get; set; }
public string SourceTitle { get; set; }
public DateTime Date { get; set; }
public Dictionary<string, string> Data { get; set; }
public MigrationHistoryEventType EventType { get; set; }
}
private enum MigrationHistoryEventType
{
Unknown = 0,
Grabbed = 1,
SeriesFolderImported = 2,
DownloadFolderImported = 3,
DownloadFailed = 4
}
private void AssociateImportedHistoryItems(IDbConnection conn, IDbTransaction tran)
{
var historyItems = new List<MigrationHistoryItem>();
using (IDbCommand historyCmd = conn.CreateCommand())
{
historyCmd.Transaction = tran;
historyCmd.CommandText = @"SELECT Id, EpisodeId, SeriesId, SourceTitle, Date, Data, EventType FROM History WHERE EventType NOT NULL";
using (IDataReader historyRead = historyCmd.ExecuteReader())
{
while (historyRead.Read())
{
historyItems.Add(new MigrationHistoryItem
{
Id = historyRead.GetInt32(0),
EpisodeId = historyRead.GetInt32(1),
SeriesId = historyRead.GetInt32(2),
SourceTitle = historyRead.GetString(3),
Date = historyRead.GetDateTime(4),
Data = Json.Deserialize<Dictionary<string, string>>(historyRead.GetString(5)),
EventType = (MigrationHistoryEventType)historyRead.GetInt32(6)
});
}
}
}
var numHistoryItemsNotAssociated = historyItems.Count(v => v.EventType == MigrationHistoryEventType.DownloadFolderImported &&
v.Data.GetValueOrDefault("downloadClientId") == null);
if (numHistoryItemsNotAssociated == 0)
{
return;
}
var historyItemsToAssociate = new Dictionary<MigrationHistoryItem, MigrationHistoryItem>();
var historyItemsLookup = historyItems.ToLookup(v => v.EpisodeId);
foreach (var historyItemGroup in historyItemsLookup)
{
var list = historyItemGroup.ToList();
for (int i = 0; i < list.Count - 1; i++)
{
var grabbedEvent = list[i];
if (grabbedEvent.EventType != MigrationHistoryEventType.Grabbed) continue;
if (grabbedEvent.Data.GetValueOrDefault("downloadClient") == null || grabbedEvent.Data.GetValueOrDefault("downloadClientId") == null) continue;
// Check if it is already associated with a failed/imported event.
int j;
for (j = i + 1; j < list.Count;j++)
{
if (list[j].EventType != MigrationHistoryEventType.DownloadFolderImported &&
list[j].EventType != MigrationHistoryEventType.DownloadFailed)
{
continue;
}
if (list[j].Data.ContainsKey("downloadClient") && list[j].Data["downloadClient"] == grabbedEvent.Data["downloadClient"] &&
list[j].Data.ContainsKey("downloadClientId") && list[j].Data["downloadClientId"] == grabbedEvent.Data["downloadClientId"])
{
break;
}
}
if (j != list.Count)
{
list.RemoveAt(j);
list.RemoveAt(i--);
continue;
}
var importedEvent = list[i + 1];
if (importedEvent.EventType != MigrationHistoryEventType.DownloadFolderImported) continue;
var droppedPath = importedEvent.Data.GetValueOrDefault("droppedPath");
if (droppedPath != null && new FileInfo(droppedPath).Directory.Name == grabbedEvent.SourceTitle)
{
historyItemsToAssociate[importedEvent] = grabbedEvent;
list.RemoveAt(i + 1);
list.RemoveAt(i--);
}
}
}
foreach (var pair in historyItemsToAssociate)
{
using (IDbCommand updateHistoryCmd = conn.CreateCommand())
{
pair.Key.Data["downloadClient"] = pair.Value.Data["downloadClient"];
pair.Key.Data["downloadClientId"] = pair.Value.Data["downloadClientId"];
updateHistoryCmd.Transaction = tran;
updateHistoryCmd.CommandText = "UPDATE History SET Data = ? WHERE Id = ?";
updateHistoryCmd.AddParameter(pair.Key.Data.ToJson());
updateHistoryCmd.AddParameter(pair.Key.Id);
updateHistoryCmd.ExecuteNonQuery();
}
}
_logger.Info("Updated old History items. {0}/{1} old ImportedEvents were associated with GrabbedEvents.", historyItemsToAssociate.Count, numHistoryItemsNotAssociated);
}
}
}

@ -1,20 +0,0 @@
using NzbDrone.Core.Datastore.Migration.Framework;
using FluentMigrator;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(52)]
public class add_columns_for_anime : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
//Support XEM names
Alter.Table("SceneMappings").AddColumn("Type").AsString().Nullable();
Execute.Sql("DELETE FROM SceneMappings");
//Add AnimeEpisodeFormat (set to Stardard Episode format for now)
Alter.Table("NamingConfig").AddColumn("AnimeEpisodeFormat").AsString().Nullable();
Execute.Sql("UPDATE NamingConfig SET AnimeEpisodeFormat = StandardEpisodeFormat");
}
}
}

@ -1,46 +0,0 @@
using System.Data;
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(53)]
public class add_series_sorttitle : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.Column("SortTitle").OnTable("Series").AsString().Nullable();
Execute.WithConnection(SetSortTitles);
}
private void SetSortTitles(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand getSeriesCmd = conn.CreateCommand())
{
getSeriesCmd.Transaction = tran;
getSeriesCmd.CommandText = @"SELECT Id, Title FROM Series";
using (IDataReader seriesReader = getSeriesCmd.ExecuteReader())
{
while (seriesReader.Read())
{
var id = seriesReader.GetInt32(0);
var title = seriesReader.GetString(1);
var sortTitle = Parser.Parser.NormalizeTitle(title).ToLower();
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE Series SET SortTitle = ? WHERE Id = ?";
updateCmd.AddParameter(sortTitle);
updateCmd.AddParameter(id);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
}
}

@ -1,31 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(54)]
public class rename_profiles : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Rename.Table("QualityProfiles").To("Profiles");
Alter.Table("Profiles").AddColumn("Language").AsInt32().Nullable();
Alter.Table("Profiles").AddColumn("GrabDelay").AsInt32().Nullable();
Alter.Table("Profiles").AddColumn("GrabDelayMode").AsInt32().Nullable();
Execute.Sql("UPDATE Profiles SET Language = 1, GrabDelay = 0, GrabDelayMode = 0");
//Rename QualityProfileId in Series
Alter.Table("Series").AddColumn("ProfileId").AsInt32().Nullable();
Execute.Sql("UPDATE Series SET ProfileId = QualityProfileId");
//Add HeldReleases
Create.TableForModel("PendingReleases")
.WithColumn("SeriesId").AsInt32()
.WithColumn("Title").AsString()
.WithColumn("Added").AsDateTime()
.WithColumn("ParsedEpisodeInfo").AsString()
.WithColumn("Release").AsString();
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(55)]
public class drop_old_profile_columns : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("QualityProfileId").FromTable("Series");
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(56)]
public class add_mediainfo_to_episodefile : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("EpisodeFiles").AddColumn("MediaInfo").AsString().Nullable();
}
}
}

@ -1,48 +0,0 @@
using System.Data;
using System.IO;
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(57)]
public class convert_episode_file_path_to_relative : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.Column("RelativePath").OnTable("EpisodeFiles").AsString().Nullable();
//TODO: Add unique contraint for series ID and Relative Path
//TODO: Warn if multiple series share the same path
Execute.WithConnection(UpdateRelativePaths);
}
private void UpdateRelativePaths(IDbConnection conn, IDbTransaction tran)
{
using (IDbCommand getSeriesCmd = conn.CreateCommand())
{
getSeriesCmd.Transaction = tran;
getSeriesCmd.CommandText = @"SELECT Id, Path FROM Series";
using (IDataReader seriesReader = getSeriesCmd.ExecuteReader())
{
while (seriesReader.Read())
{
var seriesId = seriesReader.GetInt32(0);
var seriesPath = seriesReader.GetString(1) + Path.DirectorySeparatorChar;
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE EpisodeFiles SET RelativePath = REPLACE(Path, ?, '') WHERE SeriesId = ?";
updateCmd.AddParameter(seriesPath);
updateCmd.AddParameter(seriesId);
updateCmd.ExecuteNonQuery();
}
}
}
}
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(58)]
public class drop_episode_file_path : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("Path").FromTable("EpisodeFiles");
}
}
}

@ -1,19 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(59)]
public class add_enable_options_to_indexers : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Alter.Table("Indexers")
.AddColumn("EnableRss").AsBoolean().Nullable()
.AddColumn("EnableSearch").AsBoolean().Nullable();
Execute.Sql("UPDATE Indexers SET EnableRss = Enable, EnableSearch = Enable");
Execute.Sql("UPDATE Indexers SET EnableSearch = 0 WHERE Implementation = 'Wombles'");
}
}
}

@ -1,15 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(60)]
public class remove_enable_from_indexers : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Delete.Column("Enable").FromTable("Indexers");
Delete.Column("Protocol").FromTable("DownloadClients");
}
}
}

@ -1,22 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(61)]
public class clear_bad_scene_names : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE [EpisodeFiles] " +
"SET ReleaseGroup = NULL , SceneName = NULL " +
"WHERE " +
" ReleaseGroup IS NULL " +
" OR SceneName IS NULL " +
" OR ReleaseGroup =='DRONE' " +
" OR LENGTH(SceneName) <10 " +
" OR LENGTH(ReleaseGroup) > 20 " +
" OR SceneName NOT LIKE '%.%'");
}
}
}

@ -1,83 +0,0 @@
using System.Collections.Generic;
using System.Data;
using FluentMigrator;
using NzbDrone.Common.Serializer;
using NzbDrone.Core.Datastore.Migration.Framework;
using NzbDrone.Core.Qualities;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(62)]
public class convert_quality_models : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.WithConnection(ConvertQualityModels);
}
private void ConvertQualityModels(IDbConnection conn, IDbTransaction tran)
{
ConvertQualityModelsOnTable(conn, tran, "EpisodeFiles");
ConvertQualityModelsOnTable(conn, tran, "Blacklist");
ConvertQualityModelsOnTable(conn, tran, "History");
}
private void ConvertQualityModelsOnTable(IDbConnection conn, IDbTransaction tran, string tableName)
{
var qualitiesToUpdate = new Dictionary<string, string>();
using (IDbCommand qualityModelCmd = conn.CreateCommand())
{
qualityModelCmd.Transaction = tran;
qualityModelCmd.CommandText = @"SELECT Distinct Quality FROM " + tableName;
using (IDataReader qualityModelReader = qualityModelCmd.ExecuteReader())
{
while (qualityModelReader.Read())
{
var qualityJson = qualityModelReader.GetString(0);
LegacyQualityModel062 quality;
if (!Json.TryDeserialize<LegacyQualityModel062>(qualityJson, out quality))
{
continue;
}
var newQualityModel = new QualityModel062 { Quality = quality.Quality, Revision = new Revision() };
if (quality.Proper)
newQualityModel.Revision.Version = 2;
var newQualityJson = newQualityModel.ToJson();
qualitiesToUpdate.Add(qualityJson, newQualityJson);
}
}
}
foreach (var quality in qualitiesToUpdate)
{
using (IDbCommand updateCmd = conn.CreateCommand())
{
updateCmd.Transaction = tran;
updateCmd.CommandText = "UPDATE " + tableName + " SET Quality = ? WHERE Quality = ?";
updateCmd.AddParameter(quality.Value);
updateCmd.AddParameter(quality.Key);
updateCmd.ExecuteNonQuery();
}
}
}
private class LegacyQualityModel062
{
public int Quality { get; set; }
public bool Proper { get; set; }
}
private class QualityModel062
{
public int Quality { get; set; }
public Revision Revision { get; set; }
}
}
}

@ -1,17 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(63)]
public class add_remotepathmappings : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.TableForModel("RemotePathMappings")
.WithColumn("Host").AsString()
.WithColumn("RemotePath").AsString()
.WithColumn("LocalPath").AsString();
}
}
}

@ -1,14 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(64)]
public class remove_method_from_logs : NzbDroneMigrationBase
{
protected override void LogDbUpgrade()
{
Delete.Column("Method").FromTable("Logs");
}
}
}

@ -1,16 +0,0 @@
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(65)]
public class make_scene_numbering_nullable : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Execute.Sql("UPDATE Episodes SET AbsoluteEpisodeNumber = NULL WHERE AbsoluteEpisodeNumber = 0");
Execute.Sql("UPDATE Episodes SET SceneAbsoluteEpisodeNumber = NULL WHERE SceneAbsoluteEpisodeNumber = 0");
Execute.Sql("UPDATE Episodes SET SceneSeasonNumber = NULL, SceneEpisodeNumber = NULL WHERE SceneSeasonNumber = 0 AND SceneEpisodeNumber = 0");
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save