#' Getting server sessions
#'
#' Get the server sessions (including player session log) from the appropriate API endpoint
#' @keywords sessions
#' @import jsonlite
#' @import httr
#' @param url Source of the \code{sessions/overview.json} API endpoint. Defaults to using the option
#' \code{url.general.sessions}, if that is empty, the Wurstmineberg sessions are used.
#' @return \code{data.frame} with server- and lists of player sessions
#' @export
#' @note Uses the default API location URL unless the appropriate option is set.
#' @examples
#' options(url.general.sessions = "http://api.wurstmineberg.de/server/sessions/overview.json")
#' sessions <- getSessions()
getSessions <- function(url = getOption("url.general.sessions")){
if (is.null(url)){
url <- "http://api.wurstmineberg.de/server/sessions/overview.json"
}
sessions <- jsonlite::fromJSON(url)
sessions <- as.data.frame(sessions)
# Remove empty (NULL) sessions, because they make shit complicated
sessions <- sessions[!as.logical(lapply(sessions$uptimes.sessions, is.null)), ]
# Convert dates to POSIXct because it's always good to have POSIXct
sessions$uptimes.startTime <- as.POSIXct(sessions$uptimes.startTime, tz="UTC")
sessions$uptimes.endTime <- as.POSIXct(sessions$uptimes.endTime, tz="UTC")
# Fill playerSessions with data from sessions$uptimes.sessions in an ugly way because fuck this
numSessions <- nrow(sessions)
# If the latest session is NA, we'll just end it RIGHT NOW
if(is.na(sessions$uptimes.endTime[numSessions])){
sessions$uptimes.endTime[numSessions] <- as.POSIXct(as.POSIXlt(Sys.time(), tz="UTC"))
}
# If current session is empty, change indexing bound to let it go
if(is.null(sessions$uptimes.sessions[[numSessions]])){
numSessions <- numSessions - 1}
if("leaveTime" %in% names(sessions$uptimes.sessions[[numSessions]]) == FALSE){
sessions$uptimes.sessions[[numSessions]]$leaveTime <- as.character(sessions$uptimes.endTime[numSessions])
}
# This uses session endTimes as leaveTime in case the session ended in a non-standard way
for(i in 1:numSessions){
if(is.null(sessions$uptimes.sessions[[i]])){next} # Skip empty sessions
NAcond <- is.na(sessions$uptimes.sessions[[i]]["leaveTime"])
sessions$uptimes.sessions[[i]][NAcond, "leaveTime"] <- as.character(sessions$uptimes.endTime[i])
}
return(sessions[1:numSessions,])
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.