Rename DCC project into RAM

RAM: Railroad Assets Manager
This commit is contained in:
2022-04-10 21:05:02 +02:00
parent 305507a4e6
commit d594dbe47c
77 changed files with 16 additions and 16 deletions

0
ram/consist/__init__.py Normal file
View File

49
ram/consist/admin.py Normal file
View File

@@ -0,0 +1,49 @@
from django.contrib import admin
from adminsortable2.admin import SortableInlineAdminMixin
from consist.models import Consist, ConsistItem
class ConsistItemInline(SortableInlineAdminMixin, admin.TabularInline):
model = ConsistItem
min_num = 1
extra = 0
readonly_fields = ("address", "type", "company", "era")
@admin.register(Consist)
class ConsistAdmin(admin.ModelAdmin):
inlines = (ConsistItemInline,)
readonly_fields = (
"creation_time",
"updated_time",
)
list_display = ("identifier", "company", "era")
list_filter = list_display
search_fields = list_display
fieldsets = (
(
None,
{
"fields": (
"identifier",
"consist_address",
"company",
"era",
"notes",
"tags",
)
},
),
(
"Audit",
{
"classes": ("collapse",),
"fields": (
"creation_time",
"updated_time",
),
},
),
)

6
ram/consist/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ConsistConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "consist"

View File

@@ -0,0 +1,44 @@
# Generated by Django 4.0.3 on 2022-04-07 09:25
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('metadata', '0001_initial'),
('roster', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Consist',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('identifier', models.CharField(max_length=128)),
('consist_address', models.SmallIntegerField(blank=True, default=None, null=True)),
('era', models.CharField(blank=True, max_length=32)),
('notes', models.TextField(blank=True)),
('creation_time', models.DateTimeField(auto_now_add=True)),
('updated_time', models.DateTimeField(auto_now=True)),
('company', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='metadata.company')),
('tags', models.ManyToManyField(blank=True, related_name='consist', to='metadata.tag')),
],
),
migrations.CreateModel(
name='ConsistItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('order', models.PositiveIntegerField(default=0)),
('consist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='consist_item', to='consist.consist')),
('rolling_stock', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='roster.rollingstock')),
],
options={
'ordering': ['order'],
},
),
]

View File

52
ram/consist/models.py Normal file
View File

@@ -0,0 +1,52 @@
from uuid import uuid4
from django.db import models
from metadata.models import Company, Tag
from roster.models import RollingStock
class Consist(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
identifier = models.CharField(max_length=128, unique=False)
tags = models.ManyToManyField(Tag, related_name="consist", blank=True)
consist_address = models.SmallIntegerField(
default=None, null=True, blank=True
)
company = models.ForeignKey(
Company, on_delete=models.CASCADE, null=True, blank=True
)
era = models.CharField(max_length=32, blank=True)
notes = models.TextField(blank=True)
creation_time = models.DateTimeField(auto_now_add=True)
updated_time = models.DateTimeField(auto_now=True)
def __str__(self):
return "{0}".format(self.identifier)
class ConsistItem(models.Model):
consist = models.ForeignKey(
Consist,
on_delete=models.CASCADE,
related_name="consist_item"
)
rolling_stock = models.ForeignKey(RollingStock, on_delete=models.CASCADE)
order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta(object):
ordering = ["order"]
def __str__(self):
return "{0}".format(self.rolling_stock)
def type(self):
return self.rolling_stock.rolling_class.type
def address(self):
return self.rolling_stock.address
def company(self):
return self.rolling_stock.company()
def era(self):
return self.rolling_stock.era

View File

@@ -0,0 +1,24 @@
from rest_framework import serializers
from consist.models import Consist, ConsistItem
from metadata.serializers import CompanySerializer, TagSerializer
# from roster.serializers import RollingStockSerializer
class ConsistItemSerializer(serializers.ModelSerializer):
# rolling_stock = RollingStockSerializer()
class Meta:
model = ConsistItem
fields = ("order", "rolling_stock")
class ConsistSerializer(serializers.ModelSerializer):
company = CompanySerializer()
consist_item = ConsistItemSerializer(many=True)
tags = TagSerializer(many=True)
class Meta:
model = Consist
fields = "__all__"

3
ram/consist/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

6
ram/consist/urls.py Normal file
View File

@@ -0,0 +1,6 @@
from django.urls import path
from consist.views import ConsistList
urlpatterns = [
path("list", ConsistList.as_view()),
]

15
ram/consist/views.py Normal file
View File

@@ -0,0 +1,15 @@
from rest_framework.generics import ListAPIView, RetrieveAPIView
from consist.models import Consist
from consist.serializers import ConsistSerializer
class ConsistList(ListAPIView):
queryset = Consist.objects.all()
serializer_class = ConsistSerializer
class ConsistGet(RetrieveAPIView):
queryset = Consist.objects.all()
serializer_class = ConsistSerializer
lookup_field = "uuid"

0
ram/driver/__init__.py Normal file
View File

29
ram/driver/admin.py Normal file
View File

@@ -0,0 +1,29 @@
from django.contrib import admin
from solo.admin import SingletonModelAdmin
from driver.models import DriverConfiguration
@admin.register(DriverConfiguration)
class DriverConfigurationAdmin(SingletonModelAdmin):
fieldsets = (
(
"Remote DCC-EX configuration",
{
"fields": (
"remote_host",
"remote_port",
"timeout",
)
},
),
(
"Firewall setting",
{
"fields": (
"network",
"subnet_mask",
)
},
),
)

12
ram/driver/apps.py Normal file
View File

@@ -0,0 +1,12 @@
from django.apps import AppConfig
from health_check.plugins import plugin_dir
class DriverConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "driver"
def ready(self):
from driver.health import DriverHealthCheck
plugin_dir.register(DriverHealthCheck)

53
ram/driver/connector.py Normal file
View File

@@ -0,0 +1,53 @@
import socket
from driver.models import DriverConfiguration
class Connector:
def __init__(self):
self.config = DriverConfiguration.get_solo()
def __send_data(self, message):
resp = b""
# convert to binary if str is received
if isinstance(message, str):
message = message.encode()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((self.config.remote_host, self.config.remote_port))
sock.settimeout(self.config.timeout / 1000) # milliseconds
sock.sendall(message)
while True:
try:
resp += sock.recv(1024)
except socket.timeout:
break
return resp
def passthrough(self, data):
return self.__send_data(data)
def ops(self, address, data, function=False):
if function:
message = "<F {0} {1} {2}>".format(
address, data["function"], data["state"]
)
else:
message = "<t 1 {0} {1} {2}>".format(
address, data["speed"], data["direction"]
)
self.__send_data(message)
def infra(self, data):
if "track" in data:
track = " {}".format(data["track"].upper())
else:
track = ""
if data["power"]:
self.__send_data("<1{}>".format(track))
else:
self.__send_data("<0{}>".format(track))
def emergency(self):
self.__send_data("<!>")

22
ram/driver/health.py Normal file
View File

@@ -0,0 +1,22 @@
from health_check.backends import BaseHealthCheckBackend
from health_check.exceptions import (
ServiceUnavailable,
ServiceReturnedUnexpectedResult,
)
from driver.connector import Connector
class DriverHealthCheck(BaseHealthCheckBackend):
critical_service = False
def check_status(self):
try:
Connector().passthrough(b"<s>")
except ConnectionRefusedError as e:
self.add_error(ServiceUnavailable("IOError"), e)
except Exception as e:
self.add_error(ServiceReturnedUnexpectedResult("IOError"), e)
def identifier(self):
return "DriverDaemon"

View File

@@ -0,0 +1,26 @@
# Generated by Django 4.0.3 on 2022-04-07 09:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DriverConfiguration',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('remote_host', models.GenericIPAddressField(default='192.168.4.1', protocol='IPv4')),
('remote_port', models.SmallIntegerField(default=2560)),
('timeout', models.SmallIntegerField(default=250)),
],
options={
'verbose_name': 'Configuration',
},
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 4.0.3 on 2022-04-10 15:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('driver', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='driverconfiguration',
name='network',
field=models.GenericIPAddressField(default='192.168.4.0', protocol='IPv4'),
),
migrations.AddField(
model_name='driverconfiguration',
name='subnet_mask',
field=models.GenericIPAddressField(default='255.255.255.0', protocol='IPv4'),
),
]

