l4d.tools/app/controllers/servers_controller.rb

92 lines
2.8 KiB
Ruby

class ServersController < ApplicationController
before_action :set_server, only: [ :show, :destroy, :start, :stop, :restart, :spawn ]
def index
@servers = current_user.servers.includes(:server_template).order(created_at: :desc)
end
def show
authorize_user!
end
def new
@server_templates = current_user.server_templates.order(:name)
if params[:server_template_id].present?
@server_template = current_user.server_templates.find(params[:server_template_id])
@server = current_user.servers.build(server_template: @server_template)
else
@server = current_user.servers.build
end
end
def create
template_id = params[:server_template_id] || server_params[:server_template_id]
@server_template = current_user.server_templates.find(template_id)
@server = current_user.servers.build(server_params)
@server.server_template = @server_template
@server.status = :stopped
if @server.save
Activity.log(current_user, "spawned", "Server", @server.id, { name: @server.name, port: @server.port })
SpawnServerJob.perform_later(@server.id)
redirect_to @server, notice: "Server spawning..."
else
@server_templates = current_user.server_templates.order(:name)
render :new, status: :unprocessable_entity
end
end
def spawn
authorize_user!
Activity.log(current_user, "spawning", "Server", @server.id, { name: @server.name })
SpawnServerJob.perform_later(@server.id)
@server.update(status: :starting)
redirect_to @server, notice: "Server spawning..."
end
def start
authorize_user!
L4dServer::SystemdManager.start(@server)
@server.update(status: :starting)
Activity.log(current_user, "started", "Server", @server.id, {})
redirect_to @server, notice: "Server starting..."
end
def stop
authorize_user!
L4dServer::SystemdManager.stop(@server)
@server.update(status: :stopped)
Activity.log(current_user, "stopped", "Server", @server.id, {})
redirect_to @server, notice: "Server stopped."
end
def restart
authorize_user!
L4dServer::SystemdManager.restart(@server)
@server.update(status: :starting)
Activity.log(current_user, "restarted", "Server", @server.id, {})
redirect_to @server, notice: "Server restarting..."
end
def destroy
authorize_user!
name = @server.name
@server.destroy
Activity.log(current_user, "deleted", "Server", @server.id, { name: name })
redirect_to servers_path, notice: "Server deleted."
end
private
def set_server
@server = Server.find(params[:id])
end
def server_params
params.require(:server).permit(:name, :port, :server_template_id)
end
def authorize_user!
redirect_to servers_path, alert: "Not authorized" unless @server.user_id == current_user.id
end
end