fix all lint errors

This commit is contained in:
KGT1 2020-09-21 05:30:39 +02:00
parent 31420a22cc
commit f020613759
11 changed files with 327 additions and 358 deletions

View File

@ -11,5 +11,10 @@
"ecmaVersion": 12
},
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"],
"indent": ["error", "tab"],
"no-unused-vars": ["error"],
"no-tabs":["error",{"allowIndentationTabs":true}]
}
}

View File

@ -6,7 +6,8 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node src/index.js",
"postinstall": "npx patch-package"
"postinstall": "npx patch-package",
"lint": "npx eslint src/ & npx eslint parseENV.js"
},
"repository": {
"type": "git",

View File

@ -1,20 +1,13 @@
const fs = require('fs');
const filename='./config.json';
const fs = require("fs");
const filename = "./config.json";
const configfile = require(filename);
if(!configfile["discord-prefix"])
configfile["discord-prefix"]=process.env.DISCORD_PREFIX;
if(!configfile["token"])
configfile["token"]=process.env.DISCORD_TOKEN;
if(!configfile["server-adress"])
configfile["server-adress"]=process.env.JELLYFIN_SERVER_ADDRESS;
if(!configfile["jellyfin-username"])
configfile["jellyfin-username"]=process.env.JELLYFIN_USERNAME;
if(!configfile["jellyfin-password"])
configfile["jellyfin-password"]=process.env.JELLYFIN_PASSWORD;
if(!configfile["jellyfin-app-name"])
configfile["jellyfin-app-name"]=process.env.JELLYFIN_APP_NAME;
if (!configfile["discord-prefix"]) { configfile["discord-prefix"] = process.env.DISCORD_PREFIX; }
if (!configfile.token) { configfile.token = process.env.DISCORD_TOKEN; }
if (!configfile["server-adress"]) { configfile["server-adress"] = process.env.JELLYFIN_SERVER_ADDRESS; }
if (!configfile["jellyfin-username"]) { configfile["jellyfin-username"] = process.env.JELLYFIN_USERNAME; }
if (!configfile["jellyfin-password"]) { configfile["jellyfin-password"] = process.env.JELLYFIN_PASSWORD; }
if (!configfile["jellyfin-app-name"]) { configfile["jellyfin-app-name"] = process.env.JELLYFIN_APP_NAME; }
fs.writeFile(filename, JSON.stringify(configfile, null, 1), (err) => {
if (err) return console.log(err);

View File

@ -1,4 +1,4 @@
const Discord = require('discord.js');
const Discord = require("discord.js");
var discordClient;
@ -12,4 +12,4 @@ function getDiscordClient(){
module.exports = {
getDiscordClient,
init
}
};

View File

@ -10,4 +10,4 @@ function getAudioDispatcher(){
module.exports = {
setAudioDispatcher,
getAudioDispatcher
}
};

View File

@ -1,15 +1,13 @@
const CONFIG = require("../config.json");
const CONFIG = require('../config.json');
const jellyfinClientManager = require("./jellyfinclientmanager");
const jellyfinClientManager=require('./jellyfinclientmanager');
const discordclientmanager= require('./discordclientmanager');
const discordclientmanager = require("./discordclientmanager");
discordclientmanager.init();
const discordClient = discordclientmanager.getDiscordClient();
const {audioDispatcher} = require('./dispachermanager');
const {handleChannelMessage}=require('./messagehandler');
const { handleChannelMessage } = require("./messagehandler");
jellyfinClientManager.init();
// TODO Error Checking as the apiclients is inefficent
@ -17,12 +15,11 @@ jellyfinClientManager.getJellyfinClient().authenticateUserByName(CONFIG["jellyfi
jellyfinClientManager.getJellyfinClient().setAuthenticationInfo(response.AccessToken, response.SessionInfo.UserId);
});
discordClient.on('ready', () => {
console.log('connected to Discord');
discordClient.on("ready", () => {
console.log("connected to Discord");
});
discordClient.on('message', message => {
discordClient.on("message", message => {
handleChannelMessage(message);
});

View File

@ -1,7 +1,7 @@
const { ApiClient , Events } = require('jellyfin-apiclient');
const CONFIG = require('../config.json');
const os = require('os');
const { ApiClient, Events } = require("jellyfin-apiclient");
const CONFIG = require("../config.json");
const os = require("os");
var jellyfinClient;
@ -21,4 +21,4 @@ module.exports = {
getJellyfinClient,
getJellyfinEvents,
init
}
};

View File

@ -1,30 +1,28 @@
const CONFIG = require('../config.json');
const Discord = require('discord.js');
const CONFIG = require("../config.json");
const Discord = require("discord.js");
const {
checkJellyfinItemIDRegex
} = require('./util');
} = require("./util");
const {
getAudioDispatcher
} = require('./dispachermanager');
} = require("./dispachermanager");
const discordclientmanager = require('./discordclientmanager');
const jellyfinClientManager = require('./jellyfinclientmanager');
const playbackmanager = require('./playbackmanager');
const websocketHanler = require('./websockethandler');
const discordclientmanager = require("./discordclientmanager");
const jellyfinClientManager = require("./jellyfinclientmanager");
const playbackmanager = require("./playbackmanager");
const websocketHanler = require("./websockethandler");
const discordClient = discordclientmanager.getDiscordClient();
var isSummendByPlay = false;
// random Color of the Jellyfin Logo Gradient
function getRandomDiscordColor () {
function randomNumber (b, a) {
return Math.floor((Math.random() * Math.pow(Math.pow((b - a), 2), 1 / 2)) + (b > a ? a : b))
return Math.floor((Math.random() * Math.pow(Math.pow((b - a), 2), 1 / 2)) + (b > a ? a : b));
}
const GRANDIENT_START = '#AA5CC3';
const GRANDIENT_END = '#00A4DC';
const GRANDIENT_START = "#AA5CC3";
const GRANDIENT_END = "#00A4DC";
let rS = GRANDIENT_START.slice(1, 3);
let gS = GRANDIENT_START.slice(3, 5);
@ -40,88 +38,49 @@ function getRandomDiscordColor() {
gE = parseInt(gE, 16);
bE = parseInt(bE, 16);
return ('#' + ('00' + (randomNumber(rS, rE)).toString(16)).substr(-2) + ('00' + (randomNumber(gS, gE)).toString(16)).substr(-2) + ('00' + (randomNumber(bS, bE)).toString(16)).substr(-2));
return ("#" + ("00" + (randomNumber(rS, rE)).toString(16)).substr(-2) + ("00" + (randomNumber(gS, gE)).toString(16)).substr(-2) + ("00" + (randomNumber(bS, bE)).toString(16)).substr(-2));
}
async function searchForItemID (searchString) {
let response = await jellyfinClientManager.getJellyfinClient().getSearchHints({
const response = await jellyfinClientManager.getJellyfinClient().getSearchHints({
searchTerm: searchString,
includeItemTypes: "Audio"
})
});
if (response.TotalRecordCount < 1) {
throw "Found no Song"
throw Error("Found no Song");
} else {
return response.SearchHints[0].ItemId
return response.SearchHints[0].ItemId;
}
}
function summon (voiceChannel) {
voiceChannel.join()
voiceChannel.join();
}
function summonMessage (message) {
if (!message.member.voice.channel) {
message.reply('please join a voice channel to summon me!');
}else if(message.channel.type === 'dm'){
message.reply('no dms')
}
else{
summon(message.member.voice.channel)
}
}
function handleChannelMessage(message) {
getRandomDiscordColor()
if (message.content.startsWith(CONFIG["discord-prefix"] + 'summon')) {
isSummendByPlay = false;
websocketHanler.openSocket();
summonMessage(message);
} else if (message.content.startsWith(CONFIG["discord-prefix"] + 'disconnect')) {
playbackmanager.stop()
jellyfinClientManager.getJellyfinClient().closeWebSocket();
discordClient.user.client.voice.connections.forEach((element) => {
element.disconnect();
});
} else if ((message.content.startsWith(CONFIG["discord-prefix"] + 'pause')) || (message.content.startsWith(CONFIG["discord-prefix"] + 'resume'))) {
if (getAudioDispatcher() !== undefined) {
playbackmanager.playPause();
message.reply("please join a voice channel to summon me!");
} else if (message.channel.type === "dm") {
message.reply("no dms");
} else {
message.reply("there is nothing playing!")
summon(message.member.voice.channel);
}
}
} else if (message.content.startsWith(CONFIG["discord-prefix"] + 'play')) {
if (discordClient.user.client.voice.connections.size < 1) {
summonMessage(message)
isSummendByPlay=true
}
async function playThis(){
let indexOfItemID = message.content.indexOf(CONFIG["discord-prefix"] + 'play') + (CONFIG["discord-prefix"] + 'play').length + 1;
let argument = message.content.slice(indexOfItemID);
async function playThis (message) {
const indexOfItemID = message.content.indexOf(CONFIG["discord-prefix"] + "play") + (CONFIG["discord-prefix"] + "play").length + 1;
const argument = message.content.slice(indexOfItemID);
let itemID;
// check if play command was used with itemID
let regexresults = checkJellyfinItemIDRegex(argument);
const regexresults = checkJellyfinItemIDRegex(argument);
if (regexresults) {
itemID = regexresults[0];
} else {
try {
itemID = await searchForItemID(argument);
} catch (e) {
message.reply(e);
message.reply(e.message);
playbackmanager.stop(discordClient.user.client.voice.connections.first());
return;
}
@ -129,12 +88,38 @@ function handleChannelMessage(message) {
discordClient.user.client.voice.connections.forEach((element) => {
playbackmanager.startPlaying(element, itemID, isSummendByPlay);
})
});
}
playThis();
function handleChannelMessage (message) {
getRandomDiscordColor();
} else if (message.content.startsWith(CONFIG["discord-prefix"] + 'stop')) {
if (message.content.startsWith(CONFIG["discord-prefix"] + "summon")) {
isSummendByPlay = false;
websocketHanler.openSocket();
summonMessage(message);
} else if (message.content.startsWith(CONFIG["discord-prefix"] + "disconnect")) {
playbackmanager.stop();
jellyfinClientManager.getJellyfinClient().closeWebSocket();
discordClient.user.client.voice.connections.forEach((element) => {
element.disconnect();
});
} else if ((message.content.startsWith(CONFIG["discord-prefix"] + "pause")) || (message.content.startsWith(CONFIG["discord-prefix"] + "resume"))) {
if (getAudioDispatcher() !== undefined) {
playbackmanager.playPause();
} else {
message.reply("there is nothing playing!");
}
} else if (message.content.startsWith(CONFIG["discord-prefix"] + "play")) {
if (discordClient.user.client.voice.connections.size < 1) {
summonMessage(message);
isSummendByPlay = true;
}
playThis(message);
} else if (message.content.startsWith(CONFIG["discord-prefix"] + "stop")) {
if (isSummendByPlay) {
if (discordClient.user.client.voice.connections.size > 0) {
playbackmanager.stop(discordClient.user.client.voice.connections.first());
@ -142,30 +127,29 @@ function handleChannelMessage(message) {
} else {
playbackmanager.stop();
}
} else if (message.content.startsWith(CONFIG["discord-prefix"] + 'help')) {
} else if (message.content.startsWith(CONFIG["discord-prefix"] + "help")) {
const reply = new Discord.MessageEmbed()
.setColor(getRandomDiscordColor())
.addFields({
name: `${CONFIG['discord-prefix']}summon`,
value: 'Join the channel the author of the message'
name: `${CONFIG["discord-prefix"]}summon`,
value: "Join the channel the author of the message"
}, {
name: `${CONFIG['discord-prefix']}disconnect`,
value: 'Disconnect from all current Voice Channels'
name: `${CONFIG["discord-prefix"]}disconnect`,
value: "Disconnect from all current Voice Channels"
}, {
name: `${CONFIG['discord-prefix']}play`,
value: 'Play the following item'
name: `${CONFIG["discord-prefix"]}play`,
value: "Play the following item"
}, {
name: `${CONFIG['discord-prefix']}pause/resume`,
value: 'Pause/Resume audio'
name: `${CONFIG["discord-prefix"]}pause/resume`,
value: "Pause/Resume audio"
}, {
name: `${CONFIG['discord-prefix']}help`,
value: 'Display this help message'
})
name: `${CONFIG["discord-prefix"]}help`,
value: "Display this help message"
});
message.channel.send(reply);
}
}
module.exports = {
handleChannelMessage
}
};

View File

@ -1,33 +1,27 @@
const { default: fetch } = require('node-fetch');
const {
getAudioDispatcher,
setAudioDispatcher
} = require('./dispachermanager');
} = require("./dispachermanager");
var currentPlayingItemId;
var progressInterval;
var isPaused;
const jellyfinClientManager = require('./jellyfinclientmanager');
const jellyfinClientManager = require("./jellyfinclientmanager");
function streamURLbuilder (itemID, bitrate) {
// so the server transcodes. Seems appropriate as it has the source file.
let supportedCodecs = "opus"
let supportedContainers = "ogg,opus"
const supportedCodecs = "opus";
const supportedContainers = "ogg,opus";
return `${jellyfinClientManager.getJellyfinClient().serverAddress()}/Audio/${itemID}/universal?UserId=${jellyfinClientManager.getJellyfinClient().getCurrentUserId()}&DeviceId=${jellyfinClientManager.getJellyfinClient().deviceId()}&MaxStreamingBitrate=${bitrate}&Container=${supportedContainers}&AudioCodec=${supportedCodecs}&api_key=${jellyfinClientManager.getJellyfinClient().accessToken()}&TranscodingContainer=ts&TranscodingProtocol=hls`;
}
function startPlaying (voiceconnection, itemID, disconnectOnFinish) {
isPaused = false;
async function playasync () {
let url = streamURLbuilder(itemID, voiceconnection.channel.bitrate)
jellyfinClientManager.getJellyfinClient().reportPlaybackStart({ userID: `${jellyfinClientManager.getJellyfinClient().getCurrentUserId()}`, itemID: `${itemID}` })
const url = streamURLbuilder(itemID, voiceconnection.channel.bitrate);
jellyfinClientManager.getJellyfinClient().reportPlaybackStart({ userID: `${jellyfinClientManager.getJellyfinClient().getCurrentUserId()}`, itemID: `${itemID}` });
currentPlayingItemId = itemID;
setAudioDispatcher(voiceconnection.play(url));
let time = await jellyfinClientManager.getJellyfinClient().getItem(jellyfinClientManager.getJellyfinClient().getCurrentUserId(),currentPlayingItemId)
async function asfg(){
jellyfinClientManager.getJellyfinClient().reportPlaybackProgress(getProgressPayload())
}
//progressInterval=setInterval(asfg,2000);
getAudioDispatcher().on("finish", () => {
if (disconnectOnFinish) {
@ -35,9 +29,9 @@ function startPlaying(voiceconnection, itemID, disconnectOnFinish) {
} else {
stop();
}
})
});
}
playasync().catch((rsn) => { console.log(rsn) });
playasync().catch((rsn) => { console.log(rsn); });
}
/**
* @param {Object=} disconnectVoiceConnection - Optional The voice Connection do disconnect from
@ -45,30 +39,26 @@ function startPlaying(voiceconnection, itemID, disconnectOnFinish) {
function stop (disconnectVoiceConnection) {
isPaused = true;
if (disconnectVoiceConnection) {
disconnectVoiceConnection.disconnect()
disconnectVoiceConnection.disconnect();
}
jellyfinClientManager.getJellyfinClient().reportPlaybackStopped({userId: jellyfinClientManager.getJellyfinClient().getCurrentUserId(),itemId:currentPlayingItemId})
if(getAudioDispatcher())
getAudioDispatcher().destroy();
jellyfinClientManager.getJellyfinClient().reportPlaybackStopped({ userId: jellyfinClientManager.getJellyfinClient().getCurrentUserId(), itemId: currentPlayingItemId });
if (getAudioDispatcher()) { getAudioDispatcher().destroy(); }
setAudioDispatcher(undefined);
clearInterval(progressInterval);
}
function pause () {
isPaused = true;
console.log('here paused is changed', isPaused);
jellyfinClientManager.getJellyfinClient().reportPlaybackProgress(getProgressPayload())
console.log("here paused is changed", isPaused);
jellyfinClientManager.getJellyfinClient().reportPlaybackProgress(getProgressPayload());
getAudioDispatcher().pause(true);
}
function resume () {
isPaused = false;
jellyfinClientManager.getJellyfinClient().reportPlaybackProgress(getProgressPayload())
jellyfinClientManager.getJellyfinClient().reportPlaybackProgress(getProgressPayload());
getAudioDispatcher().resume();
}
function playPause () {
if (getAudioDispatcher().paused)
resume();
else
pause();
if (getAudioDispatcher().paused) { resume(); } else { pause(); }
}
function getPostitionTicks () {
@ -78,21 +68,21 @@ function getPostitionTicks(){
function getPlayMethod () {
// TODO figure out how to figure this out
return 'Transcode';
return "Transcode";
}
function getRepeatMode () {
return 'RepeatNone';
return "RepeatNone";
}
function getPlaylistItemId () {
// as I curently dont support Playlists
return 'playlistItem0'
return "playlistItem0";
}
function getPlaySessionId () {
// i think its just a number which you dont need to retrieve but need to report
return 'ae2436edc6b91b11d72aeaa67f84e0ea';
return "ae2436edc6b91b11d72aeaa67f84e0ea";
}
function getNowPLayingQueue () {
@ -100,7 +90,7 @@ function getNowPLayingQueue(){
Id: currentPlayingItemId,
// as I curently dont support Playlists
PlaylistItemId: getPlaylistItemId()
}]
}];
}
function getCanSeek () {
@ -116,13 +106,13 @@ function getVolumeLevel(){
}
function getItemId () {
return currentPlayingItemId
return currentPlayingItemId;
}
function getIsPaused () {
// AudioDispacker Paused is to slow
if(isPaused == undefined){
if (isPaused === undefined) {
isPaused = false;
}
@ -130,7 +120,7 @@ function getIsPaused(){
}
function getProgressPayload () {
let payload= {
const payload = {
CanSeek: getCanSeek(),
IsMuted: getIsMuted(),
IsPaused: getIsPaused(),
@ -143,8 +133,8 @@ function getProgressPayload(){
PositionTicks: getPostitionTicks(),
RepeatMode: getRepeatMode(),
VolumeLevel: getVolumeLevel()
}
return payload
};
return payload;
}
module.exports = {
@ -153,4 +143,4 @@ module.exports = {
playPause,
resume,
pause
}
};

View File

@ -1,8 +1,8 @@
function checkJellyfinItemIDRegex (strgintomatch) {
let regexresult=strgintomatch.match(/([0-9]|[a-f]){32}/);
const regexresult = strgintomatch.match(/([0-9]|[a-f]){32}/);
return regexresult;
}
module.exports = {
checkJellyfinItemIDRegex
}
};

View File

@ -1,21 +1,20 @@
const jellyfinClientManager = require('./jellyfinclientmanager');
const discordclientmanager = require('./discordclientmanager');
const playbackmanager = require('./playbackmanager');
const jellyfinClientManager = require("./jellyfinclientmanager");
const discordclientmanager = require("./discordclientmanager");
const playbackmanager = require("./playbackmanager");
function openSocket () {
jellyfinClientManager.getJellyfinClient().openWebSocket();
jellyfinClientManager.getJellyfinClient().reportCapabilities(
{
'PlayableMediaTypes': "Audio",
'SupportsMediaControl': "True",
'SupportedCommands': "Play,Playstate"
PlayableMediaTypes: "Audio",
SupportsMediaControl: "True",
SupportedCommands: "Play,Playstate"
}
);
jellyfinClientManager.getJellyfinEvents().on(jellyfinClientManager.getJellyfinClient(), "message", (type, data) => {
// console.log(data);
if (data.MessageType == 'Play') {
if (data.Data.PlayCommand == 'PlayNow') {
if (data.MessageType === "Play") {
if (data.Data.PlayCommand === "PlayNow") {
discordclientmanager.getDiscordClient().user.client.voice.connections.forEach((element) => {
playbackmanager.startPlaying(element, data.Data.ItemIds[data.Data.StartIndex || 0], false);
element.on("error", (error) => {
@ -23,10 +22,10 @@ function openSocket() {
});
});
}
}else if(data.MessageType == 'Playstate'){
if(data.Data.Command == 'PlayPause'){
} else if (data.MessageType === "Playstate") {
if (data.Data.Command === "PlayPause") {
playbackmanager.playPause();
}else if(data.Data.Command == 'Stop'){
} else if (data.Data.Command === "Stop") {
playbackmanager.stop();
}
}
@ -35,4 +34,4 @@ function openSocket() {
module.exports = {
openSocket
}
};