View File

@@ -0,0 +1,28 @@
# Generated by Django 4.0.3 on 2022-04-10 16:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('driver', '0002_driverconfiguration_network_and_more'),
]
operations = [
migrations.AlterField(
model_name='driverconfiguration',
name='network',
field=models.GenericIPAddressField(blank=True, default='192.168.4.0', null=True, protocol='IPv4'),
),
migrations.AlterField(
model_name='driverconfiguration',
name='remote_host',
field=models.GenericIPAddressField(blank=True, default='192.168.4.1', null=True, protocol='IPv4'),
),
migrations.AlterField(
model_name='driverconfiguration',
name='subnet_mask',
field=models.GenericIPAddressField(blank=True, default='255.255.255.0', null=True, protocol='IPv4'),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-04-10 16:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('driver', '0003_alter_driverconfiguration_network_and_more'),
]
operations = [
migrations.AlterField(
model_name='driverconfiguration',
name='remote_host',
field=models.GenericIPAddressField(default='192.168.4.1', protocol='IPv4'),
),
]

View File

41
ram/driver/models.py Normal file
View File

@@ -0,0 +1,41 @@
from django.db import models
from django.core.exceptions import ValidationError
from ipaddress import IPv4Address, IPv4Network
from solo.models import SingletonModel
class DriverConfiguration(SingletonModel):
remote_host = models.GenericIPAddressField(
protocol="IPv4",
default="192.168.4.1"
)
remote_port = models.SmallIntegerField(default=2560)
timeout = models.SmallIntegerField(default=250)
network = models.GenericIPAddressField(
protocol="IPv4",
default="192.168.4.0",
blank=True,
null=True
)
subnet_mask = models.GenericIPAddressField(
protocol="IPv4",
default="255.255.255.0",
blank=True,
null=True
)
def __str__(self):
return "Configuration"
def clean(self, *args, **kwargs):
if self.network:
try:
IPv4Network(
"{0}/{1}".format(self.network, self.subnet_mask))
except ValueError as e:
raise ValidationError(e)
super().clean(*args, **kwargs)
class Meta:
verbose_name = "Configuration"

19
ram/driver/serializers.py Normal file
View File

@@ -0,0 +1,19 @@
from rest_framework import serializers
class FunctionSerializer(serializers.Serializer):
function = serializers.IntegerField(required=True)
state = serializers.IntegerField(required=True)
class CabSerializer(serializers.Serializer):
speed = serializers.IntegerField(required=True)
direction = serializers.IntegerField(required=True)
class InfraSerializer(serializers.Serializer):
power = serializers.BooleanField(required=True)
track = serializers.ChoiceField(
choices=("main", "prog", "join", "MAIN", "PROG", "JOIN"),
required=False,
)

3
ram/driver/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

11
ram/driver/urls.py Normal file
View File

@@ -0,0 +1,11 @@
from django.urls import path
from driver.views import SendCommand, Function, Cab, Emergency, Infra, Test
urlpatterns = [
path("test", Test.as_view()),
path("emergency", Emergency.as_view()),
path("infra", Infra.as_view()),
path("command", SendCommand.as_view()),
path("<int:address>/cab", Cab.as_view()),
path("<int:address>/function", Function.as_view()),
]

162
ram/driver/views.py Normal file
View File

@@ -0,0 +1,162 @@
from ipaddress import IPv4Address, IPv4Network
from django.http import Http404
from django.utils.decorators import method_decorator
from rest_framework import status, serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import (
IsAuthenticated,
BasePermission,
SAFE_METHODS
)
from ram.parsers import PlainTextParser
from driver.models import DriverConfiguration
from driver.connector import Connector
from driver.serializers import (
FunctionSerializer,
CabSerializer,
InfraSerializer,
)
from roster.models import RollingStock
def addresschecker(f):
"""
Check if DCC address does exist in the database
"""
def addresslookup(request, address, *args):
if not RollingStock.objects.filter(address=address):
raise Http404
return f(request, address, *args)
return addresslookup
class Firewall(BasePermission):
def has_permission(self, request, view):
config = DriverConfiguration.get_solo()
if not config.network:
return request.method in SAFE_METHODS
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = IPv4Address(x_forwarded_for.split(',')[0])
else:
ip = IPv4Address(request.META.get("REMOTE_ADDR"))
network = IPv4Network("{0}/{1}".format(
config.network,
config.subnet_mask
))
# accept IP configured is settings or localhost
if ip in network or ip in IPv4Network("127.0.0.0/8"):
return request.method in SAFE_METHODS
class Test(APIView):
"""
Send a test <s> command
"""
parser_classes = [PlainTextParser]
permission_classes = [IsAuthenticated | Firewall]
def get(self, request):
response = Connector().passthrough("<s>")
return Response(
{"response": response.decode()}, status=status.HTTP_202_ACCEPTED
)
class SendCommand(APIView):
"""
Command passthrough
"""
parser_classes = [PlainTextParser]
permission_classes = [IsAuthenticated | Firewall]
def put(self, request):
data = request.data
if not data:
raise serializers.ValidationError(
{"error": "a string is expected"}
)
cmd = data.decode().strip()
if not (cmd.startswith("<") and cmd.endswith(">")):
raise serializers.ValidationError(
{"error": "please provide a valid command"}
)
response = Connector().passthrough(cmd)
return Response(
{"response": response.decode()}, status=status.HTTP_202_ACCEPTED
)
@method_decorator(addresschecker, name="put")
class Function(APIView):
"""
Send "Function" commands to a valid DCC address
"""
permission_classes = [IsAuthenticated | Firewall]
def put(self, request, address):
serializer = FunctionSerializer(data=request.data)
if serializer.is_valid():
Connector().ops(address, serializer.data, function=True)
return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@method_decorator(addresschecker, name="put")
class Cab(APIView):
"""
Send "Cab" commands to a valid DCC address
"""
permission_classes = [IsAuthenticated | Firewall]
def put(self, request, address):
serializer = CabSerializer(data=request.data)
if serializer.is_valid():
Connector().ops(address, serializer.data)
return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Infra(APIView):
"""
Send "Infra" commands to a valid DCC address
"""
permission_classes = [IsAuthenticated | Firewall]
def put(self, request):
serializer = InfraSerializer(data=request.data)
if serializer.is_valid():
Connector().infra(serializer.data)
return Response(serializer.data, status=status.HTTP_202_ACCEPTED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Emergency(APIView):
"""
Send an "Emergency" stop, no matter the HTTP method used
"""
permission_classes = [IsAuthenticated | Firewall]
def put(self, request):
Connector().emergency()
return Response(
{"response": "emergency stop"}, status=status.HTTP_202_ACCEPTED
)
def get(self, request):
Connector().emergency()
return Response(
{"response": "emergency stop"}, status=status.HTTP_202_ACCEPTED
)

22
ram/manage.py Executable file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ram.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

0
ram/metadata/__init__.py Normal file
View File

60
ram/metadata/admin.py Normal file
View File

@@ -0,0 +1,60 @@
from django.contrib import admin
from metadata.models import (
Property,
Decoder,
Scale,
Manufacturer,
Company,
Tag,
RollingStockType,
)
@admin.register(Property)
class PropertyAdmin(admin.ModelAdmin):
search_fields = ("name",)
@admin.register(Decoder)
class DecoderAdmin(admin.ModelAdmin):
readonly_fields = ("image_thumbnail",)
list_display = ("__str__", "interface")
list_filter = ("manufacturer", "interface")
search_fields = ("__str__",)
@admin.register(Scale)
class ScaleAdmin(admin.ModelAdmin):
list_display = ("scale", "ratio", "gauge")
list_filter = ("ratio", "gauge")
search_fields = list_display
@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
readonly_fields = ("logo_thumbnail",)
list_display = ("name", "country")
list_filter = list_display
search_fields = ("name",)
@admin.register(Manufacturer)
class ManufacturerAdmin(admin.ModelAdmin):
readonly_fields = ("logo_thumbnail",)
list_display = ("name", "category")
list_filter = ("category",)
search_fields = ("name",)
@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
readonly_fields = ("slug",)
list_display = ("name", "slug")
search_fields = ("name",)
@admin.register(RollingStockType)
class RollingStockTypeAdmin(admin.ModelAdmin):
list_display = ("__str__",)
list_filter = ("type", "category")
search_fields = list_display

6
ram/metadata/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class MetadataConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "metadata"

View File

@@ -0,0 +1,98 @@
# Generated by Django 4.0.3 on 2022-04-07 09:25
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Company',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64, unique=True)),
('extended_name', models.CharField(blank=True, max_length=128)),
('country', django_countries.fields.CountryField(max_length=2)),
('freelance', models.BooleanField(default=False)),
('logo', models.ImageField(blank=True, null=True, upload_to='images/')),
],
options={
'verbose_name_plural': 'Companies',
'ordering': ['name'],
},
),
migrations.CreateModel(
name='Manufacturer',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, unique=True)),
('category', models.CharField(choices=[('model', 'Model'), ('real', 'Real')], max_length=64)),
('website', models.URLField(blank=True)),
('logo', models.ImageField(blank=True, null=True, upload_to='images/')),
],
options={
'ordering': ['category', 'name'],
},
),
migrations.CreateModel(
name='Property',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, unique=True)),
],
options={
'verbose_name_plural': 'Properties',
'ordering': ['name'],
},
),
migrations.CreateModel(
name='Scale',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('scale', models.CharField(max_length=32, unique=True)),
('ratio', models.CharField(blank=True, max_length=16)),
('gauge', models.CharField(blank=True, max_length=16)),
],
options={
'ordering': ['scale'],
},
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, unique=True)),
('slug', models.CharField(max_length=128, unique=True)),
],
),
migrations.CreateModel(
name='RollingStockType',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(max_length=64)),
('category', models.CharField(choices=[('engine', 'Engine'), ('car', 'Car'), ('railcar', 'Railcar'), ('equipment', 'Equipment'), ('other', 'Other')], max_length=64)),
],
options={
'unique_together': {('category', 'type')},
},
),
migrations.CreateModel(
name='Decoder',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=128, unique=True)),
('version', models.CharField(blank=True, max_length=64)),
('interface', models.PositiveSmallIntegerField(blank=True, choices=[(1, 'NEM651'), (2, 'NEM652'), (3, 'PluX'), (4, '21MTC'), (5, 'Next18/Next18S')], null=True)),
('sound', models.BooleanField(default=False)),
('image', models.ImageField(blank=True, null=True, upload_to='images/')),
('manufacturer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='metadata.manufacturer')),
],
),
]

