Comments are now added in functions

This commit is contained in:
killer069
2021-09-29 20:23:16 +05:30
parent 8e96e24aeb
commit 5d6b9167ed
15 changed files with 342 additions and 149 deletions

View File

@@ -26,8 +26,10 @@ interface SpotifyCopyright {
text: string;
type: string;
}
export class SpotifyVideo {
/**
* Class for Spotify Track
*/
export class SpotifyTrack {
name: string;
type: 'track' | 'playlist' | 'album';
id: string;
@@ -36,8 +38,8 @@ export class SpotifyVideo {
durationInSec: number;
durationInMs: number;
artists: SpotifyArtists[];
album: SpotifyTrackAlbum;
thumbnail: SpotifyThumbnail;
album: SpotifyTrackAlbum | undefined;
thumbnail: SpotifyThumbnail | undefined;
constructor(data: any) {
this.name = data.name;
this.id = data.id;
@@ -55,15 +57,19 @@ export class SpotifyVideo {
});
});
this.artists = artists;
this.album = {
name: data.album.name,
url: data.external_urls.spotify,
id: data.album.id,
release_date: data.album.release_date,
release_date_precision: data.album.release_date_precision,
total_tracks: data.album.total_tracks
};
this.thumbnail = data.album.images[0];
if (!data.album?.name) this.album = undefined;
else {
this.album = {
name: data.album.name,
url: data.external_urls.spotify,
id: data.album.id,
release_date: data.album.release_date,
release_date_precision: data.album.release_date_precision,
total_tracks: data.album.total_tracks
};
}
if (!data.album?.images?.[0]) this.thumbnail = undefined;
else this.thumbnail = data.album.images[0];
}
toJSON() {
@@ -81,7 +87,9 @@ export class SpotifyVideo {
};
}
}
/**
* Class for Spotify Playlist
*/
export class SpotifyPlaylist {
name: string;
type: 'track' | 'playlist' | 'album';
@@ -93,7 +101,7 @@ export class SpotifyPlaylist {
owner: SpotifyArtists;
tracksCount: number;
private spotifyData: SpotifyDataOptions;
private fetched_tracks: Map<string, SpotifyVideo[]>;
private fetched_tracks: Map<string, SpotifyTrack[]>;
constructor(data: any, spotifyData: SpotifyDataOptions) {
this.name = data.name;
this.type = 'playlist';
@@ -108,9 +116,9 @@ export class SpotifyPlaylist {
id: data.owner.id
};
this.tracksCount = Number(data.tracks.total);
const videos: SpotifyVideo[] = [];
const videos: SpotifyTrack[] = [];
data.tracks.items.forEach((v: any) => {
videos.push(new SpotifyVideo(v.track));
videos.push(new SpotifyTrack(v.track));
});
this.fetched_tracks = new Map();
this.fetched_tracks.set('1', videos);
@@ -136,11 +144,11 @@ export class SpotifyPlaylist {
}
}
).catch((err) => reject(`Response Error : \n${err}`));
const videos: SpotifyVideo[] = [];
const videos: SpotifyTrack[] = [];
if (typeof response !== 'string') return;
const json_data = JSON.parse(response);
json_data.items.forEach((v: any) => {
videos.push(new SpotifyVideo(v.track));
videos.push(new SpotifyTrack(v.track));
});
this.fetched_tracks.set(`${i}`, videos);
resolve('Success');
@@ -163,7 +171,7 @@ export class SpotifyPlaylist {
get total_tracks() {
const page_number: number = this.total_pages;
return (page_number - 1) * 100 + (this.fetched_tracks.get(`${page_number}`) as SpotifyVideo[]).length;
return (page_number - 1) * 100 + (this.fetched_tracks.get(`${page_number}`) as SpotifyTrack[]).length;
}
toJSON() {
@@ -179,7 +187,9 @@ export class SpotifyPlaylist {
};
}
}
/**
* Class for Spotify Album
*/
export class SpotifyAlbum {
name: string;
type: 'track' | 'playlist' | 'album';
@@ -192,7 +202,7 @@ export class SpotifyAlbum {
release_date_precision: string;
trackCount: number;
private spotifyData: SpotifyDataOptions;
private fetched_tracks: Map<string, SpotifyTracks[]>;
private fetched_tracks: Map<string, SpotifyTrack[]>;
constructor(data: any, spotifyData: SpotifyDataOptions) {
this.name = data.name;
this.type = 'album';
@@ -212,9 +222,9 @@ export class SpotifyAlbum {
this.release_date = data.release_date;
this.release_date_precision = data.release_date_precision;
this.trackCount = data.total_tracks;
const videos: SpotifyTracks[] = [];
const videos: SpotifyTrack[] = [];
data.tracks.items.forEach((v: any) => {
videos.push(new SpotifyTracks(v));
videos.push(new SpotifyTrack(v));
});
this.fetched_tracks = new Map();
this.fetched_tracks.set('1', videos);
@@ -240,11 +250,11 @@ export class SpotifyAlbum {
}
}
).catch((err) => reject(`Response Error : \n${err}`));
const videos: SpotifyTracks[] = [];
const videos: SpotifyTrack[] = [];
if (typeof response !== 'string') return;
const json_data = JSON.parse(response);
json_data.items.forEach((v: any) => {
videos.push(new SpotifyTracks(v));
videos.push(new SpotifyTrack(v));
});
this.fetched_tracks.set(`${i}`, videos);
resolve('Success');
@@ -267,7 +277,7 @@ export class SpotifyAlbum {
get total_tracks() {
const page_number: number = this.total_pages;
return (page_number - 1) * 100 + (this.fetched_tracks.get(`${page_number}`) as SpotifyVideo[]).length;
return (page_number - 1) * 100 + (this.fetched_tracks.get(`${page_number}`) as SpotifyTrack[]).length;
}
toJSON() {
@@ -284,45 +294,3 @@ export class SpotifyAlbum {
};
}
}
class SpotifyTracks {
name: string;
type: 'track' | 'playlist' | 'album';
id: string;
url: string;
explicit: boolean;
durationInSec: number;
durationInMs: number;
artists: SpotifyArtists[];
constructor(data: any) {
this.name = data.name;
this.id = data.id;
this.type = 'track';
this.url = data.external_urls.spotify;
this.explicit = data.explicit;
this.durationInMs = data.duration_ms;
this.durationInSec = Math.round(this.durationInMs / 1000);
const artists: SpotifyArtists[] = [];
data.artists.forEach((v: any) => {
artists.push({
name: v.name,
id: v.id,
url: v.external_urls.spotify
});
});
this.artists = artists;
}
toJSON() {
return {
name: this.name,
id: this.id,
type: this.type,
url: this.url,
explicit: this.explicit,
durationInMs: this.durationInMs,
durationInSec: this.durationInSec,
artists: this.artists
};
}
}

View File

@@ -1,12 +1,14 @@
import { request } from '../YouTube/utils/request';
import { SpotifyAlbum, SpotifyPlaylist, SpotifyVideo } from './classes';
import { SpotifyAlbum, SpotifyPlaylist, SpotifyTrack } from './classes';
import fs from 'fs';
let spotifyData: SpotifyDataOptions;
if (fs.existsSync('.data/spotify.data')) {
spotifyData = JSON.parse(fs.readFileSync('.data/spotify.data').toString());
}
/**
* Spotify Data options that are stored in spotify.data file.
*/
export interface SpotifyDataOptions {
client_id: string;
client_secret: string;
@@ -21,8 +23,12 @@ export interface SpotifyDataOptions {
}
const pattern = /^((https:)?\/\/)?open.spotify.com\/(track|album|playlist)\//;
export async function spotify(url: string): Promise<SpotifyAlbum | SpotifyPlaylist | SpotifyVideo> {
/**
* Function to get Playlist | Album | Track
* @param url url of spotify from which you want info
* @returns Spotify type.
*/
export async function spotify(url: string): Promise<Spotify> {
if (!spotifyData) throw new Error('Spotify Data is missing\nDid you forgot to do authorization ?');
if (!url.match(pattern)) throw new Error('This is not a Spotify URL');
if (url.indexOf('track/') !== -1) {
@@ -35,7 +41,7 @@ export async function spotify(url: string): Promise<SpotifyAlbum | SpotifyPlayli
return err;
});
if (response instanceof Error) throw response;
return new SpotifyVideo(JSON.parse(response));
return new SpotifyTrack(JSON.parse(response));
} else if (url.indexOf('album/') !== -1) {
const albumID = url.split('album/')[1].split('&')[0].split('?')[0];
const response = await request(`https://api.spotify.com/v1/albums/${albumID}?market=${spotifyData.market}`, {
@@ -63,7 +69,11 @@ export async function spotify(url: string): Promise<SpotifyAlbum | SpotifyPlayli
return new SpotifyPlaylist(JSON.parse(response), spotifyData);
} else throw new Error('URL is out of scope for play-dl.');
}
/**
* Function to validate Spotify url
* @param url url for validation
* @returns type of url or false.
*/
export function sp_validate(url: string): 'track' | 'playlist' | 'album' | false {
if (!url.match(pattern)) return false;
if (url.indexOf('track/') !== -1) {
@@ -74,7 +84,11 @@ export function sp_validate(url: string): 'track' | 'playlist' | 'album' | false
return 'playlist';
} else return false;
}
/**
* Fuction for authorizing for spotify data.
* @param data Sportify Data options to validate
* @returns boolean.
*/
export async function SpotifyAuthorize(data: SpotifyDataOptions): Promise<boolean> {
const response = await request(`https://accounts.spotify.com/api/token`, {
headers: {
@@ -104,20 +118,31 @@ export async function SpotifyAuthorize(data: SpotifyDataOptions): Promise<boolea
fs.writeFileSync('.data/spotify.data', JSON.stringify(spotifyData, undefined, 4));
return true;
}
/**
* Function to check if authorization token is expired or not.
* @returns boolean
*/
export function is_expired(): boolean {
if (Date.now() >= (spotifyData.expiry as number)) return true;
else return false;
}
export type Spotify = SpotifyAlbum | SpotifyPlaylist | SpotifyVideo;
/**
* type for Spotify Class
*/
export type Spotify = SpotifyAlbum | SpotifyPlaylist | SpotifyTrack;
/**
* Function for searching songs on Spotify
* @param query searching query
* @param type "album" | "playlist" | "track"
* @param limit max no of results
* @returns Spotify type.
*/
export async function sp_search(
query: string,
type: 'album' | 'playlist' | 'track',
limit: number = 10
): Promise<Spotify[]> {
const results: (SpotifyAlbum | SpotifyPlaylist | SpotifyVideo)[] = [];
const results: Spotify[] = [];
if (!spotifyData) throw new Error('Spotify Data is missing\nDid you forgot to do authorization ?');
if (query.length === 0) throw new Error('Pass some query to search.');
if (limit > 50 || limit < 0) throw new Error(`You crossed limit range of Spotify [ 0 - 50 ]`);
@@ -137,7 +162,7 @@ export async function sp_search(
const json_data = JSON.parse(response);
if (type === 'track') {
json_data.tracks.items.forEach((track: any) => {
results.push(new SpotifyVideo(track));
results.push(new SpotifyTrack(track));
});
} else if (type === 'album') {
json_data.albums.items.forEach((album: any) => {
@@ -150,7 +175,10 @@ export async function sp_search(
}
return results;
}
/**
* Function to refresh Token
* @returns boolean to check whether token is refreshed or not
*/
export async function refreshToken(): Promise<boolean> {
const response = await request(`https://accounts.spotify.com/api/token`, {
headers: {