1
0
Fork 0
mirror of https://github.com/Findus23/RPGnotes.git synced 2024-09-19 15:43:45 +02:00
RPGnotes/graph/views.py

100 lines
2.7 KiB
Python
Raw Normal View History

2022-11-19 22:46:41 +01:00
from typing import Union
from django.db import connection
2022-11-19 22:09:15 +01:00
from django.http import JsonResponse, HttpRequest, HttpResponse
from django.views.generic import TemplateView
2022-11-19 22:46:41 +01:00
from characters.models import Character
from factions.models import Faction
2022-11-19 22:09:15 +01:00
from locations.models import Location
2022-11-20 00:06:23 +01:00
from loot.models import Loot, LootType
2022-11-19 22:09:15 +01:00
from notes.models import Note
2022-11-19 22:46:41 +01:00
from users.models import TenantUser
GraphModelEl = Union[Location, Note, Character, Faction]
class Graph:
def __init__(self):
self.nodes = []
self.edges = []
def add_node(self, el: GraphModelEl, label: str = None):
if label is None:
label = el.name
self.nodes.append({
"key": el.graphkey,
"attributes": {
"label": label,
2022-11-20 00:25:04 +01:00
"size": 10,
"url": el.get_absolute_url() if hasattr(el, "get_absolute_url") else "/"
2022-11-19 22:46:41 +01:00
}
})
def add_edge(self, source: GraphModelEl, target: GraphModelEl):
self.edges.append({
"source": source.graphkey,
"target": target.graphkey
})
2022-11-19 22:09:15 +01:00
2022-11-19 22:51:43 +01:00
def prune(self) -> None:
connected_nodes = set()
for e in self.edges:
connected_nodes.add(e["source"])
connected_nodes.add(e["target"])
self.nodes = [n for n in self.nodes if n["key"] in connected_nodes]
def export(self):
return {
"attributes": {},
"nodes": self.nodes,
"edges": self.edges
}
2022-11-19 22:09:15 +01:00
#
#
# class Graph:
# def __init__(self):
# self.nodes=
class GraphView(TemplateView):
template_name = "graph/graph.jinja"
def get_graph(request: HttpRequest) -> HttpResponse:
2022-11-19 22:46:41 +01:00
g = Graph()
for loc in list(Location.objects.all()) + list(Note.objects.all()):
g.add_node(loc)
2022-11-19 22:09:15 +01:00
if loc.parent:
2022-11-19 22:46:41 +01:00
g.add_edge(loc, loc.parent)
for faction in Faction.objects.all():
g.add_node(faction, faction.name)
for user in TenantUser.objects \
.filter(tenants=connection.get_tenant()) \
.exclude(pk__in=[1, 2]):
g.add_node(user, user.name)
for char in Character.objects.all():
g.add_node(char)
if char.location:
g.add_edge(char, char.location)
if char.faction:
g.add_edge(char, char.faction)
if char.player:
g.add_edge(char, char.player)
2022-11-20 00:06:23 +01:00
for loottype in LootType.objects.all():
g.add_node(loottype)
for loot in Loot.objects.all():
g.add_node(loot)
if loot.location:
g.add_edge(loot, loot.location)
if loot.owner:
g.add_edge(loot, loot.owner)
if loot.type:
g.add_edge(loot, loot.type)
2022-11-19 22:51:43 +01:00
g.prune()
2022-11-19 22:09:15 +01:00
2022-11-19 22:51:43 +01:00
return JsonResponse(g.export())