View File

114
ram/metadata/models.py Normal file
View File

@@ -0,0 +1,114 @@
from django.db import models
from django.conf import settings
from django.dispatch.dispatcher import receiver
from django_countries.fields import CountryField
from ram.utils import get_image_preview, slugify
class Property(models.Model):
name = models.CharField(max_length=128, unique=True)
class Meta:
verbose_name_plural = "Properties"
ordering = ["name"]
def __str__(self):
return self.name
class Manufacturer(models.Model):
name = models.CharField(max_length=128, unique=True)
category = models.CharField(
max_length=64, choices=settings.MANUFACTURER_TYPES
)
website = models.URLField(blank=True)
logo = models.ImageField(upload_to="images/", null=True, blank=True)
class Meta:
ordering = ["category", "name"]
def __str__(self):
return self.name
def logo_thumbnail(self):
return get_image_preview(self.logo.url)
logo_thumbnail.short_description = "Preview"
class Company(models.Model):
name = models.CharField(max_length=64, unique=True)
extended_name = models.CharField(max_length=128, blank=True)
country = CountryField()
freelance = models.BooleanField(default=False)
logo = models.ImageField(upload_to="images/", null=True, blank=True)
class Meta:
verbose_name_plural = "Companies"
ordering = ["name"]
def __str__(self):
return self.name
def logo_thumbnail(self):
return get_image_preview(self.logo.url)
logo_thumbnail.short_description = "Preview"
class Decoder(models.Model):
name = models.CharField(max_length=128, unique=True)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
version = models.CharField(max_length=64, blank=True)
interface = models.PositiveSmallIntegerField(
choices=settings.DECODER_INTERFACES, null=True, blank=True
)
sound = models.BooleanField(default=False)
image = models.ImageField(upload_to="images/", null=True, blank=True)
def __str__(self):
return "{0} - {1}".format(self.manufacturer, self.name)
def image_thumbnail(self):
return get_image_preview(self.image.url)
image_thumbnail.short_description = "Preview"
class Scale(models.Model):
scale = models.CharField(max_length=32, unique=True)
ratio = models.CharField(max_length=16, blank=True)
gauge = models.CharField(max_length=16, blank=True)
class Meta:
ordering = ["scale"]
def __str__(self):
return str(self.scale)
class Tag(models.Model):
name = models.CharField(max_length=128, unique=True)
slug = models.CharField(max_length=128, unique=True)
def __str__(self):
return self.name
@receiver(models.signals.pre_save, sender=Tag)
def tag_pre_save(sender, instance, **kwargs):
instance.slug = slugify(instance.name)
class RollingStockType(models.Model):
type = models.CharField(max_length=64)
category = models.CharField(
max_length=64, choices=settings.ROLLING_STOCK_TYPES
)
class Meta(object):
unique_together = ("category", "type")
def __str__(self):
return "{0} {1}".format(self.type, self.category)

