Move javascript part to script.js - Implement orderBy feature

This commit is contained in:
Alessandro Maggio
2021-08-15 22:47:33 +02:00
parent c854911ca6
commit fa72feb21b
3 changed files with 308 additions and 181 deletions

View File

@@ -21,24 +21,38 @@ def streamers_available():
]
def read_json(streamer):
def read_json(streamer, return_response=True):
path = Settings.analytics_path
streamer = streamer if streamer.endswith(".json") else f"{streamer}.json"
return Response(
open(os.path.join(path, streamer)) if streamer in streamers_available() else [],
status=200,
mimetype="application/json",
if return_response is True:
return Response(
open(os.path.join(path, streamer))
if streamer in streamers_available()
else [],
status=200,
mimetype="application/json",
)
return (
json.loads(open(os.path.join(path, streamer)).read())
if streamer in streamers_available()
else []
)
def get_challenge_points(streamer):
datas = read_json(streamer, return_response=False)
if datas != {}:
return datas["series"][-1]["y"]
return 0
def json_all():
path = Settings.analytics_path
return Response(
json.dumps(
[
{
"name": streamer.strip(".json"),
"data": json.load(open(os.path.join(path, streamer))),
"data": read_json(streamer, return_response=False),
}
for streamer in streamers_available()
]
@@ -52,7 +66,19 @@ def index(refresh=5):
return render_template(
"charts.html",
refresh=(refresh * 60 * 1000),
streamers=",".join(streamers_available()),
)
def streamers():
return Response(
json.dumps(
[
{"name": s, "points": get_challenge_points(s)}
for s in sorted(streamers_available())
]
),
status=200,
mimetype="application/json",
)
@@ -70,6 +96,7 @@ class AnalyticsServer(Thread):
static_folder=os.path.join(Path().absolute(), "assets"),
)
self.app.add_url_rule("/", "index", index, defaults={"refresh": refresh})
self.app.add_url_rule("/streamers", "streamers", streamers)
self.app.add_url_rule("/json/<string:streamer>", "json", read_json)
self.app.add_url_rule("/json_all", "json_all", json_all)

View File

@@ -3,14 +3,15 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Twitch-Channel-Points-Miner-v2</title>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="{{url_for('static', filename='dark-theme.css')}}" rel="stylesheet"/>
<link href="{{url_for('static', filename='dark-theme.css')}}" rel="stylesheet" />
<style>
.tabs ul {
@@ -18,6 +19,7 @@
flex-direction: column;
flex-grow: 0px;
}
.tabs {
max-height: 425px;
overflow-y: auto;
@@ -29,39 +31,75 @@
<body style="height: 100vh;">
<div class="container">
<div style="text-align: center">
<img style="margin-top: -20px;" width="600px" src="{{url_for('static', filename='banner.png')}}" alt="banner">
<img style="margin-top: -20px;" width="600px" src="{{url_for('static', filename='banner.png')}}"
alt="banner">
<br>
<div style="margin-top: -15px;">
<a style="text-decoration: none;" href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/blob/master/LICENSE">
<img alt="License" src="https://img.shields.io/github/license/Tkd-Alex/Twitch-Channel-Points-Miner-v2" />
<a style="text-decoration: none;"
href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/blob/master/LICENSE">
<img alt="License"
src="https://img.shields.io/github/license/Tkd-Alex/Twitch-Channel-Points-Miner-v2" />
</a>
<a style="text-decoration: none;" href="https://www.python.org/downloads/release/python-360/">
<img alt="Python3" src="https://img.shields.io/badge/built%20for-Python≥3.6-red.svg?style=flat">
</a>
<a style="text-decoration: none;" href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/pulls">
<a style="text-decoration: none;"
href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/pulls">
<img alt="PRsWelcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat" />
</a>
<a style="text-decoration: none;" href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/stargazers">
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Tkd-Alex/Twitch-Channel-Points-Miner-v2" />
<a style="text-decoration: none;"
href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/stargazers">
<img alt="GitHub Repo stars"
src="https://img.shields.io/github/stars/Tkd-Alex/Twitch-Channel-Points-Miner-v2" />
</a>
<a style="text-decoration: none;" href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/issues?q=is%3Aissue+is%3Aclosed">
<img alt="GitHub closed issues" src="https://img.shields.io/github/issues-closed/Tkd-Alex/Twitch-Channel-Points-Miner-v2">
<a style="text-decoration: none;"
href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2/issues?q=is%3Aissue+is%3Aclosed">
<img alt="GitHub closed issues"
src="https://img.shields.io/github/issues-closed/Tkd-Alex/Twitch-Channel-Points-Miner-v2">
</a>
<a style="text-decoration: none;" href="https://github.com/Tkd-Alex/Twitch-Channel-Points-Miner-v2">
<img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/Tkd-Alex/Twitch-Channel-Points-Miner-v2" />
<img alt="GitHub last commit"
src="https://img.shields.io/github/last-commit/Tkd-Alex/Twitch-Channel-Points-Miner-v2" />
</a>
</div>
</div>
<br>
<div class="columns">
<div class="column"></div>
<div class="column">
<div class="dropdown">
<div class="dropdown-trigger">
<button class="button" aria-haspopup="true" aria-controls="dropdown-menu">
<span id="sorting-by">Sort by</span>
<span class="icon is-small">
<i class="fas fa-angle-down" aria-hidden="true"></i>
</span>
</button>
</div>
<div class="dropdown-menu" id="dropdown-menu" role="menu">
<div class="dropdown-content">
<a href="#" class="dropdown-item" onClick="changeSortBy(this)">
Name ascending
</a>
<a href="#" class="dropdown-item" onClick="changeSortBy(this)">
Name descending
</a>
<a href="#" class="dropdown-item" onClick="changeSortBy(this)">
Points ascending
</a>
<a href="#" class="dropdown-item" onClick="changeSortBy(this)">
Points descending
</a>
</div>
</div>
</div>
</div>
<div class="column is-3" style="text-align: right;">
<label class="checkbox" style="padding-left: 15px;">
<label class="checkbox" style="padding-left: 15px; font-weight: bold">
Annotations
<input type="checkbox" checked="true" id="annotations">
</label>
<label class="checkbox" style="padding-left: 15px;">
<label class="checkbox" style="padding-left: 15px; font-weight: bold">
Dark mode
<input type="checkbox" checked="true" id="dark-mode">
</label>
@@ -70,170 +108,29 @@
<div class="columns">
<div class="column is-2">
<div class="tabs">
<ul>
<li onCLick="getAllStreamersData()"><a>&#x02605; [All Streamers]</a></li>
{% for streamer in streamers.split(',')|sort %}
<li onClick="changeStreamer('{{ streamer }}', {{ loop.index }})"><a>{{ streamer.replace(".json", "") }}</a></li>
{% endfor %}
</ul>
<ul id="streamers-list"></ul>
</div>
</div>
<div class="column">
<div class="box" id="chart" style="padding: 0.30rem;></div>
<div class="box" id="chart" style="padding: 0.30rem;"></div>
</div>
</div>
<div style="text-align: center">If you want to help on this project, please leave a star 🌟 and share it with your friends! 😎 - A coffee is always a gesture of LOVE ❤️
<div style="text-align: center">If you want to help on this project, please leave a star 🌟 and share it with
your friends! 😎 - A coffee is always a gesture of LOVE ❤️
<a href="https://www.buymeacoffee.com/tkdalex" target="_blank">
<img style="margin-bottom: -8px; margin-left: 10px;" src="https://cdn.buymeacoffee.com/buttons/lato-yellow.png" alt="Buy Me A Coffee" height="5" width="138">
<img style="margin-bottom: -8px; margin-left: 10px;"
src="https://cdn.buymeacoffee.com/buttons/lato-yellow.png" alt="Buy Me A Coffee" height="5"
width="138">
</a>
</div>
<br>
</div>
</body>
<script type="text/javascript">
// https://apexcharts.com/javascript-chart-demos/line-charts/zoomable-timeseries/
var options = {
series: [],
chart: {
type: 'area',
stacked: false,
height: 400,
zoom: {
type: 'x',
enabled: true,
autoScaleYaxis: true
},
// background: '#2B2D3E',
foreColor: '#fff'
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth',
},
markers: {
size: 0,
},
title: {
text: 'Channel points (dates are displayed in UTC)',
align: 'left'
},
colors: ["#f9826c"],
fill: {
type: 'gradient',
gradient: {
shadeIntensity: 1,
inverseColors: false,
opacityFrom: 0.5,
opacityTo: 0,
stops: [0, 90, 100]
},
},
yaxis: {
title: {
text: 'Channel points'
},
},
xaxis: {
type: 'datetime',
labels: {
datetimeUTC: false
}
},
tooltip: {
theme: 'dark',
shared: false,
x: {
show: true,
format: 'HH:mm:ss dd MMM',
},
custom: ({series, seriesIndex, dataPointIndex, w}) => {
return (`<div class="apexcharts-active">
<div class="apexcharts-tooltip-title">${w.globals.seriesNames[seriesIndex]}</div>
<div class="apexcharts-tooltip-series-group apexcharts-active" style="order: 1; display: flex; padding-bottom: 0px !important;">
<div class="apexcharts-tooltip-text">
<div class="apexcharts-tooltip-y-group">
<span class="apexcharts-tooltip-text-label"><b>Points</b>: ${series[seriesIndex][dataPointIndex]}</span><br>
<span class="apexcharts-tooltip-text-label"><b>Reason</b>: ${w.globals.seriesZ[seriesIndex][dataPointIndex] ? w.globals.seriesZ[seriesIndex][dataPointIndex] : ''}</span>
</div>
</div>
</div>
</div>`
)
}
},
noData: {
text: 'Loading...'
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
var currentStreamer = null;
var annotations = [];
var refresh = parseInt("{{ refresh }}");
$(document).ready(function() {
chart.render();
$("li").eq(0).click();
});
function changeStreamer(streamer, index) {
$("li").removeClass( "is-active" )
$("li").eq(index - 1).addClass('is-active');
currentStreamer = streamer;
getStreamerData(streamer);
}
function getStreamerData(streamer) {
if(currentStreamer == streamer){
$.getJSON(`./json/${streamer}`, function (response) {
chart.updateSeries([{
name: streamer.replace(".json", ""),
data: response["series"]
}], true)
clearAnnotations();
annotations = response["annotations"];
updateAnnotations();
setTimeout(function(){getStreamerData(streamer);}, 300000); // 5 minutes
});
}
}
function getAllStreamersData(){
$.getJSON(`./json_all`, function (response) {apexcharts:6 It is a possibility that you may have not included 'data' property in series.
for(var i in response){
chart.appendSeries({
name: response[i]["name"].replace(".json", ""),
data: response[i]["data"]["series"]
}, true)
}
});
}
function updateAnnotations() {
if($('#annotations').prop("checked") === true){
clearAnnotations()
if(annotations && annotations.length > 0)
annotations.forEach((annotation, index) => {
annotations[index]['id'] = `id-${index}`
chart.addXaxisAnnotation(annotation, true)
})
} else clearAnnotations()
}
function clearAnnotations(){
if(annotations && annotations.length > 0)
annotations.forEach((annotation, index) => {
chart.removeAnnotation(annotation['id'])
})
chart.clearAnnotations();
}
function toggleDarkMode(){
function toggleDarkMode() {
var darkMode = $('#dark-mode').prop("checked")
$("link[href='{{url_for('static', filename='dark-theme.css')}}']").prop("disabled", !darkMode);
chart.updateOptions({
@@ -245,13 +142,8 @@
theme: darkMode === true ? "dark" : "light"
}
})
// if (darkMode === true) $("#chart").addClass("box")
// else $("#chart").removeClass("box")
}
$('#annotations').click(() => { updateAnnotations(); });
$('#dark-mode').click(() => { toggleDarkMode(); });
}
</script>
<script type="text/javascript" src="{{url_for('static', filename='script.js')}}"></script>
</html>

208
assets/script.js Normal file
View File

@@ -0,0 +1,208 @@
// https://apexcharts.com/javascript-chart-demos/line-charts/zoomable-timeseries/
var options = {
series: [],
chart: {
type: 'area',
stacked: false,
height: 400,
zoom: {
type: 'x',
enabled: true,
autoScaleYaxis: true
},
// background: '#2B2D3E',
foreColor: '#fff'
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth',
},
markers: {
size: 0,
},
title: {
text: 'Channel points (dates are displayed in UTC)',
align: 'left'
},
colors: ["#f9826c"],
fill: {
type: 'gradient',
gradient: {
shadeIntensity: 1,
inverseColors: false,
opacityFrom: 0.5,
opacityTo: 0,
stops: [0, 90, 100]
},
},
yaxis: {
title: {
text: 'Channel points'
},
},
xaxis: {
type: 'datetime',
labels: {
datetimeUTC: false
}
},
tooltip: {
theme: 'dark',
shared: false,
x: {
show: true,
format: 'HH:mm:ss dd MMM',
},
custom: ({
series,
seriesIndex,
dataPointIndex,
w
}) => {
return (`<div class="apexcharts-active">
<div class="apexcharts-tooltip-title">${w.globals.seriesNames[seriesIndex]}</div>
<div class="apexcharts-tooltip-series-group apexcharts-active" style="order: 1; display: flex; padding-bottom: 0px !important;">
<div class="apexcharts-tooltip-text">
<div class="apexcharts-tooltip-y-group">
<span class="apexcharts-tooltip-text-label"><b>Points</b>: ${series[seriesIndex][dataPointIndex]}</span><br>
<span class="apexcharts-tooltip-text-label"><b>Reason</b>: ${w.globals.seriesZ[seriesIndex][dataPointIndex] ? w.globals.seriesZ[seriesIndex][dataPointIndex] : ''}</span>
</div>
</div>
</div>
</div>`)
}
},
noData: {
text: 'Loading...'
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
var currentStreamer = null;
var annotations = [];
var streamersList = [];
var sortBy = "Name ascending";
var refresh = parseInt("{{ refresh }}");
$(document).ready(function () {
chart.render();
if (!localStorage.getItem("annotations")) localStorage.setItem("annotations", true);
if (!localStorage.getItem("dark-mode")) localStorage.setItem("dark-mode", true);
if (!localStorage.getItem("sort-by")) localStorage.setItem("sort-by", "Name ascending");
$('#annotations').prop("checked", localStorage.getItem("annotations") === "true");
$('#dark-mode').prop("checked", localStorage.getItem("dark-mode") === "true");
sortBy = localStorage.getItem("sort-by");
$('#sorting-by').text(`Sort by: ${sortBy}`);
getStreamers();
updateAnnotations();
toggleDarkMode();
});
function changeStreamer(streamer, index) {
$("li").removeClass("is-active")
$("li").eq(index - 1).addClass('is-active');
currentStreamer = streamer;
getStreamerData(streamer);
}
function getStreamerData(streamer) {
if (currentStreamer == streamer) {
$.getJSON(`./json/${streamer}`, function (response) {
chart.updateSeries([{
name: streamer.replace(".json", ""),
data: response["series"]
}], true)
clearAnnotations();
annotations = response["annotations"];
updateAnnotations();
setTimeout(function () {
getStreamerData(streamer);
}, 300000); // 5 minutes
});
}
}
function getAllStreamersData() {
$.getJSON(`./json_all`, function (response) {
for (var i in response) {
chart.appendSeries({
name: response[i]["name"].replace(".json", ""),
data: response[i]["data"]["series"]
}, true)
}
});
}
function getStreamers() {
$.getJSON('streamers', function (response) {
streamersList = response;
sortStreamers();
renderStreamers();
});
}
function renderStreamers() {
$("#streamers-list").empty();
var promised = new Promise((resolve, reject) => {
streamersList.forEach((streamer, index, array) => {
$("#streamers-list").append(`<li><a onClick="changeStreamer('${streamer.name}', ${index + 1}); return false;">${streamer.name.replace(".json", "")}</a></li>`);
if (index === array.length -1) resolve();
});
});
promised.then(() => {
changeStreamer(streamersList[0].name, 1);
});
}
function sortStreamers() {
streamersList = streamersList.sort((a, b) => {
return (a[sortBy.includes("Name") ? 'name' : 'points'] > b[sortBy.includes("Name") ? 'name' : 'points'] ? 1 : -1) * (sortBy.includes("ascending") ? 1 : -1);
});
}
function changeSortBy(option) {
sortBy = option.innerText.trim();
sortStreamers();
renderStreamers();
$('#sorting-by').text(`Sort by: ${sortBy}`);
localStorage.setItem("sort-by", sortBy);
}
function updateAnnotations() {
if ($('#annotations').prop("checked") === true) {
clearAnnotations()
if (annotations && annotations.length > 0)
annotations.forEach((annotation, index) => {
annotations[index]['id'] = `id-${index}`
chart.addXaxisAnnotation(annotation, true)
})
} else clearAnnotations()
}
function clearAnnotations() {
if (annotations && annotations.length > 0)
annotations.forEach((annotation, index) => {
chart.removeAnnotation(annotation['id'])
})
chart.clearAnnotations();
}
$('#annotations').click(() => {
updateAnnotations();
});
$('#dark-mode').click(() => {
toggleDarkMode();
});
$('.dropdown').click(() => {
$('.dropdown').toggleClass('is-active')
})