Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions App/AL/Controller/Project/Post/ProjectCrudController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using App.AL.Validation.Permission;
using App.DL.Enum;
using App.DL.Model.Project.Post;
using App.DL.Repository.Project;
using App.DL.Repository.User;
using App.PL.Transformer.Project.Post;
using Micron.AL.Validation.Basic;
using Micron.AL.Validation.Db;
using Micron.DL.Middleware;
using Micron.DL.Middleware.Auth;
using Micron.DL.Module.Controller;
using Micron.DL.Module.Http;
using Micron.DL.Module.Validator;
using Nancy;

namespace App.AL.Controller.Project.Post {
public class ProjectCrudController : BaseController {
protected override IMiddleware[] Middleware() => new IMiddleware[] {
new JwtMiddleware(),
};

public ProjectCrudController() {
Post("/api/v1/project/post/new", _ => {
var me = UserRepository.Find(CurrentRequest.UserId);
var project = ProjectRepository.FindByGuid(GetRequestStr("project_guid"));
if (project == null) return HttpResponse.Error(HttpStatusCode.NotFound, "Project not found");

var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
new ShouldHaveParameters(new[] {"project_guid", "title", "content"}),
new ExistsInTable("project_guid", "projects", "guid"),
new HasPermission(me, project.id, EntityType.Project),
}, true);
if (errors.Count > 0) return HttpResponse.Errors(errors);

var post = ProjectPost.Create(project, "some title", "some content");

return HttpResponse.Item(
"post", new ProjectPostTransformer().Transform(post), HttpStatusCode.Created
);
});

Delete("/api/v1/project/post/delete", _ => {
var post = ProjectPost.FindBy("guid", GetRequestStr("post_guid"));
if (post == null) return HttpResponse.Error(HttpStatusCode.NotFound, "Post not found");

var me = UserRepository.Find(CurrentRequest.UserId);

var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
new ShouldHaveParameters(new[] {"post_guid"}),
new HasPermission(me, post.project_id, EntityType.Project),
}, true);
if (errors.Count > 0) return HttpResponse.Errors(errors);

post.Delete();

return HttpResponse.Item("post", new ProjectPostTransformer().Transform(post));
});
}
}
}
26 changes: 26 additions & 0 deletions App/AL/Controller/Project/Post/ProjectPostsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using App.DL.Repository.Project;
using App.PL.Transformer.Project.Post;
using Micron.AL.Validation.Db;
using Micron.DL.Middleware;
using Micron.DL.Module.Controller;
using Micron.DL.Module.Http;
using Micron.DL.Module.Validator;

namespace App.AL.Controller.Project.Post {
public class ProjectPostsController : BaseController {
protected override IMiddleware[] Middleware() => new IMiddleware[] {};

public ProjectPostsController() {
Get("/api/v1/project/posts/get", _ => {
var errors = ValidationProcessor.Process(Request, new IValidatorRule[] {
new ExistsInTable("project_guid", "projects", "guid"),
});
if (errors.Count > 0) return HttpResponse.Errors(errors);

var project = ProjectRepository.FindByGuid(GetRequestStr("project_guid"));

return HttpResponse.Item("posts", new ProjectPostTransformer().Many(project.Posts()));
});
}
}
}
20 changes: 20 additions & 0 deletions App/AL/Middleware/Schedule/ScheduleAuth.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Micron.DL.Middleware;
using Micron.DL.Module.Config;
using Micron.DL.Module.Http;
using Nancy;

namespace App.AL.Middleware.Schedule {
public class ScheduleAuth : IMiddleware {
public ProcessedRequest Process(ProcessedRequest request) {
var scheduleToken = AppConfig.GetConfiguration("auth:schedule:token");

if (
string.IsNullOrEmpty(scheduleToken) || scheduleToken != request.GetRequestStr("schedule_token")
) {
request.AddError(new HttpError(HttpStatusCode.Unauthorized, "Schedule token is invalid"));
}

return request;
}
}
}
64 changes: 64 additions & 0 deletions App/AL/Schedule/Project/Post/SyncReleases.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using App.AL.Middleware.Schedule;
using App.DL.Enum;
using App.DL.Model.Project.Post;
using App.DL.Model.Repo;
using Micron.DL.Middleware;
using Micron.DL.Module.Controller;
using Micron.DL.Module.Http;
using Newtonsoft.Json.Linq;
using Octokit;
using Sentry;