View File

@@ -0,0 +1,47 @@
from rest_framework import serializers
from metadata.models import (
RollingStockType,
Scale,
Manufacturer,
Company,
Decoder,
Tag,
)
class RollingStockTypeSerializer(serializers.ModelSerializer):
class Meta:
model = RollingStockType
fields = "__all__"
class ManufacturerSerializer(serializers.ModelSerializer):
class Meta:
model = Manufacturer
fields = "__all__"
class ScaleSerializer(serializers.ModelSerializer):
class Meta:
model = Scale
fields = "__all__"
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = "__all__"
class DecoderSerializer(serializers.ModelSerializer):
manufacturer = serializers.StringRelatedField()
class Meta:
model = Decoder
fields = "__all__"
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = "__all__"

3
ram/metadata/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

3
ram/metadata/views.py Normal file
View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

0
ram/portal/__init__.py Normal file
View File

6
ram/portal/admin.py Normal file
View File

@@ -0,0 +1,6 @@
from django.contrib import admin
from solo.admin import SingletonModelAdmin
from portal.models import SiteConfiguration
admin.site.register(SiteConfiguration, SingletonModelAdmin)

6
ram/portal/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class PortalConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'portal'

View File

@@ -0,0 +1,32 @@
# Generated by Django 4.0.3 on 2022-04-08 22:00
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SiteConfiguration',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('site_name', models.CharField(default='Map viewer', max_length=256)),
('site_author', models.CharField(blank=True, max_length=256)),
('about', models.TextField(blank=True)),
('maps_per_page', models.CharField(choices=[('6', '6'), ('9', '9'), ('12', '12'), ('15', '15'), ('18', '18'), ('21', '21'), ('24', '24'), ('27', '27'), ('30', '30')], default='6', max_length=2)),
('homepage_content', models.TextField(blank=True)),
('footer', models.TextField(blank=True)),
('footer_short', models.TextField(blank=True)),
('show_copyright', models.BooleanField(default=True)),
('show_version', models.BooleanField(default=True)),
],
options={
'verbose_name': 'Site Configuration',
},
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-04-08 22:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portal', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='siteconfiguration',
name='site_name',
field=models.CharField(default='Trains assets manager', max_length=256),
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-04-09 20:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portal', '0002_alter_siteconfiguration_site_name'),
]
operations = [
migrations.RenameField(
model_name='siteconfiguration',
old_name='maps_per_page',
new_name='items_per_page',
),
]

View File

@@ -0,0 +1,22 @@
# Generated by Django 4.0.3 on 2022-04-09 20:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portal', '0003_rename_maps_per_page_siteconfiguration_items_per_page'),
]
operations = [
migrations.RenameField(
model_name='siteconfiguration',
old_name='footer_short',
new_name='footer_extended',
),
migrations.RemoveField(
model_name='siteconfiguration',
name='show_copyright',
),
]

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.0.3 on 2022-04-09 21:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portal', '0004_rename_footer_short_siteconfiguration_footer_extended_and_more'),
]
operations = [
migrations.RemoveField(
model_name='siteconfiguration',
name='homepage_content',
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-04-10 17:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portal', '0005_remove_siteconfiguration_homepage_content'),
]
operations = [
migrations.AlterField(
model_name='siteconfiguration',
name='site_name',
field=models.CharField(default='Railroad Assets Manager', max_length=256),
),
]

View File

33
ram/portal/models.py Normal file
View File

@@ -0,0 +1,33 @@
import django
from django.db import models
from ram import __version__ as app_version
from solo.models import SingletonModel
class SiteConfiguration(SingletonModel):
site_name = models.CharField(
max_length=256,
default="Railroad Assets Manager")
site_author = models.CharField(max_length=256, blank=True)
about = models.TextField(blank=True)
items_per_page = models.CharField(
max_length=2, choices=[
(str(x * 3), str(x * 3)) for x in range(2, 11)],
default='6'
)
footer = models.TextField(blank=True)
footer_extended = models.TextField(blank=True)
show_version = models.BooleanField(default=True)
class Meta:
verbose_name = "Site Configuration"
def __str__(self):
return "Site Configuration"
def version(self):
return app_version
def django_version(self):
return django.get_version()

View File

@@ -0,0 +1,11 @@
.card > a > img {
width: 100%;
}
.btn > span {
display: inline-block;
}
#footer > p {
display: inline;
}

View File

