Skip to content

Commit 09c2657

Browse files
committed
Added trakt authentication.
1 parent 67a2de0 commit 09c2657

11 files changed

Lines changed: 288 additions & 24 deletions
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
using System;
2+
using System.Linq;
3+
using System.Text;
4+
using System.Threading.Tasks;
5+
using Microsoft.AspNetCore.Mvc;
6+
using RadarrAPI.Database;
7+
using RadarrAPI.Database.Models;
8+
using TraktApiSharp;
9+
10+
namespace RadarrAPI.Controllers
11+
{
12+
[Route("v1/[controller]")]
13+
public class TraktController : Controller
14+
{
15+
private readonly DatabaseContext _database;
16+
17+
private readonly TraktClient _trakt;
18+
19+
public TraktController(DatabaseContext database, TraktClient trakt)
20+
{
21+
_database = database;
22+
_trakt = trakt;
23+
}
24+
25+
[Route("redirect")]
26+
[HttpGet]
27+
public async Task<IActionResult> RedirectToTrakt([FromQuery(Name = "target")] string target)
28+
{
29+
var validTarget = Uri.TryCreate(target, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == "http" || uriResult.Scheme == "https");
30+
if (!validTarget)
31+
{
32+
return BadRequest("Invalid target specified.");
33+
}
34+
35+
var traktEntity = new TraktEntity
36+
{
37+
State = Guid.NewGuid(),
38+
Target = target,
39+
CreatedAt = DateTime.UtcNow
40+
};
41+
42+
_database.Add(traktEntity);
43+
await _database.SaveChangesAsync();
44+
45+
return Redirect(_trakt.OAuth.CreateAuthorizationUrl(_trakt.ClientId, GetRedirectUri(), traktEntity.State.ToString()));
46+
}
47+
48+
[Route("callback")]
49+
[HttpGet]
50+
public async Task<IActionResult> TraktCallback([FromQuery(Name = "code")] string code, [FromQuery(Name = "state")] string stateStr)
51+
{
52+
if (!Guid.TryParse(stateStr, out Guid state))
53+
{
54+
return BadRequest("Invalid state specified.");
55+
}
56+
57+
var traktEntity = _database.TraktEntities.FirstOrDefault(x => x.State.Equals(state));
58+
if (traktEntity == null)
59+
{
60+
return BadRequest("Unknown state specified.");
61+
}
62+
63+
_database.Remove(traktEntity);
64+
await _database.SaveChangesAsync();
65+
66+
var traktAuth = await _trakt.OAuth.GetAuthorizationAsync(code, _trakt.ClientId, _trakt.ClientSecret, GetRedirectUri());
67+
if (!traktAuth.IsValid)
68+
{
69+
return BadRequest("Received trakt token was invalid.");
70+
}
71+
72+
return Redirect($"{traktEntity.Target}?oauth={traktAuth.AccessToken}&refresh={traktAuth.RefreshToken}");
73+
}
74+
75+
private string GetRedirectUri()
76+
{
77+
var redirectUri = new StringBuilder();
78+
redirectUri.Append(HttpContext.Request.IsHttps ? "https://" : "http://");
79+
redirectUri.Append(HttpContext.Request.Host);
80+
redirectUri.Append("/v1/trakt/callback");
81+
82+
return redirectUri.ToString();
83+
}
84+
}
85+
}

RadarrAPI/Database/DatabaseContext.cs

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,34 @@ public DatabaseContext(DbContextOptions options) : base(options)
1212
}
1313

1414
public DbSet<UpdateEntity> UpdateEntities { get; set; }
15+
1516
public DbSet<UpdateFileEntity> UpdateFileEntities { get; set; }
1617

