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
|
|
|
|
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-19 23:52:45 +01:00
|
|
|
"size": 10
|
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-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())
|