@@ -0,0 +1,75 @@
{% load static %}
{% load breadcrumbs %}
{% load solo_tags %}
{% get_solo 'portal.SiteConfiguration' as site_conf %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="{{ site_conf.about }}">
<meta name="author" content="{{ site_conf.site_author }}">
<link rel="icon" type="image/png" href="{% static 'favicon-196x196.png' %}" sizes="196x196">
<link rel="icon" type="image/png" href="{% static 'favicon-128.png' %}" sizes="128x128">
<link rel="icon" type="image/png" href="{% static 'favicon-96x96.png' %}" sizes="96x96">
<link rel="icon" type="image/png" href="{% static 'favicon-32x32.png' %}" sizes="32x32">
<link rel="icon" type="image/png" href="{% static 'favicon-16x16.png' %}" sizes="16x16">
<title>{{ site_conf.site_name }} - {{ page.name }}</title>
<!-- Bootstrap core CSS -->
<link href="{% static "css/dist/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/fonts.css" %}" rel="stylesheet">
<link href="{% static "css/main.css" %}" rel="stylesheet">
{% if site_conf.common_css %}<link rel="stylesheet" href="{{ site_conf.common_css.url }}">{% endif %}
</head>
<body class="bg-dark">
<div class="container-fluid h-100 d-flex flex-column">
<header>
{% include 'navbar.html' %}
<div class="row collapse bg-dark shadow-sm" id="navbarHeader">
<div class="container">
<div class="row">
<div class="col-sm-8 col-md-7 py-4">
{% if site_conf.about %}<h4 class="text-white">About</h4>
<p class="text-muted">{{ site_conf.about | safe }}</p>{% endif %}
{% breadcrumbs page.path %}
</div>
<div class="col-sm-4 offset-md-1 py-4 text-right">
{% if request.user.is_staff %}<div class="dropdown btn-group">
<button class="btn btn-sm btn-outline-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Edit
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="{% url 'admin:portal_flatpage_change' page.pk %}">Edit page</a>
<a class="dropdown-item" href="{% url 'admin:portal_flatpage_history' page.pk %}">History</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-danger" href="{% url 'admin:portal_flatpage_delete' page.pk %}">Delete</a>
</div>
</div>{% endif %}
{% include 'login.html' %}
</div>
</div>
</div>
</div>
</header>
</div>
<main>
<div class="album py-5 bg-white">
<div class="container">
{{ content }}
</div>
</div>
</main>
{% include 'footer.html' %}
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="{% static "js/dist/jquery.min.js" %}"></script>
<script src="{% static "js/dist/bootstrap.bundle.min.js" %}"></script>
</body>
</html>

View File

@@ -0,0 +1,20 @@
{% load markdown %}
<footer class="text-muted py-5">
<div class="container">
<p class="float-end mb-1">
<a href="#">Back to top</a>
</p>
<div id="footer" class="mb-1">
<p>&copy; {% now "Y" %}</p> {{ site_conf.footer | markdown | safe }}
</div>
<div id="footer_extended" class="mb-0">
{{ site_conf.footer_extended | markdown | safe }}
</div>
</div>
{% if site_conf.show_version %}
<div class="container">
<p class="small text-muted">Version: {{ site_conf.version }}</p>
</div>
{% endif %}
</footer>

View File

@@ -0,0 +1,216 @@
{% load static %}
{% load solo_tags %}
{% load markdown %}
{% get_solo 'portal.SiteConfiguration' as site_conf %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.88.1">
<title>{{ site_conf.site_name }}</title>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/album/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="{% static "css/main.css" %}" rel="stylesheet">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
@media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
</head>
<body>
<header>
<div class="navbar navbar-dark bg-dark shadow-sm">
<div class="container">
<a href="#" class="navbar-brand d-flex align-items-center">
<svg class="me-2" width="26" height="16" enable-background="new 0 0 26 26" version="1" viewBox="0 0 26 16" xmlns="http://www.w3.org/2000/svg">
<path d="m2.8125 0.0010991a1.0001 1.0001 0 0 0-0.8125 1c0 0.55455-0.44545 1-1 1a1.0001 1.0001 0 0 0-1 1v10a1.0001 1.0001 0 0 0 1 1c0.55455 0 1 0.44546 1 1a1.0001 1.0001 0 0 0 1 1h20a1.0001 1.0001 0 0 0 1-1c0-0.55454 0.44546-1 1-1a1.0001 1.0001 0 0 0 1-1v-10a1.0001 1.0001 0 0 0-1-1c-0.55454 0-1-0.44545-1-1a1.0001 1.0001 0 0 0-1-1h-20a1.0001 1.0001 0 0 0-0.09375 0 1.0001 1.0001 0 0 0-0.09375 0zm0.78125 2h14.406v1h2v-1h2.4062c0.30628 0.76906 0.82469 1.2875 1.5938 1.5938v8.8125c-0.76906 0.30628-1.2875 0.82469-1.5938 1.5938h-2.4062v-1h-2v1h-14.406c-0.30628-0.76906-0.82469-1.2875-1.5938-1.5938v-8.8125c0.76906-0.30628 1.2875-0.82469 1.5938-1.5938zm14.406 2v2h2v-2zm0 3v2h2v-2zm0 3v2h2v-2z" enable-background="accumulate" fill="#fff" overflow="visible" stroke-width="2" style="text-indent:0;text-transform:none"/>
</svg>
<strong>{{ site_conf.site_name }}</strong>
</a>
{% include 'login.html' %}
</div>
</div>
</header>
<main>
<section class="py-1 text-start container">
<div class="row py-lg-5">
<div class="mx-auto">
<h1 class="fw-light">About</h1>
<p class="lead text-muted">{{ site_conf.about | markdown | safe }}</p>
</div>
</div>
</section>
<div class="album py-5 bg-light">
<div class="container">
<a id="rolling-stock"></a>
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">
{% for r in rolling_stock %}
<div class="col">
<div class="card shadow-sm">
<a href="#">
{% for t in r.thumbnail.all %}{% if t.is_thumbnail %}<img src="{{ t.image.url }}" alt="Card image cap">
{% else %}
<svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Missing thumbnail</text></svg>
{% endif %}</a>{% endfor %}
<div class="card-body">
<p class="card-text"><strong>{{ r }}</strong></p>
<table class="table table-striped">
<thead>
<tr>
<th colspan="2" scope="row">Data</th>
</tr>
</thead>
<tbody>
<tr>
<th width="35%" scope="row">Type</th>
<td>{{ r.rolling_class.type }}</td>
</tr>
<tr>
<th scope="row">Company</th>
<td>{{ r.rolling_class.company }}</td>
</tr>
<tr>
<th scope="row">Class</th>
<td>{{ r.rolling_class.identifier }}</td>
</tr>
<tr>
<th scope="row">Road number</th>
<td>{{ r.road_number }}</td>
</tr>
<tr>
<th scope="row">Era</th>
<td>{{ r.era }}</td>
</tr>
</tbody>
</table>
<div class="btn-group mb-4">
<button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="button"><span data-bs-toggle="collapse" data-bs-target="#collapseModel{{ r.pk }}" aria-expanded="false" aria-controls="collapseModel{{ r.pk }}">Model data</span></button>
{% if r.decoder %}
<button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="button"> <span data-bs-toggle="collapse" data-bs-target="#collapseDCC{{ r.pk }}" aria-expanded="false" aria-controls="collapseDCC{{ r.pk }}">DCC data</span></button>
{% endif %}
<a class="btn btn-sm btn-outline-primary" href="#">Show all data</a>
{% if request.user.is_staff %}<a class="btn btn-sm btn-outline-danger" href="{% url 'admin:roster_rollingstock_change' r.pk %}">Edit</a>{% endif %}
</div>
<div class="collapse" id="collapseModel{{ r.pk }}">
<table class="table table-striped">
<thead>
<tr>
<th colspan="2" scope="row">Model data</th>
</tr>
</thead>
<tbody>
<tr>
<th width="35%" scope="row">Manufacturer</th>
<td>{{ r.manufacturer }}</td>
</tr>
<tr>
<th scope="row">Scale</th>
<td>{{ r.scale }}</td>
</tr>
<tr>
<th scope="row">SKU</th>
<td>{{ r.sku }}</td>
</tr>
</tbody>
</table>
</div>
{% if r.decoder %}
<div class="collapse" id="collapseDCC{{ r.pk }}">
<table class="table table-striped">
<thead>
<tr>
<th colspan="2" scope="row">DCC data</th>
</tr>
</thead>
<tbody>
<tr>
<th width="35%" scope="row">Decoder</th>
<td>{{ r.decoder }}</td>
</tr>
<tr>
<th scope="row">Address</th>
<td>{{ r.address }}</td>
</tr>
</tbody>
</table>
</div>
{% endif %}
{% if r.tags.all %}
<p class="card-text"><small>Tags:</small>
{% for t in r.tags.all %}<span class="badge bg-primary">
{{ t.name }}</span>{# new line is required #}
{% endfor %}
{% endif %}
</p>
<div class="d-flex justify-content-between align-items-center">
<small class="text-muted">Updated {{ r.updated_time | date:"M d, Y H:m" }}</small>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<div class="container">
{% if rolling_stock.has_other_pages %}
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center mt-4">
{% if rolling_stock.has_previous %}
<li class="page-item">
<a class="page-link" href="/page/{{ rolling_stock.previous_page_number }}#rolling_stock" tabindex="-1">Previous</a>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link">Previous</span>
</li>
{% endif %}
{% for i in rolling_stock.paginator.page_range %}
{% if rolling_stock.number == i %}
<li class="page-item active">
<span class="page-link">{{ i }}</span></span>
</li>
{% else %}
<li class="page-item"><a class="page-link" href="/page/{{ i }}#rolling-stock">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if rolling_stock.has_next %}
<li class="page-item">
<a class="page-link" href="/page/{{ rolling_stock.next_page_number }}#rolling-stock" tabindex="-1">Next</a>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link">Next</span>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</div>
</div>
</div>
</main>
{% include 'footer.html' %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@@ -0,0 +1,20 @@
{% if request.user.is_staff %}
<div class="dropdown">
<button class="btn btn-sm btn-outline-light dropdown-toggle" type="button" id="dropdownMenu2" data-bs-toggle="dropdown" aria-expanded="false">
Welcome back, <strong>{{ request.user }}</strong>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenu2">
<li><a class="dropdown-item" href="{% url 'admin:roster_rollingstock_changelist' %}">Rolling stock</a></li>
<li><a class="dropdown-item" href="{% url 'admin:consist_consist_changelist' %}">Consists</a></li>
<li><a class="dropdown-item" href="{% url 'admin:app_list' 'metadata' %}">Metadata</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{% url 'admin:index' %}">Admin</a></li>
<li><a class="dropdown-item" href="{% url 'admin:portal_siteconfiguration_changelist' %}">Site configuration</a></li>
<li><a class="dropdown-item" href="{% url 'admin:driver_driverconfiguration_changelist' %}">DCC configuration</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item text-danger" href="{% url 'admin:logout' %}?next={{ request.path }}">Logout</a></li>
</ul>
</div>
{% else %}
<a class="btn btn-sm btn-outline-light" href="{% url 'admin:login' %}?next={{ request.path }}">Log in</a>
{% endif %}

View File

View File

@@ -0,0 +1,12 @@
from django import template
from django.template.defaultfilters import stringfilter
import markdown as md
register = template.Library()
@register.filter
@stringfilter
def markdown(value):
return md.markdown(value, extensions=['markdown.extensions.fenced_code'])

3
ram/portal/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

7
ram/portal/urls.py Normal file
View File

@@ -0,0 +1,7 @@
from django.urls import path
from portal.views import GetHome
urlpatterns = [
path("<int:page>", GetHome.as_view(), name='index_pagination'),
]

6
ram/portal/utils.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import apps
def get_site_conf():
SiteConfiguration = apps.get_model('portal', 'SiteConfiguration')
return SiteConfiguration.get_solo()

26
ram/portal/views.py Normal file
View File

@@ -0,0 +1,26 @@
from django.views import View
from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from portal.utils import get_site_conf
from roster.models import RollingStock, RollingStockImage
class GetHome(View):
def get(self, request, page=1):
site_conf = get_site_conf()
rolling_stock = RollingStock.objects.all()
thumbnails = RollingStockImage.objects.filter(is_thumbnail=True)
paginator = Paginator(rolling_stock, site_conf.items_per_page)
try:
rolling_stock = paginator.page(page)
except PageNotAnInteger:
rolling_stock = paginator.page(1)
except EmptyPage:
rolling_stock = paginator.page(paginator.num_pages)
return render(request, 'home.html', {
'rolling_stock': rolling_stock,
'thumbnails': thumbnails
})

4
ram/ram/__init__.py Normal file
View File

@@ -0,0 +1,4 @@
from ram.utils import git_suffix
__version__ = '0.0.1'
__version__ += git_suffix(__file__)

16
ram/ram/asgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
ASGI config for ram project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ram.settings")
application = get_asgi_application()

8
ram/ram/parsers.py Normal file
View File

@@ -0,0 +1,8 @@
from rest_framework.parsers import BaseParser
class PlainTextParser(BaseParser):
media_type = "text/plain"
def parse(self, stream, media_type=None, parser_context=None):
return stream.read()

166
ram/ram/settings.py Normal file
View File

@@ -0,0 +1,166 @@
"""
Django settings for ram project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STORAGE_DIR = BASE_DIR / "storage"
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = (
"django-insecure-1fgtf05rwp0qp05@ef@a7%x#o+t6vk6063py=vhdmut0j!8s4u"
)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"health_check",
"health_check.db",
"django_countries",
"solo",
"rest_framework",
"adminsortable2",
"ram",
"portal",
"driver",
"metadata",
"roster",
"consist",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
# 'django.middleware.csrf.CsrfViewMiddleware',
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "ram.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "ram.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": STORAGE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
MEDIA_URL = "media/"
MEDIA_ROOT = STORAGE_DIR / "media"
COUNTRIES_OVERRIDE = {
"ZZ": "Freelance",
}
DECODER_INTERFACES = [
(1, "NEM651"),
(2, "NEM652"),
(3, "PluX"),
(4, "21MTC"),
(5, "Next18/Next18S"),
]
MANUFACTURER_TYPES = [
("model", "Model"),
("real", "Real")
]
ROLLING_STOCK_TYPES = [
("engine", "Engine"),
("car", "Car"),
("railcar", "Railcar"),
("equipment", "Equipment"),
("other", "Other"),
]

51
ram/ram/urls.py Normal file
View File

@@ -0,0 +1,51 @@
"""ram URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from portal.utils import get_site_conf
from portal.views import GetHome
site_conf = get_site_conf()
admin.site.site_header = site_conf.site_name
urlpatterns = [
path("", GetHome.as_view(), name="index"),
path("page/", include("portal.urls")),
path("ht/", include("health_check.urls")),
path("admin/", admin.site.urls),
path("api/v1/consist/", include("consist.urls")),
path("api/v1/roster/", include("roster.urls")),
path("api/v1/dcc/", include("driver.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# if settings.DEBUG:
# from django.views.generic import TemplateView
# from rest_framework.schemas import get_schema_view
#
# urlpatterns += [
# path('swagger/', TemplateView.as_view(
# template_name='swagger.html',
# extra_context={'schema_url': 'openapi-schema'}
# ), name='swagger'),
# path('openapi', get_schema_view(
# title="BITE - A Basic/IoT/Example",
# description="BITE API for IoT",
# version="1.0.0"
# ), name='openapi-schema'),
# ]

37
ram/ram/utils.py Normal file
View File

@@ -0,0 +1,37 @@
import os
import subprocess
from django.utils.html import format_html
from django.utils.text import slugify as django_slugify
def git_suffix(fname):
"""
:returns: `<short git hash>` if Git repository found
"""
try:
gh = subprocess.check_output(
['git', 'rev-parse', '--short', 'HEAD'],
stderr=open(os.devnull, 'w')).strip()
gh = "-git" + gh.decode() if gh else ''
except Exception:
# trapping everything on purpose; git may not be installed or it
# may not work properly
gh = ''
return gh
def get_image_preview(url):
return format_html(
'<img src="%s" style="max-width: 150px; max-height: 150px;'
'background-color: #eee;" />' % url
)
def slugify(string, custom_separator=None):
# Make slug 'flat', both '-' and '_' are replaced with '-'
string = django_slugify(string).replace("_", "-")
if custom_separator is not None:
string = string.replace("-", custom_separator)
return string

16
ram/ram/wsgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
WSGI config for ram project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ram.settings")
application = get_wsgi_application()

0
ram/roster/__init__.py Normal file
View File

107
ram/roster/admin.py Normal file
View File

@@ -0,0 +1,107 @@
from django.contrib import admin
from roster.models import (
RollingClass,
RollingClassProperty,
RollingStock,
RollingStockImage,
RollingStockDocument,
RollingStockProperty,
)
class RollingClassPropertyInline(admin.TabularInline):
model = RollingClassProperty
min_num = 0
extra = 0
@admin.register(RollingClass)
class RollingClass(admin.ModelAdmin):
inlines = (RollingClassPropertyInline,)
list_display = ("__str__", "type", "company")
list_filter = ("company", "type__category", "type")
search_fields = list_display
class RollingStockDocInline(admin.TabularInline):
model = RollingStockDocument
min_num = 0
extra = 0
class RollingStockImageInline(admin.TabularInline):
model = RollingStockImage
min_num = 0
extra = 0
readonly_fields = ("image_thumbnail",)
class RollingStockPropertyInline(admin.TabularInline):
model = RollingStockProperty
min_num = 0
extra = 0
@admin.register(RollingStock)
class RollingStockAdmin(admin.ModelAdmin):
inlines = (
RollingStockPropertyInline,
RollingStockImageInline,
RollingStockDocInline,
)
readonly_fields = ("creation_time", "updated_time")
list_display = (
"__str__",
"address",
"manufacturer",
"scale",
"sku",
"company",
"country",
)
list_filter = (
"rolling_class__type__category",
"rolling_class__type",
"scale",
"manufacturer",
)
search_fields = list_display
fieldsets = (
(
None,
{
"fields": (
"rolling_class",
"road_number",
"scale",
"manufacturer",
"sku",
"era",
"production_year",
"purchase_date",
"notes",
"tags",
)
},
),
(
"DCC",
{
"fields": (
"decoder",
"address",
)
},
),
(
"Audit",
{
"classes": ("collapse",),
"fields": (
"creation_time",
"updated_time",
),
},
),
)

6
ram/roster/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class RosterConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "roster"

View File

@@ -0,0 +1,104 @@
# Generated by Django 4.0.3 on 2022-04-07 09:25
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('metadata', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='RollingClass',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('identifier', models.CharField(max_length=128)),
('description', models.CharField(blank=True, max_length=256)),
('company', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='metadata.company')),
('manufacturer', models.ForeignKey(blank=True, limit_choices_to={'category': 'real'}, null=True, on_delete=django.db.models.deletion.CASCADE, to='metadata.manufacturer')),
('type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='metadata.rollingstocktype')),
],
options={
'verbose_name': 'Class',
'verbose_name_plural': 'Classes',
'ordering': ['company', 'identifier'],
},
),
migrations.CreateModel(
name='RollingStock',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('road_number', models.CharField(max_length=128)),
('sku', models.CharField(blank=True, max_length=32)),
('address', models.SmallIntegerField(blank=True, default=None, null=True)),
('era', models.CharField(blank=True, max_length=32)),
('production_year', models.SmallIntegerField(blank=True, null=True)),
('purchase_date', models.DateField(blank=True, null=True)),
('notes', models.TextField(blank=True)),
('creation_time', models.DateTimeField(auto_now_add=True)),
('updated_time', models.DateTimeField(auto_now=True)),
('decoder', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='metadata.decoder')),
('manufacturer', models.ForeignKey(blank=True, limit_choices_to={'category': 'model'}, null=True, on_delete=django.db.models.deletion.CASCADE, to='metadata.manufacturer')),
('rolling_class', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='roster.rollingclass', verbose_name='Class')),
('scale', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='metadata.scale')),
('tags', models.ManyToManyField(blank=True, related_name='rolling_stock', to='metadata.tag')),
],
options={
'verbose_name_plural': 'Rolling stock',
'ordering': ['rolling_class', 'road_number'],
},
),
migrations.CreateModel(
name='RollingStockProperty',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', models.CharField(max_length=256)),
('property', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='metadata.property')),
('rolling_stock', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='roster.rollingstock')),
],
options={
'verbose_name_plural': 'Properties',
},
),
migrations.CreateModel(
name='RollingClassProperty',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', models.CharField(max_length=256)),
('property', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='metadata.property')),
('rolling_class', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='roster.rollingclass', verbose_name='Class')),
],
options={
'verbose_name_plural': 'Properties',
},
),
migrations.CreateModel(
name='RollingStockImage',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(blank=True, null=True, upload_to='images/')),
('rolling_stock', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='roster.rollingstock')),
],
options={
'unique_together': {('rolling_stock', 'image')},
},
),
migrations.CreateModel(
name='RollingStockDocument',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(blank=True, max_length=128)),
('file', models.FileField(blank=True, null=True, upload_to='files/')),
('rolling_stock', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='roster.rollingstock')),
],
options={
'unique_together': {('rolling_stock', 'file')},
},
),
]