18+
public DbSet<TraktEntity> TraktEntities { get; set; }
19+
1720
protected override void OnModelCreating(ModelBuilder modelBuilder)
1821
{
19-
//// Define keys
20-
modelBuilder.Entity<UpdateEntity>().HasKey(k => k.UpdateEntityId);
21-
modelBuilder.Entity<UpdateFileEntity>().HasKey(k => new { k.UpdateEntityId, k.OperatingSystem });
22-
23-
//// Define relations
24-
// An Update has many UpdateFiles
25-
modelBuilder.Entity<UpdateEntity>()
26-
.HasMany(u => u.UpdateFiles)
27-
.WithOne(u => u.Update)
28-
.HasForeignKey(u => u.UpdateEntityId)
29-
.OnDelete(DeleteBehavior.Cascade)
30-
.IsRequired();
22+
modelBuilder.Entity<UpdateEntity>(builder =>
23+
{
24+
builder.HasKey(k => k.UpdateEntityId);
25+
26+
builder.HasMany(u => u.UpdateFiles)
27+
.WithOne(u => u.Update)
28+
.HasForeignKey(u => u.UpdateEntityId)
29+
.OnDelete(DeleteBehavior.Cascade)
30+
.IsRequired();
31+
});
32+
33+
modelBuilder.Entity<UpdateFileEntity>(builder =>
34+
{
35+
builder.HasKey(k => new {k.UpdateEntityId, k.OperatingSystem});
36+
});
37+
38+
modelBuilder.Entity<TraktEntity>(builder =>
39+
{
40+
builder.HasKey(k => k.Id);
41+
builder.HasIndex(k => k.State);
42+
});
3143
}
3244
}
3345
}

