Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add api to add tags dynamically #75

Merged
merged 6 commits into from
Sep 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions bfportal/bfportal/static/js/bfportal.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// https://portal.battlefield.com/experience/package/era?playgroundId=d23be170-33aa-11ed-98f8-9d6912d338ca

$(document).ready(function() {
"use strict";
$("body").on('click touch', function (event) {
Expand Down Expand Up @@ -55,17 +57,12 @@ $(document).ready(function() {
GTApiResponse.playgroundName = String;
GTApiResponse.playgroundDescription = String;
if (!GTApiResponse.hasOwnProperty('errors')) {
let tags = "";
GTApiResponse.tag.forEach(elm => tags = tags.concat(elm.metadata.translations[0].localizedText, ","));
GTApiResponse.tag.forEach(elm => {addTagToDeck(elm['metadata']['translations'][0]['localizedText'])});


GTApiResponse = GTApiResponse.validatedPlayground;
document.getElementById("id_title").value = toTitleCase(GTApiResponse.playgroundName);
document.getElementById("id_description").value = GTApiResponse.playgroundDescription;
const tagElm = document.getElementById("id_tags");
tagElm.value = tags;
if (tags.length > 1) {
tagElm.readOnly = true;
document.getElementById(tagElm.id + "Reason").textContent = "[Auto Completed as Exp Url is Provided]";
}
document.getElementById("id_no_players").value = GTApiResponse.mapRotation.maps[0].gameSize;
{
document.getElementById("id_no_bots").value = GTApiResponse.mapRotation.maps[0].gameSize;
Expand Down
3 changes: 1 addition & 2 deletions bfportal/bfportal/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,16 @@

<meta name="viewport" content="width=device-width, initial-scale=1"/>

{% block preload_media %}{% endblock %}
{% block extra_css %}
{# Override this in templates to add extra stylesheets #}
{% endblock %}

{# Global stylesheets #}
{% tailwind_css %}
<script type="text/javascript" src="{% static 'js/preload.js' %}"></script>
</head>

<body class="bg-bg-default min-h-screen m-0 relative flex flex-col {% block body_class %}{% endblock %}">

{% block header %}
{% include nav_tmpl|default:'navbar.html' %}
{% endblock %}
Expand Down
26 changes: 26 additions & 0 deletions bfportal/core/helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import requests
from loguru import logger
from taggit.models import Tag


def get_tags_from_gt_api() -> list:
"""Gets tags from GameTools api."""
all_tags_json = requests.get(
"https://api.gametools.network/bf2042/availabletags/?lang=en-us"
).json()["availableTags"]
return [
tag_dict["metadata"]["translations"][0]["localizedText"]
for tag_dict in all_tags_json
]


def save_tags_from_gt_api():
"""Saves non existing tags in db"""
tags_added = []
for tag in get_tags_from_gt_api():
if not Tag.objects.filter(name__exact=tag).exists():
Tag(name=tag).save()
tags_added.append(tag)
else:
logger.debug(f"{tag} exists in db")
logger.debug(f"Added Tags :- {tags_added}")
3 changes: 3 additions & 0 deletions bfportal/core/management/commands/ensure_initialization.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from core.helper import save_tags_from_gt_api
from core.models import (
ExperiencesCategory,
ExperiencesPage,
Expand Down Expand Up @@ -57,3 +58,5 @@ def handle(self, *args, **options):
if not hasattr(user, "profile"):
user.profile = Profile()
user.save()

save_tags_from_gt_api()
18 changes: 3 additions & 15 deletions bfportal/core/management/commands/portal.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import json

import requests
from core.models import AvailableTags
from core.helper import save_tags_from_gt_api
from django.core.management import BaseCommand


Expand All @@ -14,18 +11,9 @@ def add_arguments(self, parser): # noqa: D102
parser.add_argument(
"--get_tags",
action="store_true",
help="Gets all tags from game tools",
help="Gets all tags from game tools and saves to db",
)

def handle(self, *args, **options): # noqa: D102
if options.get("get_tags", None):
all_tags_json = requests.get(
"https://api.gametools.network/bf2042/availabletags/?lang=en-us"
).json()["availableTags"]
tags = [
tag_dict["metadata"]["translations"][0]["localizedText"]
for tag_dict in all_tags_json
]
AvailableTags.objects.all().delete()
new_obj = AvailableTags(tags=json.dumps(tags))
new_obj.save()
save_tags_from_gt_api()
16 changes: 16 additions & 0 deletions bfportal/core/migrations/0051_delete_availabletags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Generated by Django 3.2.12 on 2022-09-20 10:42

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
("core", "0050_auto_20220919_1727"),
]

operations = [
migrations.DeleteModel(
name="AvailableTags",
),
]
6 changes: 0 additions & 6 deletions bfportal/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,9 +638,3 @@ def user_experiences(self, request, discord_id):
)
else:
return HttpResponse("User not Found", status=404)


class AvailableTags(models.Model): # noqa: D101
tags = models.TextField(
blank=True, verbose_name="All available tags in BF 2042 Portal Rules editor"
)
79 changes: 61 additions & 18 deletions bfportal/core/static/js/autocomplete_helper.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,61 @@
function bindTriggers(html_id) {
const deck = $(`#${html_id}_on_deck`);
deck.bind('added', function () {
deck.children().last().show({
duration: 100,
start: function () {
deck.children().last().css('display', 'flex')
}
})
if (!deck.hasClass("ml-2")) deck.addClass("ml-2")
})
deck.bind('killed', function () {
if (!deck.children().length) deck.removeClass("ml-2")
})
}

function addTagToDeck(tagName) {
fetch(`/ajax_select/ajax_lookup/tags?term=${tagName}`).then(
resp => resp.json().then(json => {
return addTag(json[0])
})
)
function addTag(tag){
const pk = tag.pk,
id = "id_tags",
$deck = $("#id_tags_on_deck"),
$text = $("#id_tags_text"),
$this = $('#id_tags'),
prev = $this.val();

if (prev.indexOf('|' + pk + '|') === -1) {
$this.val((prev ? prev : '|') + pk + '|');
addKiller(tag.repr, pk);
$text.val('');
$deck.trigger('added', [tag.pk, tag]);
$this.trigger('change');
}

function addKiller(repr, pk) {
const killId = 'kill_' + pk + id,
killButton = '<span class="ui-icon ui-icon-trash" id="' + killId + '">X</span> ';
$deck.append('<div id="' + id + '_on_deck_' + pk + '">' + killButton + repr + ' </div>');

$('#' + killId).click(function () {
kill(pk);
$deck.trigger('killed', [pk]);
});
}

function kill(pk) {
$this.val($this.val().replace('|' + pk + '|', '|'));
$('#' + id + '_on_deck_' + pk).fadeOut().remove();
}
return false;
}
}


defer(function initAutoCompleteHelper() {
$(document).ready(function () {
const autocompleteContainers = ["tags", "creators"]
Expand All @@ -6,8 +64,8 @@ defer(function initAutoCompleteHelper() {
const input = $(`#id_${container}_text`),
inputContainer = $(`#${container}InputContainer`),
deck = $(`#id_${container}_on_deck`);
if(deck.children().length){
if(!deck.hasClass("ml-2")) deck.addClass("ml-2")
if (deck.children().length) {
if (!deck.hasClass("ml-2")) deck.addClass("ml-2")
deck.children().each(function () {
$(this).css('display', 'flex')
})
Expand All @@ -18,26 +76,11 @@ defer(function initAutoCompleteHelper() {
input.focusout(function () {
inputContainer.removeClass("border-1/2 border-bf2042-4")
})
bindTriggers(`id_${container}`)
})
})
})

function bindTriggers(html_id){
const deck = $(`#${html_id}_on_deck`);
deck.bind('added', function () {
deck.children().last().show({
duration: 100,
start: function () {
deck.children().last().css('display', 'flex')
}
})
if(!deck.hasClass("ml-2")) deck.addClass("ml-2")
})
deck.bind('killed', function () {
if(!deck.children().length) deck.removeClass("ml-2")
})
}

function handleKeyDown(elm, event) {
if (!elm.value && event.keyCode === 8) {
const deck = $(`#${$(elm).parent().attr('id') === "tagsInputContainer" ? 'id_tags' : 'id_creators'}_on_deck`),
Expand Down
13 changes: 5 additions & 8 deletions bfportal/core/templates/ajax_select/custom_base.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
<div id="{{ name }}InputContainer" class="w-full flex flex-row items-center bg-card-bg h-9 text-white rounded">
<div id="{{ html_id }}_on_deck" class="results_on_deck flex flex-row items-center gap-x-1"></div>
<label for="{{ html_id }}_text"></label><input class="w-full px-2 rounded bg-transparent border-0 focus:ring-0 disabled:bg-[#1f1f1f] placeholder:font-medium placeholder:text-sm"
type="text" name="{{ name }}_text" id="{{ html_id }}_text" value="" autocomplete="off"
placeholder="{{ name|capfirst }}" onkeydown="handleKeyDown(this, event)"/>
<div id="{{ name }}InputContainer" class="w-full flex flex-row items-center bg-card-bg min-h-9 text-white rounded flex-wrap">
<div id="{{ html_id }}_on_deck" class="results_on_deck flex flex-row flex-wrap items-center gap-x-1 gap-y-1 max-w-fit"></div>
<input class="min-w-[30px] px-2 rounded bg-transparent border-0 focus:ring-0 disabled:bg-[#1f1f1f] placeholder:font-medium placeholder:text-sm"
type="text" name="{{ name }}_text" id="{{ html_id }}_text" value="" autocomplete="off"
placeholder="{{ name|capfirst }}" onkeydown="handleKeyDown(this, event)"/>
<input type="hidden" class="bg-card-bg text-white" name="{{ name }}" id="{{ html_id }}" value="{{ current_ids }}"
data-ajax-select="autocompleteselectmultiple" data-plugin-options="{{ data_plugin_options }}"/>
</div>
{% block extra_script %}
<script type="application/javascript"> bindTriggers("{{ html_id }}") </script>
{% endblock %}

{% block help %}{% if help_text %}<p class="help">{{ help_text }}</p>{% endif %}{% endblock %}
8 changes: 6 additions & 2 deletions bfportal/core/templates/core/submit_experience_page.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
{% load wagtailcore_tags widget_tweaks static %}

{% block extra_css %}
{{ form.media }}
{{ form.media.css }}
{% endblock %}

{% block content %}
<script src="{% static 'js/autocomplete_helper.js' %}"></script>
<div class="w-9/12 mx-auto mb-8 mt-8">
<div class="flex flex-col gap-y-2">
<form action="." method="POST" id="submitExpPage">
Expand Down Expand Up @@ -164,3 +163,8 @@
</div>
</div>
{% endblock %}

{% block extra_js %}
{{ form.media.js }}
<script src="{% static 'js/autocomplete_helper.js' %}"></script>
{% endblock %}
3 changes: 2 additions & 1 deletion bfportal/factory/management/commands/fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from random import choice, choices, randint
from uuid import uuid4

from core.helper import get_tags_from_gt_api
from core.models import ExperiencePage, ExperiencesCategory, ExperiencesPage
from django.contrib.auth import get_user_model
from django.core.management import BaseCommand
Expand Down Expand Up @@ -51,7 +52,7 @@ def handle(self, *args, **options):
owner = [
user for user in get_user_model().objects.all() if not user.is_superuser
]
tags = [factory.word() for i in range(20)]
tags = get_tags_from_gt_api()
experiences_page = ExperiencesPage.objects.first()
page_count = options.get("no_of_pages", [0])[0]
logger.critical("delete all Experience Pages [y/n] ")
Expand Down
3 changes: 2 additions & 1 deletion bfportal/factory/management/commands/playground.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from core.helper import get_tags_from_gt_api
from django.core.management import BaseCommand


class Command(BaseCommand):
"""Command that is used to develop other command and test stuff"""

def handle(self, *args, **options): # noqa: D102
print("pass")
print(get_tags_from_gt_api())
6 changes: 3 additions & 3 deletions bfportal/theme/static_src/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ body::-webkit-scrollbar-thumb:hover {
}
}

.ui-widget.ui-widget-content {
ul.ui-widget.ui-widget-content {
background-color: theme('colors.card-bg');
color: white;
border: 0;
Expand All @@ -97,11 +97,11 @@ body::-webkit-scrollbar-thumb:hover {
color: white;
}

.ui-menu-item-wrapper span {
a.ui-menu-item-wrapper span {
color: white;
}

.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active, a.ui-button:active, .ui-button:active, .ui-button.ui-state-active:hover {
a.ui-menu-item-wrapper.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active, a.ui-button:active, .ui-button:active, .ui-button.ui-state-active:hover {
background: theme("colors.hover-bg-light");
border: 0;

Expand Down