View File

@@ -0,0 +1,23 @@
# Generated by Django 4.0.3 on 2022-04-08 21:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('roster', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='rollingstockimage',
unique_together=set(),
),
migrations.AddField(
model_name='rollingstockimage',
name='is_thumbnail',
field=models.BooleanField(default=False),
preserve_default=False,
),
]

View File

@@ -0,0 +1,19 @@
# Generated by Django 4.0.3 on 2022-04-08 22:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('roster', '0002_alter_rollingstockimage_unique_together_and_more'),
]
operations = [
migrations.AlterField(
model_name='rollingstockimage',
name='rolling_stock',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='thumbnail', to='roster.rollingstock'),
),
]

View File

168
ram/roster/models.py Normal file
View File

@@ -0,0 +1,168 @@
import os
from uuid import uuid4
from django.db import models
# from django.core.files.storage import FileSystemStorage
# from django.dispatch import receiver
from ram.utils import get_image_preview
from metadata.models import (
Property,
Scale,
Manufacturer,
Decoder,
Company,
Tag,
RollingStockType,
)
# class OverwriteMixin(FileSystemStorage):
# def get_available_name(self, name, max_length):
# self.delete(name)
# return name
class RollingClass(models.Model):
identifier = models.CharField(max_length=128, unique=False)
type = models.ForeignKey(
RollingStockType, on_delete=models.CASCADE, null=True, blank=True
)
company = models.ForeignKey(
Company, on_delete=models.CASCADE, null=True, blank=True
)
description = models.CharField(max_length=256, blank=True)
manufacturer = models.ForeignKey(
Manufacturer, on_delete=models.CASCADE, null=True, blank=True,
limit_choices_to={"category": "real"}
)
class Meta:
ordering = ["company", "identifier"]
verbose_name = "Class"
verbose_name_plural = "Classes"
def __str__(self):
return "{0} {1}".format(self.company, self.identifier)
class RollingClassProperty(models.Model):
rolling_class = models.ForeignKey(
RollingClass,
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name="Class",
)
property = models.ForeignKey(Property, on_delete=models.CASCADE)
value = models.CharField(max_length=256)
def __str__(self):
return self.property.name
class Meta:
verbose_name_plural = "Properties"
class RollingStock(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False)
rolling_class = models.ForeignKey(
RollingClass,
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name="Class",
)
road_number = models.CharField(max_length=128, unique=False)
manufacturer = models.ForeignKey(
Manufacturer, on_delete=models.CASCADE, null=True, blank=True,
limit_choices_to={"category": "model"}
)
scale = models.ForeignKey(Scale, on_delete=models.CASCADE)
sku = models.CharField(max_length=32, blank=True)
decoder = models.ForeignKey(
Decoder, on_delete=models.CASCADE, null=True, blank=True
)
address = models.SmallIntegerField(default=None, null=True, blank=True)
era = models.CharField(max_length=32, blank=True)
production_year = models.SmallIntegerField(null=True, blank=True)
purchase_date = models.DateField(null=True, blank=True)
notes = models.TextField(blank=True)
tags = models.ManyToManyField(
Tag, related_name="rolling_stock", blank=True
)
creation_time = models.DateTimeField(auto_now_add=True)
updated_time = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["rolling_class", "road_number"]
verbose_name_plural = "Rolling stock"
def __str__(self):
return "{0} {1}".format(self.rolling_class, self.road_number)
def country(self):
return str(self.rolling_class.company.country)
def company(self):
return str(self.rolling_class.company)
class RollingStockDocument(models.Model):
rolling_stock = models.ForeignKey(RollingStock, on_delete=models.CASCADE)
description = models.CharField(max_length=128, blank=True)
file = models.FileField(upload_to="files/", null=True, blank=True)
class Meta(object):
unique_together = ("rolling_stock", "file")
def __str__(self):
return "{0}".format(os.path.basename(self.file.name))
# return "{0}".format(self.description)
class RollingStockImage(models.Model):
rolling_stock = models.ForeignKey(
RollingStock,
on_delete=models.CASCADE,
related_name="thumbnail")
image = models.ImageField(upload_to="images/", null=True, blank=True)
is_thumbnail = models.BooleanField()
def image_thumbnail(self):
return get_image_preview(self.image.url)
image_thumbnail.short_description = "Preview"
def __str__(self):
return "{0}".format(os.path.basename(self.image.name))
def save(self, **kwargs):
if self.is_thumbnail:
RollingStockImage.objects.filter(
rolling_stock=self.rolling_stock).update(is_thumbnail=False)
super().save(**kwargs)
class RollingStockProperty(models.Model):
rolling_stock = models.ForeignKey(
RollingStock,
on_delete=models.CASCADE,
null=False,
blank=False
)
property = models.ForeignKey(Property, on_delete=models.CASCADE)
value = models.CharField(max_length=256)
def __str__(self):
return self.property.name
class Meta:
verbose_name_plural = "Properties"
# @receiver(models.signals.post_delete, sender=Cab)
# def post_save_image(sender, instance, *args, **kwargs):
# try:
# instance.image.delete(save=False)
# except Exception:
# pass

