src/main/kotlin/de/uapcore/lightpit/servlet/ProjectServlet.kt

Sat, 27 Nov 2021 13:03:57 +0100

author
Mike Becker <universe@uap-core.de>
date
Sat, 27 Nov 2021 13:03:57 +0100
changeset 242
b7f3e972b13c
parent 232
296e12ff8d1c
child 247
e71ae69c68c0
permissions
-rw-r--r--

#109 add comment history

     1 /*
     2  * Copyright 2021 Mike Becker. All rights reserved.
     3  *
     4  * Redistribution and use in source and binary forms, with or without
     5  * modification, are permitted provided that the following conditions are met:
     6  *
     7  * 1. Redistributions of source code must retain the above copyright
     8  * notice, this list of conditions and the following disclaimer.
     9  *
    10  * 2. Redistributions in binary form must reproduce the above copyright
    11  * notice, this list of conditions and the following disclaimer in the
    12  * documentation and/or other materials provided with the distribution.
    13  *
    14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    17  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    20  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    21  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    22  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    24  */
    26 package de.uapcore.lightpit.servlet
    28 import de.uapcore.lightpit.*
    29 import de.uapcore.lightpit.dao.DataAccessObject
    30 import de.uapcore.lightpit.entities.*
    31 import de.uapcore.lightpit.types.IssueCategory
    32 import de.uapcore.lightpit.types.IssueStatus
    33 import de.uapcore.lightpit.types.VersionStatus
    34 import de.uapcore.lightpit.types.WebColor
    35 import de.uapcore.lightpit.util.AllFilter
    36 import de.uapcore.lightpit.util.IssueFilter
    37 import de.uapcore.lightpit.util.IssueSorter.Companion.DEFAULT_ISSUE_SORTER
    38 import de.uapcore.lightpit.util.SpecificFilter
    39 import de.uapcore.lightpit.viewmodel.*
    40 import java.sql.Date
    41 import javax.servlet.annotation.WebServlet
    43 @WebServlet(urlPatterns = ["/projects/*"])
    44 class ProjectServlet : AbstractServlet() {
    46     init {
    47         get("/", this::projects)
    48         get("/%project", this::project)
    49         get("/%project/issues/%version/%component/", this::project)
    50         get("/%project/edit", this::projectForm)
    51         get("/-/create", this::projectForm)
    52         post("/-/commit", this::projectCommit)
    54         get("/%project/versions/", this::versions)
    55         get("/%project/versions/%version/edit", this::versionForm)
    56         get("/%project/versions/-/create", this::versionForm)
    57         post("/%project/versions/-/commit", this::versionCommit)
    59         get("/%project/components/", this::components)
    60         get("/%project/components/%component/edit", this::componentForm)
    61         get("/%project/components/-/create", this::componentForm)
    62         post("/%project/components/-/commit", this::componentCommit)
    64         get("/%project/issues/%version/%component/%issue", this::issue)
    65         get("/%project/issues/%version/%component/%issue/edit", this::issueForm)
    66         post("/%project/issues/%version/%component/%issue/comment", this::issueComment)
    67         get("/%project/issues/%version/%component/-/create", this::issueForm)
    68         post("/%project/issues/%version/%component/-/commit", this::issueCommit)
    69     }
    71     private fun projects(http: HttpRequest, dao: DataAccessObject) {
    72         val projects = dao.listProjects()
    73         val projectInfos = projects.map {
    74             ProjectInfo(
    75                 project = it,
    76                 versions = dao.listVersions(it),
    77                 components = emptyList(), // not required in this view
    78                 issueSummary = dao.collectIssueSummary(it)
    79             )
    80         }
    82         with(http) {
    83             view = ProjectsView(projectInfos)
    84             navigationMenu = projectNavMenu(projects)
    85             styleSheets = listOf("projects")
    86             render("projects")
    87         }
    88     }
    90     private fun activeProjectNavMenu(
    91         projects: List<Project>,
    92         projectInfo: ProjectInfo,
    93         selectedVersion: Version? = null,
    94         selectedComponent: Component? = null
    95     ) =
    96         projectNavMenu(
    97             projects,
    98             projectInfo.versions,
    99             projectInfo.components,
   100             projectInfo.project,
   101             selectedVersion,
   102             selectedComponent
   103         )
   105     private sealed interface LookupResult<T>
   106     private class NotFound<T> : LookupResult<T>
   107     private data class Found<T>(val elem: T?) : LookupResult<T>
   109     private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
   110         val node = pathParams[paramName]
   111         return if (node == null || node == "-") {
   112             Found(null)
   113         } else {
   114             val result = list.find { it.node == node }
   115             if (result == null) {
   116                 NotFound()
   117             } else {
   118                 Found(result)
   119             }
   120         }
   121     }
   123     private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
   124         val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
   126         val versions: List<Version> = dao.listVersions(project)
   127         val components: List<Component> = dao.listComponents(project)
   129         return ProjectInfo(
   130             project,
   131             versions,
   132             components,
   133             dao.collectIssueSummary(project)
   134         )
   135     }
   137     private fun sanitizeNode(name: String): String {
   138         val san = name.replace(Regex("[/\\\\]"), "-")
   139         return if (san.startsWith(".")) {
   140             "v$san"
   141         } else {
   142             san
   143         }
   144     }
   146     private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
   148     private data class PathInfos(
   149         val projectInfo: ProjectInfo,
   150         val version: Version?,
   151         val component: Component?
   152     ) {
   153         val project = projectInfo.project
   154         val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
   155     }
   157     private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
   158         val projectInfo = obtainProjectInfo(http, dao)
   159         if (projectInfo == null) {
   160             http.response.sendError(404)
   161             return null
   162         }
   164         val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   165             is NotFound -> {
   166                 http.response.sendError(404)
   167                 return null
   168             }
   169             is Found -> {
   170                 result.elem
   171             }
   172         }
   173         val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
   174             is NotFound -> {
   175                 http.response.sendError(404)
   176                 return null
   177             }
   178             is Found -> {
   179                 result.elem
   180             }
   181         }
   183         return PathInfos(projectInfo, version, component)
   184     }
   186     private fun project(http: HttpRequest, dao: DataAccessObject) {
   187         withPathInfo(http, dao)?.run {
   189             val issues = dao.listIssues(IssueFilter(
   190                 project = SpecificFilter(project),
   191                 version = version?.let { SpecificFilter(it) } ?: AllFilter(),
   192                 component = component?.let { SpecificFilter(it) } ?: AllFilter()
   193             )).sortedWith(DEFAULT_ISSUE_SORTER)
   195             with(http) {
   196                 pageTitle = project.name
   197                 view = ProjectDetails(projectInfo, issues, version, component)
   198                 feedPath = feedPath(project)
   199                 navigationMenu = activeProjectNavMenu(
   200                     dao.listProjects(),
   201                     projectInfo,
   202                     version,
   203                     component
   204                 )
   205                 styleSheets = listOf("projects")
   206                 render("project-details")
   207             }
   208         }
   209     }
   211     private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
   212         if (!http.pathParams.containsKey("project")) {
   213             http.view = ProjectEditView(Project(-1), dao.listUsers())
   214             http.navigationMenu = projectNavMenu(dao.listProjects())
   215         } else {
   216             val projectInfo = obtainProjectInfo(http, dao)
   217             if (projectInfo == null) {
   218                 http.response.sendError(404)
   219                 return
   220             }
   221             http.view = ProjectEditView(projectInfo.project, dao.listUsers())
   222             http.navigationMenu = activeProjectNavMenu(
   223                 dao.listProjects(),
   224                 projectInfo
   225             )
   226         }
   227         http.styleSheets = listOf("projects")
   228         http.render("project-form")
   229     }
   231     private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
   232         val project = Project(http.param("id")?.toIntOrNull() ?: -1).apply {
   233             name = http.param("name") ?: ""
   234             node = http.param("node") ?: ""
   235             description = http.param("description") ?: ""
   236             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   237             repoUrl = http.param("repoUrl") ?: ""
   238             owner = (http.param("owner")?.toIntOrNull() ?: -1).let {
   239                 if (it < 0) null else dao.findUser(it)
   240             }
   241             // intentional defaults
   242             if (node.isBlank()) node = name
   243             // sanitizing
   244             node = sanitizeNode(node)
   245         }
   247         if (project.id < 0) {
   248             dao.insertProject(project)
   249         } else {
   250             dao.updateProject(project)
   251         }
   253         http.renderCommit("projects/${project.node}")
   254     }
   256     private fun versions(http: HttpRequest, dao: DataAccessObject) {
   257         val projectInfo = obtainProjectInfo(http, dao)
   258         if (projectInfo == null) {
   259             http.response.sendError(404)
   260             return
   261         }
   263         with(http) {
   264             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.versions")}"
   265             view = VersionsView(
   266                 projectInfo,
   267                 dao.listVersionSummaries(projectInfo.project)
   268             )
   269             feedPath = feedPath(projectInfo.project)
   270             navigationMenu = activeProjectNavMenu(
   271                 dao.listProjects(),
   272                 projectInfo
   273             )
   274             styleSheets = listOf("projects")
   275             render("versions")
   276         }
   277     }
   279     private fun versionForm(http: HttpRequest, dao: DataAccessObject) {
   280         val projectInfo = obtainProjectInfo(http, dao)
   281         if (projectInfo == null) {
   282             http.response.sendError(404)
   283             return
   284         }
   286         val version: Version
   287         when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   288             is NotFound -> {
   289                 http.response.sendError(404)
   290                 return
   291             }
   292             is Found -> {
   293                 version = result.elem ?: Version(-1, projectInfo.project.id)
   294             }
   295         }
   297         with(http) {
   298             view = VersionEditView(projectInfo, version)
   299             feedPath = feedPath(projectInfo.project)
   300             navigationMenu = activeProjectNavMenu(
   301                 dao.listProjects(),
   302                 projectInfo,
   303                 selectedVersion = version
   304             )
   305             styleSheets = listOf("projects")
   306             render("version-form")
   307         }
   308     }
   310     private fun obtainIdAndProject(http: HttpRequest, dao:DataAccessObject): Pair<Int, Project>? {
   311         val id = http.param("id")?.toIntOrNull()
   312         val projectid = http.param("projectid")?.toIntOrNull() ?: -1
   313         val project = dao.findProject(projectid)
   314         return if (id == null || project == null) {
   315             http.response.sendError(400)
   316             null
   317         } else {
   318             Pair(id, project)
   319         }
   320     }
   322     private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
   323         val idParams = obtainIdAndProject(http, dao) ?: return
   324         val (id, project) = idParams
   326         val version = Version(id, project.id).apply {
   327             name = http.param("name") ?: ""
   328             node = http.param("node") ?: ""
   329             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   330             status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
   331             // TODO: process error messages
   332             eol =  http.param("eol", ::dateOptValidator, null, mutableListOf())
   333             release =  http.param("release", ::dateOptValidator, null, mutableListOf())
   334             // intentional defaults
   335             if (node.isBlank()) node = name
   336             // sanitizing
   337             node = sanitizeNode(node)
   338         }
   340         // sanitize eol and release date
   341         if (version.status.isEndOfLife) {
   342             if (version.eol == null) version.eol = Date(System.currentTimeMillis())
   343         } else if (version.status.isReleased) {
   344             if (version.release == null) version.release = Date(System.currentTimeMillis())
   345         }
   347         if (id < 0) {
   348             dao.insertVersion(version)
   349         } else {
   350             dao.updateVersion(version)
   351         }
   353         http.renderCommit("projects/${project.node}/versions/")
   354     }
   356     private fun components(http: HttpRequest, dao: DataAccessObject) {
   357         val projectInfo = obtainProjectInfo(http, dao)
   358         if (projectInfo == null) {
   359             http.response.sendError(404)
   360             return
   361         }
   363         with(http) {
   364             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
   365             view = ComponentsView(
   366                 projectInfo,
   367                 dao.listComponentSummaries(projectInfo.project)
   368             )
   369             feedPath = feedPath(projectInfo.project)
   370             navigationMenu = activeProjectNavMenu(
   371                 dao.listProjects(),
   372                 projectInfo
   373             )
   374             styleSheets = listOf("projects")
   375             render("components")
   376         }
   377     }
   379     private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
   380         val projectInfo = obtainProjectInfo(http, dao)
   381         if (projectInfo == null) {
   382             http.response.sendError(404)
   383             return
   384         }
   386         val component: Component
   387         when (val result = http.lookupPathParam("component", projectInfo.components)) {
   388             is NotFound -> {
   389                 http.response.sendError(404)
   390                 return
   391             }
   392             is Found -> {
   393                 component = result.elem ?: Component(-1, projectInfo.project.id)
   394             }
   395         }
   397         with(http) {
   398             view = ComponentEditView(projectInfo, component, dao.listUsers())
   399             feedPath = feedPath(projectInfo.project)
   400             navigationMenu = activeProjectNavMenu(
   401                 dao.listProjects(),
   402                 projectInfo,
   403                 selectedComponent = component
   404             )
   405             styleSheets = listOf("projects")
   406             render("component-form")
   407         }
   408     }
   410     private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
   411         val idParams = obtainIdAndProject(http, dao) ?: return
   412         val (id, project) = idParams
   414         val component = Component(id, project.id).apply {
   415             name = http.param("name") ?: ""
   416             node = http.param("node") ?: ""
   417             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   418             color = WebColor(http.param("color") ?: "#000000")
   419             description = http.param("description")
   420             // TODO: process error message
   421             active = http.param("active", ::boolValidator, true, mutableListOf())
   422             lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
   423                 if (it < 0) null else dao.findUser(it)
   424             }
   425             // intentional defaults
   426             if (node.isBlank()) node = name
   427             // sanitizing
   428             node = sanitizeNode(node)
   429         }
   431         if (id < 0) {
   432             dao.insertComponent(component)
   433         } else {
   434             dao.updateComponent(component)
   435         }
   437         http.renderCommit("projects/${project.node}/components/")
   438     }
   440     private fun issue(http: HttpRequest, dao: DataAccessObject) {
   441         withPathInfo(http, dao)?.run {
   442             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   443             if (issue == null) {
   444                 http.response.sendError(404)
   445                 return
   446             }
   448             val comments = dao.listComments(issue)
   450             with(http) {
   451                 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
   452                 view = IssueDetailView(issue, comments, project, version, component)
   453                 feedPath = feedPath(projectInfo.project)
   454                 navigationMenu = activeProjectNavMenu(
   455                     dao.listProjects(),
   456                     projectInfo,
   457                     version,
   458                     component
   459                 )
   460                 styleSheets = listOf("projects")
   461                 javascript = "issue-editor"
   462                 render("issue-view")
   463             }
   464         }
   465     }
   467     private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
   468         withPathInfo(http, dao)?.run {
   469             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1) ?: Issue(
   470                 -1,
   471                 project,
   472             )
   474             // for new issues set some defaults
   475             if (issue.id < 0) {
   476                 // pre-select component, if available in the path info
   477                 issue.component = component
   479                 // pre-select version, if available in the path info
   480                 if (version != null) {
   481                     if (version.status.isReleased) {
   482                         issue.affected = version
   483                     } else {
   484                         issue.resolved = version
   485                     }
   486                 }
   487             }
   489             with(http) {
   490                 view = IssueEditView(
   491                     issue,
   492                     projectInfo.versions,
   493                     projectInfo.components,
   494                     dao.listUsers(),
   495                     project,
   496                     version,
   497                     component
   498                 )
   499                 feedPath = feedPath(projectInfo.project)
   500                 navigationMenu = activeProjectNavMenu(
   501                     dao.listProjects(),
   502                     projectInfo,
   503                     version,
   504                     component
   505                 )
   506                 styleSheets = listOf("projects")
   507                 javascript = "issue-editor"
   508                 render("issue-form")
   509             }
   510         }
   511     }
   513     private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
   514         withPathInfo(http, dao)?.run {
   515             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   516             if (issue == null) {
   517                 http.response.sendError(404)
   518                 return
   519             }
   521             val commentId = http.param("commentid")?.toIntOrNull() ?: -1
   522             if (commentId > 0) {
   523                 val comment = dao.findComment(commentId)
   524                 if (comment == null) {
   525                     http.response.sendError(404)
   526                     return
   527                 }
   528                 val originalAuthor = comment.author?.username
   529                 if (originalAuthor != null && originalAuthor == http.remoteUser) {
   530                     val newComment = http.param("comment")
   531                     if (!newComment.isNullOrBlank()) {
   532                         comment.comment = newComment
   533                         dao.updateComment(comment)
   534                         dao.insertHistoryEvent(issue, comment)
   535                     } else {
   536                         logger().debug("Not updating comment ${comment.id} because nothing changed.")
   537                     }
   538                 } else {
   539                     http.response.sendError(403)
   540                     return
   541                 }
   542             } else {
   543                 val comment = IssueComment(-1, issue.id).apply {
   544                     author = http.remoteUser?.let { dao.findUserByName(it) }
   545                     comment = http.param("comment") ?: ""
   546                 }
   547                 val newId = dao.insertComment(comment)
   548                 dao.insertHistoryEvent(issue, comment, newId)
   549             }
   551             http.renderCommit("${issuesHref}${issue.id}")
   552         }
   553     }
   555     private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
   556         withPathInfo(http, dao)?.run {
   557             val issue = Issue(
   558                 http.param("id")?.toIntOrNull() ?: -1,
   559                 project
   560             ).apply {
   561                 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
   562                 category = IssueCategory.valueOf(http.param("category") ?: "")
   563                 status = IssueStatus.valueOf(http.param("status") ?: "")
   564                 subject = http.param("subject") ?: ""
   565                 description = http.param("description") ?: ""
   566                 assignee = http.param("assignee")?.toIntOrNull()?.let {
   567                     when (it) {
   568                         -1 -> null
   569                         -2 -> component?.lead
   570                         else -> dao.findUser(it)
   571                     }
   572                 }
   573                 // TODO: process error messages
   574                 eta = http.param("eta", ::dateOptValidator, null, mutableListOf())
   576                 affected = http.param("affected")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
   577                 resolved = http.param("resolved")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
   578             }
   580             val openId = if (issue.id < 0) {
   581                 val id = dao.insertIssue(issue)
   582                 dao.insertHistoryEvent(issue, id)
   583                 id
   584             } else {
   585                 val reference = dao.findIssue(issue.id)
   586                 if (reference == null) {
   587                     http.response.sendError(404)
   588                     return
   589                 }
   591                 if (issue.hasChanged(reference)) {
   592                     dao.updateIssue(issue)
   593                     dao.insertHistoryEvent(issue)
   594                 } else {
   595                     logger().debug("Not updating issue ${issue.id} because nothing changed.")
   596                 }
   598                 val newComment = http.param("comment")
   599                 if (!newComment.isNullOrBlank()) {
   600                     val comment = IssueComment(-1, issue.id).apply {
   601                         author = http.remoteUser?.let { dao.findUserByName(it) }
   602                         comment = newComment
   603                     }
   604                     val commentid = dao.insertComment(comment)
   605                     dao.insertHistoryEvent(issue, comment, commentid)
   606                 }
   607                 issue.id
   608             }
   610             if (http.param("more") != null) {
   611                 http.renderCommit("${issuesHref}-/create")
   612             } else {
   613                 http.renderCommit("${issuesHref}${openId}")
   614             }
   615         }
   616     }
   617 }

mercurial