rewrite some fetch methods to use the useAxios hook

This commit is contained in:
geoffrey45 2022-06-16 14:18:45 +03:00
parent 600b267ce4
commit 92e2420174
17 changed files with 305 additions and 284 deletions

View File

@ -40,6 +40,7 @@ def get_albums():
def get_album():
"""Returns all the tracks in the given album."""
data = request.get_json()
print(data)
album, artist = data["album"], data["artist"]
albumhash = helpers.create_album_hash(album, artist)
@ -47,6 +48,10 @@ def get_album():
tracks = [models.Track(t) for t in tracks]
album = instances.album_instance.find_album_by_hash(albumhash)
if not album:
return {"error": "Album not found."}, 404
album = models.Album(album)
album.count = len(tracks)

View File

@ -12,7 +12,7 @@ from app.lib import playlistlib
from flask import Blueprint
from flask import request
from app.helpers import UseBisection, create_new_date
from app.helpers import Get, UseBisection, create_new_date
playlist_bp = Blueprint("playlist", __name__, url_prefix="/")
@ -104,7 +104,9 @@ def update_playlist(playlistid: str):
"thumb": None,
}
p = UseBisection(api.PLAYLISTS, "playlistid", [playlistid])()
playlists = Get.get_all_playlists()
p = UseBisection(playlists, "playlistid", [playlistid])()
p: models.Playlist = p[0]
if playlist is not None:

View File

@ -143,27 +143,12 @@ class Playlist:
self.lastUpdated = data["lastUpdated"]
self.count = len(self.pretracks)
def create_img_link(self, image: str):
if image:
return image
return "default.webp"
def update_count(self):
self.count = len(self.pretracks)
def add_track(self, track):
if track not in self.pretracks:
self.pretracks.append(track)
self.update_count()
self.lastUpdated = helpers.create_new_date()
else:
raise TrackExistsInPlaylist("Track already exists in playlist")
def update_desc(self, desc):
self.description = desc
def update_playlist(self, data: dict):
self.name = data["name"]
self.description = data["description"]

View File

