client: implement queuing

This commit is contained in:
geoffrey45
2021-12-21 13:42:06 +03:00
parent 8a744ce0be
commit 36999d8061
17 changed files with 240 additions and 179 deletions
+1
View File
@@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"animate.css": "^4.1.1", "animate.css": "^4.1.1",
"core-js": "^3.6.5", "core-js": "^3.6.5",
"mitt": "^3.0.0",
"register-service-worker": "^1.7.1", "register-service-worker": "^1.7.1",
"sass": "^1.44.0", "sass": "^1.44.0",
"sass-loader": "^10", "sass-loader": "^10",
+44 -17
View File
@@ -1,4 +1,6 @@
import typing
from app.models import Folders, Artists from app.models import Folders, Artists
from app.helpers import ( from app.helpers import (
all_songs_instance, all_songs_instance,
convert_one_to_json, convert_one_to_json,
@@ -29,6 +31,7 @@ bp = Blueprint('api', __name__, url_prefix='')
artist_instance = Artists() artist_instance = Artists()
folder_instance = Folders() folder_instance = Folders()
img_path = "http://127.0.0.1:8900/images/thumbnails/"
def main_whatever(): def main_whatever():
@@ -242,26 +245,26 @@ def getArtistData():
@bp.route("/f/<folder>") @bp.route("/f/<folder>")
@cache.cached() @cache.cached()
def getFolderTree(folder: str = None): def getFolderTree(folder: str = None):
if folder == "home":
requested_dir = home_dir
else:
try: try:
req_dir, last_id = folder.split('::') req_dir, last_id = folder.split('::')
except (ValueError):
req_dir = folder
last_id = None
req_dir = req_dir.replace('|', '/') req_dir = req_dir.replace('|', '/')
if req_dir:
dir_list = req_dir.split('/') dir_list = req_dir.split('/')
requested_dir = os.path.join(home_dir, *dir_list) requested_dir = os.path.join(home_dir, *dir_list)
if req_dir == "home":
requested_dir = home_dir
if last_id == "None":
last_id = None
except:
requested_dir = home_dir
last_id = None
dir_content = os.scandir(requested_dir) dir_content = os.scandir(requested_dir)
folders = [] folders = []
files = []
for entry in dir_content: for entry in dir_content:
if entry.is_dir() and not entry.name.startswith('.'): if entry.is_dir() and not entry.name.startswith('.'):
@@ -278,20 +281,23 @@ def getFolderTree(folder: str = None):
if entry.is_file(): if entry.is_file():
if isValidFile(entry.name) == True: if isValidFile(entry.name) == True:
file = all_songs_instance.find_song_by_path(entry.path)
if not file:
getTags(entry.path)
songs_array = all_songs_instance.find_songs_by_folder( songs_array = all_songs_instance.find_songs_by_folder(
req_dir, last_id) req_dir, last_id)
songs = convert_to_json(songs_array) songs = convert_to_json(songs_array)
for song in songs: for song in songs:
song['artists'] = song['artists'].split(', ') song['artists'] = song['artists'].split(', ')
song['filepath'] = song['filepath'].replace(home_dir, '')
song['image'] = img_path + song['image']
files = songs song['type']['name'] = "folder"
song['type']['id'] = req_dir
for file in files: return {"files": songs, "folders": folders}
file['filepath'] = file['filepath'].replace(home_dir, '')
return {"files": files, "folders": folders}
@bp.route('/image/<img_type>/<image_id>') @bp.route('/image/<img_type>/<image_id>')
@@ -313,3 +319,24 @@ def send_image(img_type, image_id):
print(img_dir + image) print(img_dir + image)
return send_from_directory(img_dir, image) return send_from_directory(img_dir, image)
@bp.route('/get/queue', methods=['POST'])
def post():
args = request.get_json()
type = args['type']
id = args['id']
if type == "folder":
songs = all_songs_instance.find_songs_by_folder_og(id)
songs_array = convert_to_json(songs)
for song in songs_array:
song['artists'] = song['artists'].split(', ')
song['filepath'] = song['filepath'].replace(home_dir, '')
song['image'] = img_path + song['image']
return {'songs': songs_array}
return {'msg': 'ok'}
+12 -6
View File
@@ -54,16 +54,16 @@ def extract_thumb(path):
return webp_path return webp_path
if path.endswith('.flac'): if path.endswith('.flac'):
audio = FLAC(path)
try: try:
audio = FLAC(path)
album_art = audio.pictures[0].data album_art = audio.pictures[0].data
except IndexError: except:
album_art = None album_art = None
elif path.endswith('.mp3'): elif path.endswith('.mp3'):
audio = ID3(path)
try: try:
audio = ID3(path)
album_art = audio.getall('APIC')[0].data album_art = audio.getall('APIC')[0].data
except IndexError: except:
album_art = None album_art = None
if album_art is None: if album_art is None:
@@ -91,9 +91,15 @@ def extract_thumb(path):
def getTags(full_path): def getTags(full_path):
if full_path.endswith('.flac'): if full_path.endswith('.flac'):
try:
audio = FLAC(full_path) audio = FLAC(full_path)
except:
return
elif full_path.endswith('.mp3'): elif full_path.endswith('.mp3'):
try:
audio = MP3(full_path) audio = MP3(full_path)
except:
return
try: try:
artists = audio['artist'][0] artists = audio['artist'][0]
@@ -122,8 +128,8 @@ def getTags(full_path):
title = audio['TIT2'][0] title = audio['TIT2'][0]
except: except:
title = 'Unknown' title = 'Unknown'
except IndexError: except:
title = 'Unknown' title = full_path.split('/')[-1]
try: try:
album = audio['album'][0] album = audio['album'][0]
+4 -2
View File
@@ -51,8 +51,7 @@ class AllSongs(Mongo):
def insert_song(self, song_obj): def insert_song(self, song_obj):
self.collection.update_one( self.collection.update_one(
{'filepath': song_obj['filepath']}, { "$set": song_obj}, upsert=True) {'filepath': song_obj['filepath']}, {"$set": song_obj}, upsert=True)
# self.collection.insert_one(song_obj)
def find_song_by_title(self, query): def find_song_by_title(self, query):
self.collection.create_index([('title', pymongo.TEXT)]) self.collection.create_index([('title', pymongo.TEXT)])
@@ -71,6 +70,9 @@ class AllSongs(Mongo):
else: else:
return self.collection.find({'folder': query, '_id': {'$gt': ObjectId(last_id)}}).limit(limit) return self.collection.find({'folder': query, '_id': {'$gt': ObjectId(last_id)}}).limit(limit)
def find_songs_by_folder_og(self, query):
return self.collection.find({'folder': query})
def find_songs_by_artist(self, query): def find_songs_by_artist(self, query):
return self.collection.find({'artists': {'$regex': query, '$options': 'i'}}) return self.collection.find({'artists': {'$regex': query, '$options': 'i'}})
+10 -2
View File
@@ -12,7 +12,7 @@
<PinnedStuff :collapsed="collapsed" /> <PinnedStuff :collapsed="collapsed" />
</div> </div>
<div class="content"> <div class="content">
<router-view /> <router-view @sendQueue="updpateQueue"/>
</div> </div>
<div class="r-sidebar"> <div class="r-sidebar">
<Search <Search
@@ -23,7 +23,7 @@
<div class="m-np"> <div class="m-np">
<NowPlaying /> <NowPlaying />
</div> </div>
<UpNext v-model:up_next="up_next" @expandQueue="expandQueue" /> <UpNext v-model:up_next="up_next" @expandQueue="expandQueue" :queue="queue"/>
<RecommendedArtist /> <RecommendedArtist />
</div> </div>
</div> </div>
@@ -51,6 +51,12 @@ export default {
}, },
setup() { setup() {
const queue = ref(JSON.parse(localStorage.getItem("queue")) || []);
const updpateQueue = (data)=> {
queue.value = data;
}
const collapsed = ref(true); const collapsed = ref(true);
function toggleNav() { function toggleNav() {
@@ -76,12 +82,14 @@ export default {
return { return {
toggleNav, toggleNav,
updpateQueue,
collapsed, collapsed,
up_next, up_next,
expandQueue, expandQueue,
expandSearch, expandSearch,
collapseSearch, collapseSearch,
search, search,
queue,
}; };
}, },
}; };
+5 -5
View File
@@ -129,11 +129,11 @@ a {
margin-bottom: 0.5em; margin-bottom: 0.5em;
} }
@media (max-width: 70em) { // @media (max-width: 70em) {
.r-sidebar { // .r-sidebar {
display: none; // display: none;
} // }
} // }
.image { .image {
background-position: center; background-position: center;
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

+33 -7
View File
@@ -2,18 +2,25 @@
<div class="folder"> <div class="folder">
<div class="table rounded" ref="songtitle" v-if="songs.length"> <div class="table rounded" ref="songtitle" v-if="songs.length">
<table> <table>
<thead>
<tr> <tr>
<th>Track</th> <th>Track</th>
<th>Artist</th> <th>Artist</th>
<th>Album</th> <th>Album</th>
<th v-if="songTitleWidth > minWidth">Duration</th> <th v-if="songTitleWidth > minWidth">Duration</th>
</tr> </tr>
<tr v-for="song in songs" :key="song" @click="playAudio(song.filepath)"> </thead>
<tbody>
<tr
v-for="song in songs"
:key="song"
@click="updateQueue(song.type.name, song.type.id)"
>
<td :style="{ width: songTitleWidth + 'px' }" class="flex"> <td :style="{ width: songTitleWidth + 'px' }" class="flex">
<div <div
class="album-art rounded image" class="album-art rounded image"
:style="{ :style="{
backgroundImage: `url(&quot;${image_path + song.image}&quot;)`, backgroundImage: `url(&quot;${song.image}&quot;)`,
}" }"
></div> ></div>
<div> <div>
@@ -24,7 +31,7 @@
<div class="ellip"> <div class="ellip">
<span <span
class="artist" class="artist"
v-for="artist in song.artists" v-for="artist in putCommas(song.artists)"
:key="artist" :key="artist"
>{{ artist }}</span >{{ artist }}</span
> >
@@ -40,6 +47,7 @@
{{ `${Math.trunc(song.length / 60)} min` }} {{ `${Math.trunc(song.length / 60)} min` }}
</td> </td>
</tr> </tr>
</tbody>
</table> </table>
</div> </div>
<div v-else ref="songtitle"></div> <div v-else ref="songtitle"></div>
@@ -48,15 +56,17 @@
<script> <script>
import { ref } from "@vue/reactivity"; import { ref } from "@vue/reactivity";
import { onMounted, onUnmounted } from "@vue/runtime-core"; import { onMounted, onUnmounted } from "@vue/runtime-core";
import { playAudio } from "@/composables/playAudio.js"; import { playAudio } from "@/composables/playAudio.js";
import getQueue from "@/composables/getQueue.js";
import putCommas from "@/composables/perks.js";
export default { export default {
props: ["songs"], props: ["songs"],
setup() { setup(props, context) {
const songtitle = ref(null); const songtitle = ref(null);
const songTitleWidth = ref(null); const songTitleWidth = ref(null);
const image_path = "http://127.0.0.1:8900/images/thumbnails/";
const minWidth = ref(300); const minWidth = ref(300);
@@ -66,6 +76,11 @@ export default {
songTitleWidth.value = a > minWidth.value * 4 ? a / 4 : a / 3; songTitleWidth.value = a > minWidth.value * 4 ? a / 4 : a / 3;
}; };
const updateQueue = async (type, id) => {
const queue = await getQueue(type, id);
context.emit("updateQueue", queue);
};
onMounted(() => { onMounted(() => {
resizeSongTitleWidth(); resizeSongTitleWidth();
@@ -80,7 +95,14 @@ export default {
}); });
}); });
return { songtitle, image_path, songTitleWidth, minWidth, playAudio }; return {
songtitle,
songTitleWidth,
minWidth,
playAudio,
updateQueue,
putCommas
};
}, },
}; };
</script> </script>
@@ -103,11 +125,15 @@ export default {
position: relative; position: relative;
margin: 1rem; margin: 1rem;
tr { tbody tr {
cursor: pointer;
transition: all 0.5s ease;
&:hover { &:hover {
td { td {
background-color: rgba(255, 174, 0, 0.534); background-color: rgba(255, 174, 0, 0.534);
} }
transform: scale(0.99);
} }
} }
} }
+2 -2
View File
@@ -45,7 +45,7 @@
</div> </div>
</router-link> </router-link>
<hr /> <hr />
<router-link :to="{ name: 'FolderView', params: { path: '$home' } }"> <router-link :to="{ name: 'FolderView', params: { path: 'home' } }">
<div class="nav-button" id="folders-button"> <div class="nav-button" id="folders-button">
<div class="in"> <div class="in">
<div class="nav-icon image" id="folders-icon"></div> <div class="nav-icon image" id="folders-icon"></div>
@@ -54,7 +54,7 @@
</div> </div>
</router-link> </router-link>
<hr /> <hr />
<router-link :to="{ name: 'FolderView', params: { path: '$home' } }"> <router-link :to="{ name: 'FolderView', params: { path: 'home' } }">
<div class="nav-button" id="folders-button"> <div class="nav-button" id="folders-button">
<div class="in"> <div class="in">
<div class="nav-icon image" id="settings-icon"></div> <div class="nav-icon image" id="settings-icon"></div>
+17 -89
View File
@@ -14,12 +14,21 @@
<div> <div>
<div :class="{ hr: is_expanded }" class="all-items"> <div :class="{ hr: is_expanded }" class="all-items">
<div :class="{ v0: !is_expanded, v1: is_expanded }" class="scrollable"> <div :class="{ v0: !is_expanded, v1: is_expanded }" class="scrollable">
<div class="song-item h-1" v-for="song in songs" :key="song"> <div class="song-item h-1" v-for="song in queue" :key="song">
<div class="album-art image"></div> <div
class="album-art image"
:style="{
backgroundImage: `url(&quot;${song.image}&quot;)`,
}"
></div>
<div class="tags"> <div class="tags">
<p class="title">{{ song.title }}</p> <p class="title">{{ song.title }}</p>
<hr /> <hr />
<p class="artist">{{ song.artist }}</p> <p class="artist">
<span v-for="artist in putCommas(song.artists)" :key="artist">{{
artist
}}</span>
</p>
</div> </div>
</div> </div>
</div> </div>
@@ -30,97 +39,18 @@
<script> <script>
import { toRefs } from "@vue/reactivity"; import { toRefs } from "@vue/reactivity";
import putCommas from "@/composables/perks.js";
export default { export default {
props: ["up_next"], props: ["up_next", "queue"],
emits: ["expandQueue"],
setup(props, { emit }) { setup(props, { emit }) {
const songs = [
{
title: "Hard to forget",
artist: "Sam Hunt",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
{
title: "Bluebird",
artist: "Miranda Lambert",
},
{
title: "I called mama",
artist: "Ken Chesseny",
},
];
const is_expanded = toRefs(props).up_next; const is_expanded = toRefs(props).up_next;
let collapse = () => { let collapse = () => {
emit("expandQueue"); emit("expandQueue");
}; };
return { songs, collapse, is_expanded }; return { collapse, is_expanded, putCommas };
}, },
}; };
</script> </script>
@@ -177,10 +107,9 @@ export default {
.up-next .main-item .album-art { .up-next .main-item .album-art {
width: 4.5rem; width: 4.5rem;
height: 4.5rem; height: 4.5rem;
background-color: #ccc; background-image: url(../../assets/images/null.webp);
margin: 0 0.5rem 0 0; margin: 0 0.5rem 0 0;
border-radius: 0.5rem; border-radius: 0.5rem;
background-image: url(../../assets/images/htf.jpeg);
} }
.up-next .main-item .tags hr { .up-next .main-item .tags hr {
@@ -234,10 +163,9 @@ export default {
.up-next .all-items .album-art { .up-next .all-items .album-art {
width: 3rem; width: 3rem;
height: 3rem; height: 3rem;
background-color: #ccc;
margin: 0 0.5rem 0 0; margin: 0 0.5rem 0 0;
border-radius: 0.5rem; border-radius: 0.5rem;
background-image: url(../../assets/images/htf.jpeg); background-image: url(../../assets/images/null.webp);
} }
.up-next .all-items .song-item .artist { .up-next .all-items .song-item .artist {
+5
View File
@@ -0,0 +1,5 @@
const car = () => {
return;
};
export default car;
+2 -2
View File
@@ -12,13 +12,13 @@ const getData = async (path, last_id) => {
if (last_id) { if (last_id) {
url = `${folders_uri}/f/${encoded_path}::${last_id}`; url = `${folders_uri}/f/${encoded_path}::${last_id}`;
} else { } else {
url = url = `${folders_uri}/f/${encoded_path}`; url = url = `${folders_uri}/f/${encoded_path}::None`;
} }
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) { if (!res.ok) {
const message = `An erro has occured: ${res.status}`; const message = `An error has occured: ${res.status}`;
throw new Error(message); throw new Error(message);
} }
+27
View File
@@ -0,0 +1,27 @@
const url = "http://127.0.0.1:9876/get/queue";
const getQueue = async (type, id) => {
const res = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
type: type,
id: id,
}),
});
if (!res.ok) {
const message = `An error has occured: ${res.status}`;
throw new Error(message);
}
const data = await res.json();
localStorage.setItem("queue", JSON.stringify(data.songs));
return data.songs;
};
export default getQueue;
+15
View File
@@ -0,0 +1,15 @@
const putCommas = (artists) => {
let result = [];
artists.forEach((i, index, artists) => {
if (index !== artists.length - 1) {
result.push(i + ", ");
} else {
result.push(i);
}
});
return result;
};
export default putCommas;
+7 -1
View File
@@ -6,5 +6,11 @@ import router from "./router";
import "../src/assets/css/global.scss"; import "../src/assets/css/global.scss";
import "animate.css"; import "animate.css";
import mitt from "mitt";
createApp(App).use(router).mount("#app"); const emitter = mitt();
const app = createApp(App);
app.use(router);
app.provide('emitter', emitter);
app.mount('#app');
+7 -2
View File
@@ -5,7 +5,7 @@
</div> </div>
<div id="scrollable" ref="scrollable"> <div id="scrollable" ref="scrollable">
<FolderList :folders="folders" /> <FolderList :folders="folders" />
<SongList :songs="songs" /> <SongList :songs="songs" @updateQueue="updateQueue" />
</div> </div>
</div> </div>
</template> </template>
@@ -27,7 +27,7 @@ export default {
FolderList, FolderList,
SearchBox, SearchBox,
}, },
setup() { setup(props, context) {
const route = useRoute(); const route = useRoute();
const path = ref(route.params.path); const path = ref(route.params.path);
@@ -39,6 +39,10 @@ export default {
const scrollable = ref(null); const scrollable = ref(null);
const loading = ref(false); const loading = ref(false);
const updateQueue = (queue) => {
context.emit("sendQueue", queue);
};
onMounted(() => { onMounted(() => {
const getPathFolders = (path, last_id) => { const getPathFolders = (path, last_id) => {
loading.value = true; loading.value = true;
@@ -92,6 +96,7 @@ export default {
path, path,
scrollable, scrollable,
loading, loading,
updateQueue,
}; };
}, },
}; };
+5
View File
@@ -5935,6 +5935,11 @@ mississippi@^3.0.0:
stream-each "^1.1.0" stream-each "^1.1.0"
through2 "^2.0.0" through2 "^2.0.0"
mitt@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/mitt/-/mitt-3.0.0.tgz#69ef9bd5c80ff6f57473e8d89326d01c414be0bd"
integrity sha512-7dX2/10ITVyqh4aOSVI9gdape+t9l2/8QxHrFmUXu4EEUpdlxl6RudZUPZoc+zuY2hk1j7XxVroIVIan/pD/SQ==
mixin-deep@^1.2.0: mixin-deep@^1.2.0:
version "1.3.2" version "1.3.2"
resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566"