RadarrAPI/Database/Migrations/20170113010120_Initial.cs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,12 @@ protected override void Up(MigrationBuilder migrationBuilder)
1111
name: "Updates",
1212
columns: table => new
1313
{
14-
UpdateEntityId = table.Column<int>(nullable: false)
15-
.Annotation("MySql:ValueGeneratedOnAdd", true),
16-
Branch = table.Column<int>(nullable: false),
17-
Fixed = table.Column<string>(nullable: true),
18-
New = table.Column<string>(nullable: true),
14+
UpdateEntityId = table.Column<int>(nullable: false).Annotation("MySql:ValueGeneratedOnAdd", true),
15+
Version = table.Column<string>(nullable: true),
1916
ReleaseDate = table.Column<DateTime>(nullable: false),
20-
Version = table.Column<string>(nullable: true)
17+
New = table.Column<string>(nullable: true),
18+
Fixed = table.Column<string>(nullable: true),
19+
Branch = table.Column<int>(nullable: false)
2120
},
2221
constraints: table =>
2322
{
@@ -31,8 +30,8 @@ protected override void Up(MigrationBuilder migrationBuilder)
3130
UpdateEntityId = table.Column<int>(nullable: false),
3231
OperatingSystem = table.Column<int>(nullable: false),
3332
Filename = table.Column<string>(nullable: true),
34-
Hash = table.Column<string>(nullable: true),
35-
Url = table.Column<string>(nullable: true)
33+
Url = table.Column<string>(nullable: true),
34+
Hash = table.Column<string>(nullable: true)
3635
},
3736
constraints: table =>
3837
{

RadarrAPI/Database/Migrations/20170304204209_AddTraktEntity.Designer.cs

Lines changed: 86 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using Microsoft.EntityFrameworkCore.Migrations;
4+
5+
namespace RadarrAPI.Database.Migrations
6+
{
7+
public partial class AddTraktEntity : Migration
8+
{
9+
protected override void Up(MigrationBuilder migrationBuilder)
10+
{
11+
migrationBuilder.CreateTable(
12+
name: "Trakt",
13+
columns: table => new
14+
{
15+
Id = table.Column<int>(nullable: false).Annotation("MySql:ValueGeneratedOnAdd", true),
16+
State = table.Column<Guid>(nullable: false),
17+
Target = table.Column<string>(nullable: true),
18+
CreatedAt = table.Column<DateTime>(nullable: false),
19+
},
20+
constraints: table =>
21+
{
22+
table.PrimaryKey("PK_Trakt", x => x.Id);
23+
});
24+
25+
migrationBuilder.CreateIndex(
26+
name: "IX_Trakt_State",
27+
table: "Trakt",
28+
column: "State");
29+
}
30+
31+
protected override void Down(MigrationBuilder migrationBuilder)
32+
{
33+
migrationBuilder.DropTable(
34+
name: "Trakt");
35+
}
36+
}
37+
}

RadarrAPI/Database/Migrations/DatabaseContextModelSnapshot.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
using Microsoft.EntityFrameworkCore;
33
using Microsoft.EntityFrameworkCore.Infrastructure;
44
using Microsoft.EntityFrameworkCore.Metadata;
5+
using Microsoft.EntityFrameworkCore.Migrations;
6+
using RadarrAPI.Database;
7+
using RadarrAPI.Update;
58

69
namespace RadarrAPI.Database.Migrations
710
{
@@ -13,6 +16,24 @@ protected override void BuildModel(ModelBuilder modelBuilder)
1316
modelBuilder
1417
.HasAnnotation("ProductVersion", "1.1.0-rtm-22752");
1518

19+
modelBuilder.Entity("RadarrAPI.Database.Models.TraktEntity", b =>
20+
{
21+
b.Property<int>("Id")
22+
.ValueGeneratedOnAdd();
23+
24+
b.Property<DateTime>("CreatedAt");
25+
26+
b.Property<Guid>("State");
27+
28+
b.Property<string>("Target");
29+
30+
b.HasKey("Id");
31+
32+
b.HasIndex("State");
33+
34+
b.ToTable("Trakt");
35+
});
36+
1637
modelBuilder.Entity("RadarrAPI.Database.Models.UpdateEntity", b =>
1738
{
1839
b.Property<int>("UpdateEntityId")
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System;
2+
using System.ComponentModel.DataAnnotations.Schema;
3+
4+
namespace RadarrAPI.Database.Models
5+
{
6+
[Table("Trakt")]
7+
public class TraktEntity
8+
{
9+
public int Id { get; set; }
10+
11+
public Guid State { get; set; }
12+
13+
public string Target { get; set; }
14+
15+
public DateTime CreatedAt { get; set; }
16+
}
17+
}

RadarrAPI/Properties/launchSettings.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@
1010
"profiles": {
1111
"IIS Express": {
1212
"commandName": "IISExpress",
13-
"launchBrowser": true,
13+
"launchBrowser": false,
1414
"launchUrl": "api/values",
1515
"environmentVariables": {
1616
"ASPNETCORE_ENVIRONMENT": "Development"
1717
}
1818
},
1919
"RadarrAPI": {
2020
"commandName": "Project",
21-
"launchBrowser": true,
21+
"launchBrowser": false,
2222
"launchUrl": "http://localhost:53442/v1/update/nightly/changes?version=0.2.0.0&os=windows",
2323
"environmentVariables": {
2424
"ASPNETCORE_ENVIRONMENT": "Development"

RadarrAPI/RadarrAPI.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<PackageReference Include="Octokit" Version="0.24.1-alpha0001" />
1515
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="1.1.0" />
1616
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql.Design" Version="1.1.0" />
17+
<PackageReference Include="TraktApiSharp" Version="1.0.0-alpha1" />
1718
</ItemGroup>
1819
<ItemGroup>
1920
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />

RadarrAPI/Startup.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using Microsoft.EntityFrameworkCore;
1313
using NLog.Web;
1414
using StatsdClient;
15+
using TraktApiSharp;
1516

1617
namespace RadarrAPI
1718
{
@@ -40,6 +41,7 @@ public void ConfigureServices(IServiceCollection services)
4041
services.Configure<Config>(Configuration);
4142
services.AddSingleton(new GitHubClient(new ProductHeaderValue("RadarrAPI")));
4243
services.AddSingleton<ReleaseService>();
44+
services.AddSingleton(new TraktClient(Configuration.GetSection("Trakt")["ClientId"], Configuration.GetSection("Trakt")["ClientSecret"]));
4345
services.AddMvc();
4446

4547
// Add database

0 commit comments

Comments
 (0)