@ -18,7 +18,7 @@
<script setup lang="ts">
import { onMounted } from "vue";
import { useRoute } from "vue-router";
import { createNewPlaylist } from "../../composables/playlists";
import { createNewPlaylist } from "../../composables/fetch/playlists";
import { Track } from "../../interfaces";
import { Notification, NotifType } from "../../stores/notification";
import usePlaylistStore from "@/stores/pages/playlists";
@ -43,22 +43,22 @@ emit("title", "New Playlist");
/**
* Create a new playlist. If this modal is called with a track,
* add the track to the new playlist.
* @param e Event
* @param {Event} e
*/
function create(e: Event) {
e.preventDefault();
const name = (e.target as HTMLFormElement).elements["name"].value;
if (name.trim()) {
createNewPlaylist(name, props.track).then((status) => {
createNewPlaylist(name, props.track).then(({ success, playlist }) => {
emit("hideModal");
if (!status.success) return;
if (!success) return;
if (route.name !== "Playlists") return;
setTimeout(() => {
playlistStore.addPlaylist(status.playlist);
playlistStore.addPlaylist(playlist);
}, 600);
});
} else {

View File

@ -41,7 +41,13 @@
/>
</div>
<div class="submit">
<input type="submit" id="updateplaylistsubmit" class="rounded" value="Update" @click="" />
<input
type="submit"
id="updateplaylistsubmit"
class="rounded"
value="Update"
@click=""
/>
</div>
</form>
</template>
@ -49,7 +55,7 @@
<script setup lang="ts">
import usePStore from "@/stores/pages/playlist";
import { onMounted } from "vue";
import { updatePlaylist } from "../../composables/playlists";
import { updatePlaylist } from "../../composables/fetch/playlists";
import { Playlist } from "../../interfaces";
const pStore = usePStore();
@ -105,8 +111,10 @@ function update_playlist(e: Event) {
if (!clicked) {
clicked = true;
const elem = document.getElementById("updateplaylistsubmit") as HTMLFormElement
elem.value = "Updating"
const elem = document.getElementById(
"updateplaylistsubmit"
) as HTMLFormElement;
elem.value = "Updating";
} else {
return;
}

View File

@ -1,65 +0,0 @@
import axios, { AxiosError } from "axios";
import state from "./state";
import { AlbumInfo, Track } from "../interfaces";
const getAlbumTracks = async (album: string, artist: string) => {
let data = {
info: <AlbumInfo>{},
tracks: <Track[]>[],
};
await axios
.post(state.settings.uri + "/album", {
album: album,
artist: artist,
})
.then((res) => {
data.info = res.data.info;
data.tracks = res.data.tracks;
})
.catch((err: AxiosError) => {
console.error(err);
});
return data;
};
const getAlbumArtists = async (album:string, artist:string) => {
let artists = [];
await axios
.post(state.settings.uri + "/album/artists", {
album: album,
artist: artist,
})
.then((res) => {
artists = res.data.artists;
})
.catch((err: AxiosError) => {
console.error(err);
});
return artists;
};
const getAlbumBio = async (album: string, albumartist: string) => {
let bio = null;
await axios
.post(state.settings.uri + "/album/bio", {
album: album,
albumartist: albumartist,
})
.then((res) => {
bio = res.data.bio;
})
.catch((err: AxiosError) => {
if (err.response.status === 404) {
bio = null;
}
});
return bio;
};
export { getAlbumTracks, getAlbumArtists, getAlbumBio };

View File

@ -0,0 +1,66 @@
import axios, { AxiosError } from "axios";
import state from "../state";
import { AlbumInfo, Track } from "../../interfaces";
import useAxios from "../useAxios";
const getAlbumTracks = async (album: string, artist: string) => {
const url = state.settings.uri + "/album";
interface AlbumData {
info: AlbumInfo;
tracks: Track[];
}
const { data, status } = await useAxios({
url,
props: {
album: album,
artist: artist,
},
});
if (status == 404) {
return {
info: {},
tracks: [],
};
}
return data as AlbumData;
};
const getAlbumArtists = async (album: string, artist: string) => {
const { data, error } = await useAxios({
url: state.settings.uri + "/album/artists",
props: {
album: album,
artist: artist,
},
});
if (error) {
console.error(error);
}
return data.artists;
};
const getAlbumBio = async (album: string, albumartist: string) => {
const { data, status } = await useAxios({
url: state.settings.uri + "/album/bio",
props: {
album: album,
albumartist: albumartist,
},
});
if (data) {
return data.bio;
}
if (status == 404) {
return null;
}
};
export { getAlbumTracks, getAlbumArtists, getAlbumBio };

View File

@ -0,0 +1,130 @@
import axios from "axios";
import { Playlist, Track } from "../../interfaces";
import { Notification, NotifType } from "../../stores/notification";
import state from "../state";
import useAxios from "../useAxios";
/**
* Creates a new playlist on the server.
* @param playlist_name The name of the playlist to create.
*/
async function createNewPlaylist(playlist_name: string, track?: Track) {
const { data, status } = await useAxios({
url: state.settings.uri + "/playlist/new",
props: {
name: playlist_name,
},
});
if (status == 201) {
new Notification("✅ Playlist created successfullly!");
if (track) {
setTimeout(() => {
addTrackToPlaylist(data.playlist, track);
}, 1000);
}
return {
success: true,
playlist: data.playlist as Playlist,
};
}
new Notification("That playlist already exists", NotifType.Error);
return {
success: false,
playlist: <Playlist>{},
};
}
/**
* Fetches all playlists from the server.
* @returns {Promise<Playlist[]>} A promise that resolves to an array of playlists.
*/
async function getAllPlaylists(): Promise<Playlist[]> {
const { data, error } = await useAxios({
url: state.settings.uri + "/playlists",
get: true,
});
if (error) console.error(error);
if (data) {
return data.data;
}
return [];
}
async function addTrackToPlaylist(playlist: Playlist, track: Track) {
const uri = `${state.settings.uri}/playlist/${playlist.playlistid}/add`;
const { status } = await useAxios({
url: uri,
props: {
track: track.trackid,
},
});
if (status == 409) {
new Notification("Track already exists in playlist", NotifType.Info);
return;
}
new Notification(track.title + " added to " + playlist.name);
}
async function getPlaylist(pid: string) {
const uri = state.settings.uri + "/playlist/" + pid;
interface PlaylistData {
info: Playlist;
tracks: Track[];
}
const { data, error } = await useAxios({
url: uri,
get: true,
});
if (error) {
new Notification("Something funny happened!", NotifType.Error);
}
if (data) {
return data as PlaylistData;
}
return null;
}
async function updatePlaylist(pid: string, playlist: FormData, pStore: any) {
const uri = state.settings.uri + "/playlist/" + pid + "/update";
const { data, error } = await useAxios({
url: uri,
put: true,
props: playlist,
headers: {
"Content-Type": "multipart/form-data",
},
});
if (error) {
new Notification("Something funny happened!", NotifType.Error);
}
if (data) {
pStore.updatePInfo(data.data);
new Notification("Playlist updated!");
}
}
export {
createNewPlaylist,
getAllPlaylists,
addTrackToPlaylist,
getPlaylist,
updatePlaylist,
};

View File

@ -1,22 +1,31 @@
import axios from "axios";
import { Folder, Track } from "../interfaces";
import state from "./state";
import useAxios from "./useAxios";
export default async function (path: string) {
let tracks = Array<Track>();
let folders = Array<Folder>();
interface FolderData {
tracks: Track[];
folders: Folder[];
}
await axios
.post(`${state.settings.uri}/folder`, {
const { data, error } = await useAxios({
url: `${state.settings.uri}/folder`,
props: {
folder: path,
})
.then((res) => {
tracks = res.data.tracks;
folders = res.data.folders;
})
.catch((err) => {
console.error(err);
});
},
});
return { tracks, folders };
if (error) {
console.error(error);
}
if (data) {
return data as FolderData;
}
return <FolderData>{
tracks: [],
folders: [],
};
}

View File

@ -1,145 +0,0 @@
import axios from "axios";
import { Playlist, Track } from "../interfaces";
import { Notification, NotifType } from "../stores/notification";
import state from "./state";
/**
* Creates a new playlist on the server.
* @param playlist_name The name of the playlist to create.
*/
async function createNewPlaylist(playlist_name: string, track?: Track) {
let status = {
success: false,
playlist: <Playlist>{},
};
await axios
.post(state.settings.uri + "/playlist/new", {
name: playlist_name,
})
.then((res) => {
new Notification("✅ Playlist created successfullly!");
if (track) {
setTimeout(() => {
addTrackToPlaylist(res.data.playlist, track);
}, 1000);
}
status.success = true;
status.playlist = res.data.playlist;
})
.catch((err) => {
if (err.response.status == 409) {
new Notification(
"That playlist already exists",
NotifType.Error
);
}
});
return status;
}
/**
* Fetches all playlists from the server.
* @returns {Promise<Playlist[]>} A promise that resolves to an array of playlists.
*/
async function getAllPlaylists(): Promise<Playlist[]> {
let playlists = <Playlist[]>[];
const newLocal = `${state.settings.uri}/playlists`;
await axios
.get(newLocal)
.then((res) => {
playlists = res.data.data;
})
.catch((err) => {
console.error(err);
});
return playlists;
}
async function addTrackToPlaylist(playlist: Playlist, track: Track) {
const uri = `${state.settings.uri}/playlist/${playlist.playlistid}/add`;
await axios
.post(uri, { track: track.trackid })
.then(() => {
new Notification(track.title + " added to " + playlist.name);
})
.catch((error) => {
if (error.response.status == 409) {
new Notification("Track already exists in playlist", NotifType.Info);
}
});
}
async function getPTracks(playlistid: string) {
const uri = state.settings.uri + "/playlist/" + playlistid;
let tracks: Track[] = [];
await axios
.get(uri)
.then((res) => {
tracks = res.data.data;
})
.catch((err) => {
new Notification("Something funny happened!", NotifType.Error);
throw new Error(err);
});
return tracks;
}
async function getPlaylist(pid: string) {
const uri = state.settings.uri + "/playlist/" + pid;
let playlist = {
info: {},
tracks: <Track[]>[],
};
await axios
.get(uri)
.then((res) => {
playlist.info = res.data.info;
playlist.tracks = res.data.tracks;
})
.catch((err) => {
new Notification("Something funny happened!", NotifType.Error);
throw new Error(err);
});
return playlist;
}
async function updatePlaylist(pid: string, playlist: FormData, pStore: any) {
const uri = state.settings.uri + "/playlist/" + pid + "/update";
await axios
.put(uri, playlist, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
pStore.updatePInfo(res.data.data);
new Notification("Playlist updated!");
})
.catch((err) => {
new Notification("Something funny happened!", NotifType.Error);
throw new Error(err);
});
}
export {
createNewPlaylist,
getAllPlaylists,
addTrackToPlaylist,
getPTracks,
getPlaylist,
updatePlaylist,
};

View File

@ -0,0 +1,32 @@
import { FetchProps } from "../interfaces";
import axios, { AxiosError, AxiosResponse } from "axios";
export default async (args: FetchProps) => {
let data: any = null;
let error: string = null;
let status: number = null;
function getAxios() {
if (args.get) {
return axios.get(args.url, args.props);
}
if (args.put) {
return axios.put(args.url, args.props, args.headers);
}
return axios.post(args.url, args.props);
}
await getAxios()
.then((res: AxiosResponse) => {
data = res.data;
status = res.status;
})
.catch((err: AxiosError) => {
error = err.message as string;
status = err.response.status as number;
});
return { data, error, status };
};

View File

@ -1,4 +1,4 @@
import useQStore from "@/stores/queue"
import useQStore from "@/stores/queue";
let key_down_fired = false;
@ -9,12 +9,12 @@ function focusSearchBox() {
}
export default function (queue: typeof useQStore) {
const q = queue()
window.addEventListener("keydown", (e: any) => {
let target = e.target;
const q = queue();
window.addEventListener("keydown", (e: KeyboardEvent) => {
let target = e.target as HTMLElement;
let ctrlKey = e.ctrlKey;
function FocusedOnInput(target: any) {
function FocusedOnInput(target: HTMLElement) {
return target.tagName === "INPUT" || target.tagName === "TEXTAREA";
}

View File

@ -1,7 +1,7 @@
import { Playlist, Track } from "../interfaces";
import Router from "../router";
import { Option } from "../interfaces";
import { getAllPlaylists, addTrackToPlaylist } from "../composables/playlists";
import { getAllPlaylists, addTrackToPlaylist } from "../composables/fetch/playlists";
import useQueueStore from "../stores/queue";
import useModalStore from "../stores/modal";

View File

@ -1,6 +1,6 @@
import { FromOptions, NotifType } from "./composables/enums";
interface Track {
export interface Track {
trackid: string;
title: string;
album?: string;
@ -16,14 +16,14 @@ interface Track {
disknumber?: number;
}
interface Folder {
export interface Folder {
name: string;
path: string;
trackcount: number;
subdircount: number;
}
interface AlbumInfo {
export interface AlbumInfo {
title: string;
artist: string;
count: number;
@ -35,12 +35,12 @@ interface AlbumInfo {
is_single: boolean;
}
interface Artist {
export interface Artist {
name: string;
image: string;
}
interface Option {
export interface Option {
type?: string;
label?: string;
action?: Function;
@ -49,7 +49,7 @@ interface Option {
critical?: Boolean;
}
interface Playlist {
export interface Playlist {
playlistid: string;
name: string;
description?: string;
@ -60,49 +60,42 @@ interface Playlist {
thumb?: string;
}
interface Notif {
export interface Notif {
text: string;
type: NotifType;
}
interface fromFolder {
export interface fromFolder {
type: FromOptions;
path: string;
name: string;
}
interface fromAlbum {
export interface fromAlbum {
type: FromOptions;
name: string;
albumartist: string;
}
interface fromPlaylist {
export interface fromPlaylist {
type: FromOptions;
name: string;
playlistid: string;
}
interface fromSearch {
export interface fromSearch {
type: FromOptions;
query: string;
}
interface subPath {
export interface subPath {
name: string;
path: string;
active: boolean;
}
export {
Track,
Folder,
AlbumInfo,
Artist,
Option,
Playlist,
Notif,
fromFolder,
fromAlbum,
fromPlaylist,
fromSearch,
subPath,
};
export interface FetchProps {
url: string;
props?: {};
get?: boolean;
put?: boolean;
headers?: {};
}

View File

@ -4,7 +4,7 @@ import {
getAlbumTracks,
getAlbumArtists,
getAlbumBio,
} from "../../composables/album";
} from "../../composables/fetch/album";
export default defineStore("album", {
state: () => ({
@ -21,6 +21,7 @@ export default defineStore("album", {
* @param albumartist artist of the album
*/
async fetchTracksAndArtists(title: string, albumartist: string) {
const tracks = await getAlbumTracks(title, albumartist);
const artists = await getAlbumArtists(title, albumartist);

View File

@ -1,5 +1,5 @@
import { defineStore } from "pinia";
import { getPlaylist } from "../../composables/playlists";
import { getPlaylist } from "../../composables/fetch/playlists";
import { Track, Playlist } from "../../interfaces";
export default defineStore("playlist-tracks", {

View File

@ -1,6 +1,6 @@
import { defineStore } from "pinia";
import { Playlist } from "../../interfaces";
import { getAllPlaylists } from "../../composables/playlists";
import { getAllPlaylists } from "../../composables/fetch/playlists";
export default defineStore("playlists", {
state: () => ({