This repository was archived by the owner on Nov 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathIssueApiController.cs
More file actions
229 lines (196 loc) · 8.65 KB
/
IssueApiController.cs
File metadata and controls
229 lines (196 loc) · 8.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
namespace RobMensching.TinyBugs.Controllers
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using RobMensching.TinyBugs.Models;
using RobMensching.TinyBugs.Services;
using RobMensching.TinyBugs.ViewModels;
using RobMensching.TinyWebStack;
using ServiceStack.Logging;
using ServiceStack.OrmLite;
using ServiceStack.Text;
[Route("api/issue/{issue}")]
public class IssueApiController : ControllerBase
{
public override ViewBase Get(ControllerContext context)
{
long issueId;
if (!this.TryGetIssueIdFromContext(context, out issueId))
{
return new StatusCodeView(HttpStatusCode.BadRequest);
}
IssueViewModel issue;
if (!QueryService.TryGetIssueWithComments(issueId, out issue))
{
return new StatusCodeView(HttpStatusCode.NotFound);
}
issue.Location = context.ApplicationPath + issue.Id + "/";
return new JsonView(issue);
}
public override ViewBase Post(ControllerContext context)
{
// Forward POST to PUT for those clients that only use POST.
return this.Put(context);
}
public override ViewBase Put(ControllerContext context)
{
long issueId;
if (!this.TryGetIssueIdFromContext(context, out issueId))
{
return new StatusCodeView(HttpStatusCode.BadRequest);
}
User user;
if (!UserService.TryAuthenticateUser(context.User, out user))
{
return new StatusCodeView(HttpStatusCode.BadGateway); // TODO: return a better error code that doesn't cause forms authentication to overwrite our response
}
Issue issue;
using (var db = DataService.Connect(true))
{
issue = db.GetByIdOrDefault<Issue>(issueId);
if (issue == null)
{
return new StatusCodeView(HttpStatusCode.NotFound);
}
}
if (!user.IsInRole(UserRole.User))
{
return new StatusCodeView(HttpStatusCode.Forbidden);
}
bool unassigned = (issue.AssignedToUserId == 0);
bool owner = (user.Id == issue.AssignedToUserId || user.Id == issue.CreatedByUserId);
bool contributor = user.IsInRole(UserRole.Contributor);
PopulateResults results = issue.PopulateWithData(context.UnvalidatedForm, user.Guid);
if (results.Errors.Count > 0)
{
return new JsonView(results.Errors, HttpStatusCode.BadRequest);
}
// Only a few fields can be updated by normal users.
if (!owner && !contributor)
{
// AssignedTo may be changed if the issue isn't assigned to anyone. Status can be
// changed but if it is changed we'll check it further next. Remove anything else.
var disallowed = results.Updates.Keys.Where(s => !((unassigned && s == "AssignedToUserId") || s == "Status" || s == "UpdatedAt")).ToList();
foreach (var remove in disallowed)
{
results.Updates.Remove(remove);
}
// If status is being changed, ensure it's being set to untriaged.
PopulateResults.UpdatedValue statusChange;
if (results.Updates.TryGetValue("Status", out statusChange) &&
(IssueStatus)statusChange.New != IssueStatus.Untriaged)
{
results.Updates.Remove("Status");
}
}
string comment = context.UnvalidatedForm.Get("comment");
IssueViewModel vm = UpdateIssue(context, issue, user.Id, comment, results.Updates);
if (vm == null)
{
return new StatusCodeView(HttpStatusCode.InternalServerError);
}
return new JsonView(vm);
}
public override ViewBase Delete(ControllerContext context)
{
long issueId;
if (!this.TryGetIssueIdFromContext(context, out issueId))
{
return new StatusCodeView(HttpStatusCode.BadRequest);
}
User user;
if (!UserService.TryAuthenticateUser(context.User, out user))
{
return new StatusCodeView(HttpStatusCode.BadGateway); // TODO: return a better error code that doesn't cause forms authentication to overwrite our response
}
Issue issue;
using (var db = DataService.Connect(true))
{
issue = db.GetByIdOrDefault<Issue>(issueId);
if (issue == null)
{
return new StatusCodeView(HttpStatusCode.NotFound);
}
}
if (user.Id != issue.CreatedByUserId &&
!user.IsInRole(UserRole.Contributor))
{
return new StatusCodeView(HttpStatusCode.Forbidden);
}
this.DeleteIssue(issue.Id);
return null;
}
public bool TryGetIssueIdFromContext(ControllerContext context, out long issueId)
{
string value = context.RouteData.Values["issue"] as string;
return Int64.TryParse(value, out issueId);
}
public IssueViewModel UpdateIssue(ControllerContext context, Issue issue, long userId, string commentText, Dictionary<string, PopulateResults.UpdatedValue> updates)
{
IssueViewModel vm = null;
IssueComment comment = new IssueComment();
comment.IssueId = issue.Id;
comment.CommentByUserId = userId;
comment.CreatedAt = issue.UpdatedAt;
comment.Text = commentText;
foreach (var kvp in updates)
{
if (kvp.Key.Equals("UpdatedAt", StringComparison.OrdinalIgnoreCase))
{
continue;
}
object oldValue = kvp.Value.FriendlyOld ?? kvp.Value.Old ?? String.Empty;
object newValue = kvp.Value.FriendlyNew ?? kvp.Value.New ?? String.Empty;
IssueChange change = new IssueChange();
change.Column = kvp.Value.FriendlyName ?? kvp.Key;
change.Old = oldValue.ToString();
change.New = newValue.ToString();
comment.Changes.Add(change);
}
comment.Changes.Sort();
using (var db = DataService.Connect())
using (var tx = db.BeginTransaction())
{
// If there is some sort of recognizable change.
if (!String.IsNullOrEmpty(comment.Text) || comment.Changes.Count > 0)
{
db.UpdateOnly(issue, v => v.Update(updates.Keys.ToArray()).Where(i => i.Id == issue.Id));
db.Insert(comment);
comment.Id = db.GetLastInsertId();
}
if (QueryService.TryGetIssueWithCommentsUsingDb(issue.Id, db, out vm))
{
var allComments = String.Join(" ", vm.Comments.Select( issueComment => issueComment.Text ));
db.Update<FullTextSearchIssue>(new { Text = issue.Text, Title = issue.Title, Comments = allComments }, s => s.DocId == issue.Id);
vm.Location = context.ApplicationPath + vm.Id + "/";
var breadcrumbs = new BreadcrumbsViewModel(new Breadcrumb("Issues", context.ApplicationPath), new Breadcrumb("#" + vm.Id + " - " + vm.Title, vm.Location));
FileService.WriteIssue(vm, breadcrumbs);
tx.Commit();
// best effort email about changes to issue.
try
{
MailService.SendIssueComment(vm, comment.Id);
}
catch (Exception e)
{
LogManager.GetLogger("error").Error(String.Format(" failed to send update about issue #{0}, comment #{1}", issue.Id, comment.Id), e);
}
}
}
return vm;
}
public void DeleteIssue(long issueId)
{
using (var db = DataService.Connect())
using (var tx = db.BeginTransaction())
{
db.DeleteByIdParam<Issue>(issueId);
FileService.RemoveIssue(issueId);
tx.Commit();
}
}
}
}