32
ram/roster/serializers.py Normal file
View File

@@ -0,0 +1,32 @@
from rest_framework import serializers
from roster.models import RollingClass, RollingStock
from metadata.serializers import (
RollingStockTypeSerializer,
ManufacturerSerializer,
ScaleSerializer,
CompanySerializer,
DecoderSerializer,
TagSerializer,
)
class RollingClassSerializer(serializers.ModelSerializer):
company = CompanySerializer()
type = RollingStockTypeSerializer()
class Meta:
model = RollingClass
fields = "__all__"
class RollingStockSerializer(serializers.ModelSerializer):
rolling_class = RollingClassSerializer()
manufacturer = ManufacturerSerializer()
decoder = DecoderSerializer()
scale = ScaleSerializer()
tags = TagSerializer(many=True)
class Meta:
model = RollingStock
fields = "__all__"
read_only_fields = ("creation_time", "updated_time")

3
ram/roster/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

9
ram/roster/urls.py Normal file
View File

@@ -0,0 +1,9 @@
from django.urls import path
from roster.views import RosterList, RosterGet, RosterAddress, RosterIdentifier
urlpatterns = [
path("list", RosterList.as_view()),
path("get/<str:uuid>", RosterGet.as_view()),
path("address/<int:address>", RosterAddress.as_view()),
path("identifier/<str:identifier>", RosterIdentifier.as_view()),
]

27
ram/roster/views.py Normal file
View File

@@ -0,0 +1,27 @@
from rest_framework.generics import ListAPIView, RetrieveAPIView
from roster.models import RollingStock
from roster.serializers import RollingStockSerializer
class RosterList(ListAPIView):
queryset = RollingStock.objects.all()
serializer_class = RollingStockSerializer
class RosterGet(RetrieveAPIView):
queryset = RollingStock.objects.all()
serializer_class = RollingStockSerializer
lookup_field = "uuid"
class RosterAddress(ListAPIView):
queryset = RollingStock.objects.all()
serializer_class = RollingStockSerializer
lookup_field = "address"
class RosterIdentifier(RetrieveAPIView):
queryset = RollingStock.objects.all()
serializer_class = RollingStockSerializer
lookup_field = "identifier"