Several bugfixes and finishing touches

This commit is contained in:
Claude Brisson
2023-12-25 12:26:08 +01:00
parent 91e0bc839a
commit e33bc995c6
18 changed files with 264 additions and 38 deletions

View File

@@ -46,7 +46,7 @@ object StandingsHandler: PairgothApiHandler {
RANK -> tournament.pairables.mapValues { it.value.rank }
RATING -> tournament.pairables.mapValues { it.value.rating }
NBW -> historyHelper.wins
MMS -> historyHelper.scores
MMS -> historyHelper.mms
STS -> nullMap
CPS -> nullMap

View File

@@ -142,7 +142,10 @@ object OpenGotha {
country = player.country,
club = player.club
).also {
canonicMap.put("${player.name}${player.firstName}".uppercase(Locale.ENGLISH), it.id)
player.participating.toString().forEachIndexed { i,c ->
if (c == '0') it.skip.add(i + 1)
}
canonicMap.put("${player.name.replace(" ", "")}${player.firstName.replace(" ", "")}".uppercase(Locale.ENGLISH), it.id)
}
}.associateByTo(tournament.players) { it.id }
val gamesPerRound = ogTournament.games.game.groupBy {
@@ -155,7 +158,7 @@ object OpenGotha {
black = canonicMap[game.blackPlayer] ?: throw Error("player not found: ${game.blackPlayer}"),
white = canonicMap[game.whitePlayer] ?: throw Error("player not found: ${game.whitePlayer}"),
handicap = game.handicap,
result = when (game.result) {
result = when (game.result.removeSuffix("_BYDEF")) {
"RESULT_UNKNOWN" -> Game.Result.UNKNOWN
"RESULT_WHITEWINS" -> Game.Result.WHITE
"RESULT_BLACKWINS" -> Game.Result.BLACK

View File

@@ -15,7 +15,7 @@ open class HistoryHelper(protected val history: List<List<Game>>, scoresGetter:
else -> 0.0
}
val scores by lazy {
private val scores by lazy {
scoresGetter()
}
@@ -76,6 +76,9 @@ open class HistoryHelper(protected val history: List<List<Game>>, scoresGetter:
}
}
// define mms to be a synonym of scores
val mms by lazy { scores }
// SOS related functions given a score function
val sos by lazy {
(history.flatten().map { game ->

View File

@@ -161,6 +161,11 @@
<version>${servlet.api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
<!-- proxy -->
<dependency>
<groupId>org.eclipse.jetty</groupId>

View File

@@ -0,0 +1,53 @@
package org.jeudego.pairgoth.util
import org.apache.commons.fileupload.FileItemIterator
import org.apache.commons.fileupload.FileItemStream
import org.apache.commons.fileupload.FileUploadException
import org.apache.commons.fileupload.servlet.ServletFileUpload
import org.apache.commons.fileupload.util.Streams
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import javax.servlet.http.HttpServletRequest
object Upload {
internal var logger = LoggerFactory.getLogger("upload")
const val SIZE_RANDOM = 20
@Throws(IOException::class, FileUploadException::class)
fun handleFileUpload(request: HttpServletRequest): List<Pair<String, ByteArray>> {
// Check that we have a file upload request
val isMultipart: Boolean = ServletFileUpload.isMultipartContent(request)
if (!isMultipart) {
throw IOException("multipart content expected")
}
val files = mutableListOf<Pair<String, ByteArray>>()
// Create a new file upload handler
val upload = ServletFileUpload()
val iter: FileItemIterator = upload.getItemIterator(request)
// over all fields
while (iter.hasNext()) {
val item: FileItemStream = iter.next()
val name: String = item.fieldName
val stream: InputStream = item.openStream()
if (item.isFormField) {
// standard fields set into request attributes
request.setAttribute(name, Streams.asString(stream))
} else {
val filename: String = item.name
if (StringUtils.isEmpty(filename)) {
// ignoring empty file
continue
}
val input: InputStream = item.openStream()
val bytes = ByteArrayOutputStream()
Streams.copy(input, bytes, true)
files.add(Pair(filename, bytes.toByteArray()))
}
}
return files
}
}

View File

@@ -11,6 +11,7 @@ import org.slf4j.LoggerFactory
class ApiTool {
companion object {
const val JSON = "application/json"
const val XML = "application/xml"
val apiRoot = System.getProperty("pairgoth.api.external.url")?.let { "${it.removeSuffix("/")}/" }
?: throw Error("no configured API url")
val logger = LoggerFactory.getLogger("api")
@@ -50,4 +51,7 @@ class ApiTool {
fun delete(url: String, payload: Json? = null) = prepare(url)
.delete(payload?.toRequestBody() ?: EMPTY_REQUEST)
.process()
fun post(url: String, xml: String) =
prepare(url).post(xml.toRequestBody(XML.toMediaType())).process()
}

View File

@@ -0,0 +1,28 @@
package org.jeudego.pairgoth.web
import org.jeudego.pairgoth.util.Upload
import org.jeudego.pairgoth.view.ApiTool
import java.nio.charset.StandardCharsets
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class ImportServlet: HttpServlet() {
private val api = ApiTool()
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
val uploads = Upload.handleFileUpload(req)
if (uploads.size != 1) resp.sendError(HttpServletResponse.SC_BAD_REQUEST)
else {
val xml = uploads.first().second.toString(StandardCharsets.UTF_8)
val apiResp = api.post("tour", xml)
if (apiResp.isObject && apiResp.asObject().getBoolean("success") == true) {
resp.contentType = "application/json; charset=UTF-8"
resp.writer.println(apiResp.toString())
} else {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
}
}
}
}

View File

@@ -54,7 +54,8 @@ class LanguageFilter : Filter {
} else {
// the request must be redirected
val destination = if (askedLanguage != null) target else uri
response.sendRedirect("/${preferredLanguage}${destination}")
val query = request.queryString ?: ""
response.sendRedirect("/${preferredLanguage}${destination}${if (query.isEmpty()) "" else "?$query"}")
}
}
}

View File

@@ -0,0 +1,8 @@
@layer pairgoth {
.tournaments.section {
display: flex;
flex-flow: row wrap;
gap: 1em;
justify-content: center;
}
}

View File

@@ -320,6 +320,7 @@
max-height: inherit;
}
.popup-footer {
margin-top: 1em;
position: relative;
text-align: justify;
display: flex;
@@ -343,4 +344,9 @@
pointer-events: all;
cursor: pointer;
}
thead {
position: sticky;
top: 0;
}
}

View File

@@ -81,6 +81,7 @@
position: relative;
.toggle {
cursor: pointer;
text-align: center;
input {
display: none;
}
@@ -94,7 +95,7 @@
height: 26px;
border-radius: 18px;
background-color: #F7D6A3;
display: flex;
display: inline-flex;
align-items: center;
padding-left: 5px;
padding-right: 5px;

View File

@@ -30,7 +30,7 @@
*#
<div id="header" class="horz flex">
<div id="logo">
<img src="/img/logov2.svg"/>
<a href="/"><img src="/img/logov2.svg"/></a>
</div>
<div id="title">
</div>

View File

@@ -71,6 +71,12 @@
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet>
<servlet-name>import</servlet-name>
<servlet-class>org.jeudego.pairgoth.web.ImportServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
@@ -89,6 +95,10 @@
<servlet-name>search</servlet-name>
<url-pattern>/api/search/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>import</servlet-name>
<url-pattern>/api/import/*</url-pattern>
</servlet-mapping>
<!-- context params -->
<context-param>

View File

@@ -1,15 +1,79 @@
<div class="section">
<div class="actions section">
<a href="tour" class="ui blue icon floating button">
<i class="fa fa-plus-square-o"></i>
New tournament
</a>
</div>
#foreach($tour in $api.get('tour').entrySet())
<div class="section">
$tour
<a href="tour?id=${tour.key}" class="ui open basic secondary white icon floating button">
<i class="fa fa-folder-open-o"></i>
Open
<a id="import-tournament" class="ui orange icon floating button">
<i class="fa fa-upload"></i>
Import tournament
</a>
</div>
<div class="tournaments section">
#foreach($tour in $api.get('tour').entrySet())
<a href="tour?id=${tour.key}" class="ui open basic secondary white icon floating button">
<i class="fa fa-folder-open-o"></i>
$tour.value
</a>
#end
</div>
<div id="import-popup" class="popup">
<div class="popup-body">
<form id="import-form" class="ui form">
<div class="popup-content">
<div class="field">
<label>OpenGotha file</label>
<input type="file" name="file" accept=".xml"/>
</div>
</div>
<div class="popup-footer">
<button id="cancel-import" type="button" class="ui gray right labeled icon floating close button">
<i class="times icon"></i>
Cancel
</button>
<button id="import" type="button" class="ui green right labeled icon floating button">
<i class="plus icon"></i>
Import
</button>
</div>
</form>
</div>
</div>
<script type="text/javascript">
// #[[
function doImport() {
let form = $('#import-form')[0];
let formData = new FormData(form);
fetch('/api/import', {
method: 'POST',
body: formData
}).then(resp => {
if (resp.ok) return resp.json();
else throw resp;
}).then(json => {
if (json.success) {
console.log(`/tour?id=${json.id}`)
document.location.href = `/tour?id=${json.id}`
} else {
showError(json.error || 'unknown error')
}
}).catch(err => {
error(err);
});
}
onLoad(()=>{
$('#import-tournament').on('click', e => {
modal('import-popup');
e.preventDefault();
return false;
});
$('#import').on('click', e => {
let files = $('#import-form input')[0].files;
if (files.length > 0) {
doImport();
} else showError('no file choosen');
close_modal();
});
});
// ]]#
</script>

View File

@@ -163,6 +163,34 @@ function close_modal() {
$(`.popup`).removeClass('shown');
}
function screenshot() {
const bodyContent = document.body.innerHTML;
// Create an SVG element
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', window.innerWidth);
svg.setAttribute('height', window.innerHeight);
// Create a foreignObject element
const foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
foreignObject.setAttribute('width', '100%');
foreignObject.setAttribute('height', '100%');
// Append the body content to foreignObject
foreignObject.innerHTML = bodyContent;
// Append foreignObject to the SVG
svg.appendChild(foreignObject);
// Create a data URL from the SVG
const dataUrl = 'data:image/svg+xml,' + encodeURIComponent(new XMLSerializer().serializeToString(svg));
// Open the screenshot in a new window/tab (optional)
const screenshotWindow = window.open();
screenshotWindow.document.write('<img src="' + dataUrl + '" alt="Screenshot">');
}
onLoad(() => {
$('button.close').on('click', e => {
let modal = e.target.closest('.popup');
@@ -223,5 +251,13 @@ onLoad(() => {
}
});
// disable hash scrolling
if (window.location.hash) {
console.log("lkhjqlksjdhflkqsjhfd")
setTimeout(function() {
window.scrollTo(0, 0);
}, 1);
}
});

View File

@@ -44,7 +44,7 @@ function search(needle) {
let html = resultTemplate.render(result);
$('#search-result')[0].innerHTML = html;
} else console.log(result);
})
});
} else {
$('#search-result').clear();
searchTimer = undefined;

View File

@@ -51,7 +51,7 @@
<th>Plc</th>
<th>Name</th>
<th>Rank</th>
<th>Cntry</th>
<th>Ctr</th>
<th>Nbw</th>
#foreach($r in [1..$round])
<th>R$r</th>
@@ -66,7 +66,7 @@
<td>$part.num</td>
<td>$part.place</td>
<td>$part.name $part.firstname</td>
<td>$part.rank</td>
<td>#rank($part.rank)</td>
<td>$part.country</td>
<td>$part.NBW</td>
#set($mx = $round - 1)

View File

@@ -149,31 +149,35 @@
});
// prev/next round buttons
if (activeRound === 1) {
$('.prev-round').addClass('disabled');
}
if (activeRound === tour_rounds) {
$('.next-round').addClass('disabled');
}
$('.prev-round').on('click', e => {
let round = activeRound - 1;
if (round > 0) {
window.location.search = `id=${tour_id}&round=${round}`
if (typeof(activeRound) !== 'undefined') {
if (activeRound === 1) {
$('.prev-round').addClass('disabled');
}
});
$('.next-round').on('click', e => {
let round = activeRound + 1;
if (round <= tour_rounds) {
window.location.search = `id=${tour_id}&round=${round}`
if (activeRound === tour_rounds) {
$('.next-round').addClass('disabled');
}
});
$('.prev-round').on('click', e => {
let round = activeRound - 1;
if (round > 0) {
window.location.search = `id=${tour_id}&round=${round}`
}
});
$('.next-round').on('click', e => {
let round = activeRound + 1;
if (round <= tour_rounds) {
window.location.search = `id=${tour_id}&round=${round}`
}
});
}
});
// ]]#
#include('/js/tour-information.inc.js')
#include('/js/tour-registration.inc.js')
#include('/js/tour-pairing.inc.js')
#include('/js/tour-results.inc.js')
#include('/js/tour-standings.inc.js')
#if($tour)
#include('/js/tour-registration.inc.js')
#include('/js/tour-pairing.inc.js')
#include('/js/tour-results.inc.js')
#include('/js/tour-standings.inc.js')
#end
</script>
<div id="invalid_character" class="hidden">Invalid character</div>
<script type="text/javascript" src="/lib/datepicker-1.3.4/datepicker-full.min.js"></script>