namespace App.AL.Schedule.Project.Post {
public class SyncReleases : BaseController {
protected override IMiddleware[] Middleware() => new IMiddleware[] {
new ScheduleAuth(),
};

public SyncReleases() {
Post("/api/v1/schedule/project/sync_releases/start", _ => {
Task.Run(() => {
try {
var githubClient = new GitHubClient(new ProductHeaderValue("GitCom"));
githubClient.Credentials = new Credentials("b914880948da3cb7c00be78bcf8febe63ebe2861");

int pageIndex = 1;
var repos = Repo.Paginate(pageIndex);

while (repos.Length > 0) {
foreach (var repo in repos) {
if (repo.service_type != RepoServiceType.GitHub) continue;
var splitUrl = repo.repo_url.Split("/");
var releases = githubClient.Repository.Release
.GetAll(splitUrl[3], splitUrl[4]).Result;
releases = releases.OrderBy(x => x.Id).ToArray();

foreach (var release in releases) {
if (release.Body.Length < 100) continue;

var existingPost = ProjectPost.FindBy("origin_id", release.Id.ToString());
if (existingPost != null) continue;

var post = ProjectPost.Create(
repo.Project(), $"Released {release.Name}", release.Body
);
post.UpdateCol("origin_id", release.Id.ToString());
}
}

++pageIndex;
repos = Repo.Paginate(pageIndex);
}
}
catch (Exception e) {
SentrySdk.CaptureException(e);
}
});
return HttpResponse.Data(new JObject());
});
}
}
}
2 changes: 1 addition & 1 deletion App/AL/Utils/External/GitHub/GitHubRepositoriesUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public static class GitHubRepositoriesUtils {
public const string GithubApiHost = "https://api.github.com/";

private static GitHubClient GetClient() {
return new GitHubClient(new ProductHeaderValue("SupportHub"));
return new GitHubClient(new ProductHeaderValue("GitCom"));
}

public static ExternalRepo[] GetUserRepositories(User user) {
Expand Down
60 changes: 60 additions & 0 deletions App/DL/Model/Project/Post/ProjectPost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Linq;
using App.DL.Repository.Project;
using Dapper;

namespace App.DL.Model.Project.Post {
public class ProjectPost : Micron.DL.Model.Model {
public int id;

public string guid;

public int project_id;

public string title;

public string content;

public DateTime created_at;

public DateTime updated_at;

public static ProjectPost Find(int id)
=> Connection().Query<ProjectPost>(
"SELECT * FROM project_posts WHERE id = @id LIMIT 1", new {id}
).FirstOrDefault();

public static ProjectPost FindBy(string col, string val)
=> Connection().Query<ProjectPost>(
$"SELECT * FROM project_posts WHERE {col} = @val LIMIT 1", new {val}
).FirstOrDefault();

public static ProjectPost[] Get(Project project)
=> Connection().Query<ProjectPost>(
"SELECT * FROM project_posts WHERE project_id = @project_id", new {project_id = project.id}
).ToArray();

public static ProjectPost Create(Project project, string title, string content) {
return Find(ExecuteScalarInt(
@"INSERT INTO project_posts(guid, project_id, title, content, updated_at)
VALUES (@guid, @project_id, @title, @content, CURRENT_TIMESTAMP);
SELECT currval('project_posts_id_seq');"
, new {
guid = Guid.NewGuid().ToString(), project_id = project.id, title, content
}
));
}

public ProjectPost UpdateCol(string col, string val) {
ExecuteSql(
$"UPDATE project_posts SET {col} = @val, updated_at = CURRENT_TIMESTAMP WHERE id = @id",
new {val, id}
);
return this;
}

public void Delete() => ExecuteScalarInt("DELETE FROM project_posts WHERE id = @id", new {id});

public Project Project() => ProjectRepository.Find(project_id);
}
}
3 changes: 3 additions & 0 deletions App/DL/Model/Project/Project.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using App.DL.Repository.Project;
using App.DL.Repository.Product;
using App.DL.Model.Product;
using App.DL.Model.Project.Post;

// ReSharper disable InconsistentNaming

Expand Down Expand Up @@ -136,6 +137,8 @@ public bool InLibrary(UserModel user)
public int StarsCount() =>
ExecuteScalarInt("SELECT COUNT(*) FROM user_projects_library WHERE project_id = @id", new {id});

public ProjectPost[] Posts() => ProjectPost.Get(this);

public void Delete() => ExecuteScalarInt("DELETE FROM projects WHERE id = @id", new {id});
}
}
6 changes: 6 additions & 0 deletions App/DL/Model/Repo/Repo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ public static Repo Find(string originId, RepoServiceType type)
new {origin_id = originId}
).FirstOrDefault();

public static Repo[] Paginate(int page, int size = 20)
=> Connection().Query<Repo>(
"SELECT * FROM repositories OFFSET @offset LIMIT @size",
new {offset = ((page-1) * size), size}
).ToArray();

public static int Create(
UserModel creator, string title, string repoUrl, RepoServiceType serviceType, string originId = ""
) {
Expand Down
20 changes: 20 additions & 0 deletions App/PL/Transformer/Project/Post/ProjectPostTransformer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using App.DL.Model.Project.Post;
using Micron.PL.Transformer;
using Newtonsoft.Json.Linq;

namespace App.PL.Transformer.Project.Post {
public class ProjectPostTransformer : BaseTransformer {
public override JObject Transform(object obj) {
var item = (ProjectPost) obj;
var result = new JObject {
["guid"] = item.guid,
["title"] = item.title,
["project_guid"] = item.Project().guid,
["content"] = item.content,
["created_at"] = item.created_at,
["updated_at"] = item.updated_at
};
return result;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use Phinx\Migration\AbstractMigration;

class CreateProjectPostsTable extends AbstractMigration
{
public function change()
{
$table = $this->table('project_posts');
$table
->addColumn('guid', 'string')
->addColumn('project_id', 'integer', ['signed' => false, 'null' => false])
->addColumn('title', 'text')
->addColumn('content', 'text')

->addForeignKey('project_id', 'projects', 'id', ['delete'=> 'CASCADE', 'update'=> 'CASCADE'])

->addTimestamps()

->addIndex(['guid'], ['unique' => true])

->create();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php


use Phinx\Migration\AbstractMigration;

class AlterProjectPostsAddOriginId extends AbstractMigration
{
public function change()
{
$table = $this->table('project_posts');
$table->addColumn('origin_id', 'string', ['null' => true])
->save();
}
}