Skip to content
This repository has been archived by the owner on Jun 28, 2024. It is now read-only.

Commit

Permalink
refactor: Separate backend and frontend, avoid template-filling on th…
Browse files Browse the repository at this point in the history
…e fly. Resolve #158.
  • Loading branch information
TerryGeng committed Jul 12, 2020
1 parent 9a6aaba commit 4e541a7
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 50 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,7 @@ tmp/

*.db

templates/*

# Pycharm
.idea/
.idea/
37 changes: 24 additions & 13 deletions interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def build_tags_color_lookup():


def get_all_dirs():
dirs = []
dirs = ["."]
paths = var.music_db.query_all_paths()
for path in paths:
pos = 0
Expand All @@ -225,18 +225,7 @@ def get_all_dirs():
@web.route("/", methods=['GET'])
@requires_auth
def index():
while var.cache.dir_lock.locked():
time.sleep(0.1)

tags_color_lookup = build_tags_color_lookup()
max_upload_file_size = util.parse_file_size(var.config.get("webinterface", "max_upload_file_size", fallback="30MB"))

return render_template('index.html',
dirs=get_all_dirs(),
upload_enabled=var.config.getboolean("webinterface", "upload_enabled", fallback=True),
tags_color_lookup=tags_color_lookup,
max_upload_file_size=max_upload_file_size
)
return open('templates/index.html', "r").read()


@web.route("/playlist", methods=['GET'])
Expand Down Expand Up @@ -527,6 +516,8 @@ def build_library_query_condition(form):

if form['type'] == 'file':
folder = form['dir']
if folder == ".":
folder = ""
if not folder.endswith('/') and folder:
folder += '/'
condition.and_like('path', folder + '%')
Expand All @@ -552,6 +543,26 @@ def build_library_query_condition(form):
abort(400)


@web.route("/library/info", methods=['GET'])
@requires_auth
def library_info():
global log

while var.cache.dir_lock.locked():
time.sleep(0.1)

tags = var.music_db.query_all_tags()
max_upload_file_size = util.parse_file_size(var.config.get("webinterface", "max_upload_file_size", fallback="30MB"))

print(get_all_dirs())
return jsonify(dict(
dirs=get_all_dirs(),
upload_enabled=var.config.getboolean("webinterface", "upload_enabled", fallback=True),
tags=tags,
max_upload_file_size=max_upload_file_size
))


@web.route("/library", methods=['POST'])
@requires_auth
def library():
Expand Down
1 change: 0 additions & 1 deletion templates/index.html

This file was deleted.

1 change: 0 additions & 1 deletion templates/need_token.html

This file was deleted.

81 changes: 67 additions & 14 deletions web/js/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Tooltip,
} from 'bootstrap/js/src/index';
import {
getColor,
isOverflown,
setProgressBar,
secondsToStr,
Expand Down Expand Up @@ -416,18 +417,6 @@ function setFilterType(event, type) {
updateResults();
}

// Bind Event
$('.filter-tag').click(function (e) {
const tag = $(e.currentTarget);
if (!tag.hasClass('tag-clicked')) {
tag.addClass('tag-clicked');
tag.removeClass('tag-unclicked');
} else {
tag.addClass('tag-unclicked');
tag.removeClass('tag-clicked');
}
updateResults();
});

filter_dir.change(function () {
updateResults();
Expand Down Expand Up @@ -501,6 +490,9 @@ function bindLibraryResultEvent() {
);
}

const lib_filter_tag_group = $("#filter-tags");
const lib_filter_tag_element = $(".filter-tag");

const lib_group = $('#library-group');
const id_element = $('.library-item-id');
const title_element = $('.library-item-title');
Expand All @@ -513,6 +505,65 @@ const tag_edit_element = $('.library-item-edit');
// var notag_element = $(".library-item-notag");
// var tag_element = $(".library-item-tag");

function updateLibraryControls(){
$.ajax({
type: 'GET',
url: 'library/info',
statusCode: {
200: displayLibraryControls,
403: function () {
location.reload(true);
},
},
});
}

function displayLibraryControls(data){
$("#maxUploadFileSize").val(data.max_upload_file_size);
if (data.upload_enabled) {
$("#uploadDisabled").val("false");
$("#upload").show();
} else {
$("#uploadDisabled").val("true");
$("#upload").hide();
}

let select = $("#filter-dir");
let dataList = $("#upload-target-dirs");
select.find("option").remove();
dataList.find("option").remove();
if (data.dirs.length > 0) {
console.log(data.dirs);
data.dirs.forEach(function (dir) {
$("<option value=\"" + dir + "\">" + dir + "</option>").appendTo(select);
$("<option value=\"" + dir + "\">").appendTo(dataList);
});
}

// ----- Tag filters -----
$(".filter-tag").remove();
if (data.tags.length > 0) {
data.tags.forEach(function (tag) {
const tag_copy = lib_filter_tag_element.clone();
tag_copy.html(tag);
tag_copy.addClass('badge-' + getColor(tag));
tag_copy.appendTo(lib_filter_tag_group);
});
}
// Bind Event
$('.filter-tag').click(function (e) {
const tag = $(e.currentTarget);
if (!tag.hasClass('tag-clicked')) {
tag.addClass('tag-clicked');
tag.removeClass('tag-unclicked');
} else {
tag.addClass('tag-unclicked');
tag.removeClass('tag-clicked');
}
updateResults();
});
}

function addResultItem(item) {
id_element.val(item.id);
title_element.html(item.title);
Expand Down Expand Up @@ -609,6 +660,8 @@ function updateResults(dest_page = 1) {
opacity: 1,
}, 200);
});

updateLibraryControls();
}

const download_form = $('#download-form');
Expand Down Expand Up @@ -1210,10 +1263,10 @@ function playheadDragged(event) {
// ----- Application -----
// -----------------------

updateResults();

document.addEventListener('DOMContentLoaded', () => {
updateResults();
updatePlaylist();
updateLibraryControls();

// Check the version of playlist to see if update is needed.
setInterval(checkForPlaylistUpdate, 3000);
Expand Down
38 changes: 37 additions & 1 deletion web/js/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,42 @@ export function isOverflown(element) {
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
}

export function hash(string) {
if (typeof string != "string") return 0;
let hash = 0;
if (string.length === 0) {
return hash;
}
for (let i = 0; i < string.length; i++) {
let char = string.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}

export function getColor(string) {
let num = hash(string) % 8;
switch(num) {
case 0:
return "primary";
case 1:
return "secondary";
case 2:
return "success";
case 3:
return "danger";
case 4:
return "warning";
case 5:
return "info";
case 6:
return "light";
case 7:
return "dark";
}
}

export function setProgressBar(bar, progress, text = '') {
const progPos = (-1 * (1 - progress) * bar.scrollWidth).toString();
const progStr = (progress * 100).toString();
Expand Down Expand Up @@ -32,4 +68,4 @@ export function coverArtString(title) {
}

return 'Cover art for ' + nameOfSong;
}
}
25 changes: 6 additions & 19 deletions web/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,6 @@ <h3 class="card-title">Filters</h3>
<div id="filter-path" class="input-group mb-2">
<select class="form-control form-control-sm" id="filter-dir" disabled>
<option value="">.</option>
{% for dir in dirs %}
<option value="{{ dir }}">{{ dir }}</option>
{% endfor %}
</select>
</div>

Expand All @@ -197,12 +194,9 @@ <h3 class="card-title">Filters</h3>
</div>

<div class="col">
<fieldset id="filter-type mb-2">
<fieldset id="filter-tags">
<legend>Tags</legend>
{% for tag in tags_color_lookup.keys() %}
<span id="filter-tag"
class="filter-tag tag-unclicked tag-click badge badge-{{ tags_color_lookup[tag] }}">{{ tag }}</span>
{% endfor %}
<span class="filter-tag tag-unclicked tag-click badge"></span>
</fieldset>
</div>
</div>
Expand Down Expand Up @@ -338,12 +332,8 @@ <h3 class="modal-title" id="deleteWarningModalLabel">Are you really sure?</h3>
</div>
</div>

{% if upload_enabled %}
<div id="upload" class="container mb-3">
{% else %}
<div id="upload" class="container mb-3" style="display: none;">
<input type="hidden" id="uploadDisabled" value="true" />
{% endif %}
<input type="hidden" id="uploadDisabled" value="false" />
<div class="card">
<div class="card-header">
<h3 class="card-title">Upload File</h3>
Expand All @@ -368,11 +358,8 @@ <h3 class="card-title">Upload File</h3>
<div class="input-group-prepend">
<label for="uploadTargetDir" class="input-group-text">Upload To</label>
</div>
<input class="form-control" list="targetdirs" id="uploadTargetDir" name="targetdir" placeholder="uploads" />
<datalist id="targetdirs">
{% for dir in dirs %}
<option value="{{ dir }}">
{% endfor %}
<input class="form-control" list="upload-target-dirs" id="uploadTargetDir" name="upload-target-dirs" placeholder="uploads" />
<datalist id="upload-target-dirs">
</datalist>
</div>
</div>
Expand Down Expand Up @@ -552,7 +539,7 @@ <h3 class="modal-title" id="uploadTitle"><i class="fas fa-upload mr-1"></i>Uploa
</div>
</div>

<input type="hidden" id="maxUploadFileSize" value="{{ max_upload_file_size }}" />
<input type="hidden" id="maxUploadFileSize" value="" />

<script src="static/js/main.js"></script>
</body>
Expand Down

0 comments on commit 4e541a7

Please sign in to comment.