Docs + Pretty code

This commit is contained in:
killer069 2021-10-12 14:09:14 +05:30
parent 229bbc7a11
commit bd4afbe82a
11 changed files with 118 additions and 89 deletions

View File

@ -42,6 +42,33 @@ _This creates basic spotify / soundcloud / youtube data to be stored locally._
authorization() //After then you will be asked about type of data you want to create and then follow the steps properly.
```
### setToken(options : `TokenOptions`)
_This sets token without using file._
```js
setToken({
spotify : {
client_id : "ID"
client_secret : "Secret"
refresh_token : "Token"
market : "Country Code"
}
}) // Setting Spotify Token [ To get refresh_token, just run through authorization, and set file save to No ]
setToken({
soundcloud : {
client_id : "ID"
}
}) // Setting SoundCloud Token
setToken({
youtube : {
cookie : "Cookies"
}
}) // Warning : Using setToken for youtube cookies will only update cookies present in memory only.
```
### Search
#### SearchOptions :

View File

@ -83,8 +83,7 @@ export function request(req_url: string, options: RequestOpts = { method: 'GET'
res.setEncoding('utf-8');
res.on('data', (c) => (data += c));
res.on('end', () => resolve(data));
}
else {
} else {
let cookies_added = false;
if (options.cookies) {
let cook = getCookies();
@ -115,7 +114,7 @@ export function request(req_url: string, options: RequestOpts = { method: 'GET'
} else if (res.statusCode > 400) {
reject(new Error(`GOT ${res.statusCode} from proxy request`));
}
resolve(res.body)
resolve(res.body);
}
});
}
@ -140,7 +139,7 @@ export function request(req_url: string, options: RequestOpts = { method: 'GET'
function proxy_getter(req_url: string, req_proxy: ProxyOptions[], headers?: Object): Promise<Proxy> {
return new Promise((resolve, reject) => {
const proxy: string | ProxyOpts = req_proxy[randomIntFromInterval(0, req_proxy.length)];
const parsed_url = new URL(req_url)
const parsed_url = new URL(req_url);
let opts: ProxyOpts;
if (typeof proxy === 'string') {
const parsed = new URL(proxy);
@ -175,14 +174,14 @@ function proxy_getter(req_url : string, req_proxy : ProxyOptions[], headers? : O
});
}
req.on('connect', async function (res, socket) {
const conn_proxy = new Proxy(parsed_url, { method : "GET", socket : socket, headers : headers })
await conn_proxy.fetch()
socket.end()
resolve(conn_proxy)
})
const conn_proxy = new Proxy(parsed_url, { method: 'GET', socket: socket, headers: headers });
await conn_proxy.fetch();
socket.end();
resolve(conn_proxy);
});
req.on('error', (e: Error) => reject(e));
req.end();
})
});
}
/**

View File

@ -275,8 +275,8 @@ export class Stream {
this.request = stream;
stream.on('data', (c) => {
this.stream.push(c)
})
this.stream.push(c);
});
stream.on('end', () => {
if (this.downloaded_time >= 300) return;
else this.loop();

View File

@ -153,5 +153,5 @@ function parseHlsFormats(data: SoundCloudTrackFormat[]) {
}
export function setSoundCloudToken(options: SoundDataOptions) {
soundData = options
soundData = options;
}

View File

@ -5,7 +5,7 @@ import fs from 'fs';
let spotifyData: SpotifyDataOptions;
if (fs.existsSync('.data/spotify.data')) {
spotifyData = JSON.parse(fs.readFileSync('.data/spotify.data').toString());
spotifyData.file = true
spotifyData.file = true;
}
/**
* Spotify Data options that are stored in spotify.data file.
@ -21,7 +21,7 @@ export interface SpotifyDataOptions {
expires_in?: number;
expiry?: number;
market?: string;
file? : boolean
file?: boolean;
}
const pattern = /^((https:)?\/\/)?open.spotify.com\/(track|album|playlist)\//;
@ -119,11 +119,11 @@ export async function SpotifyAuthorize(data: SpotifyDataOptions, file : boolean)
};
if (file) fs.writeFileSync('.data/spotify.data', JSON.stringify(spotifyData, undefined, 4));
else {
console.log(`Client ID : ${spotifyData.client_id}`)
console.log(`Client Secret : ${spotifyData.client_secret}`)
console.log(`Refresh Token : ${spotifyData.refresh_token}`)
console.log(`Market : ${spotifyData.market}`)
console.log(`\nPaste above info in setToken function.`)
console.log(`Client ID : ${spotifyData.client_id}`);
console.log(`Client Secret : ${spotifyData.client_secret}`);
console.log(`Refresh Token : ${spotifyData.refresh_token}`);
console.log(`Market : ${spotifyData.market}`);
console.log(`\nPaste above info in setToken function.`);
}
return true;
}
@ -212,7 +212,7 @@ export async function refreshToken(): Promise<boolean> {
}
export function setSpotifyToken(options: SpotifyDataOptions) {
spotifyData = options
spotifyData.file = false
refreshToken()
spotifyData = options;
spotifyData.file = false;
refreshToken();
}

View File

@ -102,8 +102,8 @@ export class LiveStreaming {
}
this.request = stream;
stream.on('data', (c) => {
this.stream.push(c)
})
this.stream.push(c);
});
stream.on('end', () => {
this.packet_count++;
resolve('');
@ -204,8 +204,8 @@ export class Stream {
}
this.request = stream;
stream.on('data', (c) => {
this.stream.push(c)
})
this.stream.push(c);
});
stream.once('error', async (err) => {
this.cleanup();

View File

@ -3,7 +3,7 @@ import fs from 'fs';
let youtubeData: youtubeDataOptions;
if (fs.existsSync('.data/youtube.data')) {
youtubeData = JSON.parse(fs.readFileSync('.data/youtube.data').toString());
youtubeData.file = true
youtubeData.file = true;
}
interface youtubeDataOptions {
@ -29,11 +29,12 @@ export function setCookie(key: string, value: string): boolean {
}
export function uploadCookie() {
if (youtubeData.cookie && youtubeData.file) fs.writeFileSync('.data/youtube.data', JSON.stringify(youtubeData, undefined, 4));
if (youtubeData.cookie && youtubeData.file)
fs.writeFileSync('.data/youtube.data', JSON.stringify(youtubeData, undefined, 4));
}
export function setCookieToken(options: { cookie: string }) {
let cook = options.cookie
let cook = options.cookie;
let cookie: Object = {};
cook.split(';').forEach((x) => {
const arr = x.split('=');
@ -42,6 +43,6 @@ export function setCookieToken(options : { cookie : string }){
const value = arr.join('=').trim();
Object.assign(cookie, { [key]: value });
});
youtubeData = { cookie }
youtubeData.file = false
youtubeData = { cookie };
youtubeData.file = false;
}

View File

@ -30,7 +30,8 @@ export function yt_validate(url: string): 'playlist' | 'video' | 'search' | fals
if (url.match(video_pattern)) {
let id: string;
if (url.includes('youtu.be/')) id = url.split('youtu.be/')[1].split(/(\?|\/|&)/)[0];
else if (url.includes('youtube.com/embed/')) id = url.split('youtube.com/embed/')[1].split(/(\?|\/|&)/)[0];
else if (url.includes('youtube.com/embed/'))
id = url.split('youtube.com/embed/')[1].split(/(\?|\/|&)/)[0];
else id = url.split('watch?v=')[1].split(/(\?|\/|&)/)[0];
if (id.match(video_id_pattern)) return 'video';
else return false;
@ -57,7 +58,8 @@ export function extractID(url: string): string {
if (url.indexOf('list=') === -1) {
let video_id: string;
if (url.includes('youtu.be/')) video_id = url.split('youtu.be/')[1].split(/(\?|\/|&)/)[0];
else if (url.includes('youtube.com/embed/')) video_id = url.split('youtube.com/embed/')[1].split(/(\?|\/|&)/)[0];
else if (url.includes('youtube.com/embed/'))
video_id = url.split('youtube.com/embed/')[1].split(/(\?|\/|&)/)[0];
else video_id = url.split('watch?v=')[1].split(/(\?|\/|&)/)[0];
return video_id;
} else {

View File

@ -1,7 +1,7 @@
export { playlist_info, video_basic_info, video_info, yt_validate, extractID, YouTube, YouTubeStream } from './YouTube';
export { spotify, sp_validate, refreshToken, is_expired, Spotify } from './Spotify';
export { soundcloud, so_validate, SoundCloud, SoundCloudStream } from './SoundCloud';
export { setToken } from './token'
export { setToken } from './token';
enum AudioPlayerStatus {
Idle = 'idle',
@ -117,8 +117,8 @@ export function authorization(): void {
});
ask.question('Do you want to save data in a file ? (Yes / No): ', (msg) => {
let file: boolean;
if(msg.toLowerCase() === 'yes') file = true
else if(msg.toLowerCase() === 'no') file = false
if (msg.toLowerCase() === 'yes') file = true;
else if (msg.toLowerCase() === 'no') file = false;
else {
console.log("That option doesn't exist. Try again...");
ask.close();
@ -171,7 +171,7 @@ export function authorization(): void {
});
} else if (msg.toLowerCase().startsWith('sc')) {
if (!file) {
console.log("You already had a client ID, just paste that in setToken function.");
console.log('You already had a client ID, just paste that in setToken function.');
ask.close();
return;
}
@ -192,7 +192,7 @@ export function authorization(): void {
});
} else if (msg.toLowerCase().startsWith('yo')) {
if (!file) {
console.log("You already had cookie, just paste that in setToken function.");
console.log('You already had cookie, just paste that in setToken function.');
ask.close();
return;
}
@ -220,12 +220,12 @@ export function authorization(): void {
ask.close();
}
});
})
});
}
export function attachListeners(player: EventEmitter, resource: YouTubeStream | SoundCloudStream) {
const pauseListener = () => resource.pause()
const resumeListener = () => resource.resume()
const pauseListener = () => resource.pause();
const resumeListener = () => resource.resume();
player.on(AudioPlayerStatus.Paused, pauseListener);
player.on(AudioPlayerStatus.AutoPaused, pauseListener);
player.on(AudioPlayerStatus.Playing, resumeListener);

View File

@ -1,24 +1,24 @@
import { setSoundCloudToken } from "./SoundCloud";
import { setSpotifyToken } from "./Spotify";
import { setCookieToken } from "./YouTube/utils/cookie";
import { setSoundCloudToken } from './SoundCloud';
import { setSpotifyToken } from './Spotify';
import { setCookieToken } from './YouTube/utils/cookie';
interface tokenOptions {
spotify?: {
client_id : string
client_id: string;
client_secret: string;
refresh_token : string
market : string
}
refresh_token: string;
market: string;
};
soundcloud?: {
client_id : string
}
client_id: string;
};
youtube?: {
cookie : string
}
cookie: string;
};
}
export function setToken(options: tokenOptions) {
if(options.spotify) setSpotifyToken(options.spotify)
if(options.soundcloud) setSoundCloudToken(options.soundcloud)
if(options.youtube) setCookieToken(options.youtube)
if (options.spotify) setSpotifyToken(options.spotify);
if (options.soundcloud) setSoundCloudToken(options.soundcloud);
if (options.youtube) setCookieToken(options.youtube);
}