-
Notifications
You must be signed in to change notification settings - Fork 1
/
RadiYo.ts
227 lines (221 loc) · 9.6 KB
/
RadiYo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import { Client, ClientUser, Guild, MessageActionRow, MessageEmbed, MessageSelectMenu, MessageSelectOptionData, TextBasedChannel, VoiceChannel } from 'discord.js';
import 'dotenv/config';
import featuredStationsJSON from './featured_stations.json';
import { RadioPlayer } from './RadioPlayer';
import { FeaturedStation, Station } from './util/interfaces';
import logger from './util/logger';
import { VoiceManager } from './VoiceManager';
class RadiYo {
readonly DISCORD_TOKEN: string = this.getEnv('DISCORD_TOKEN');
readonly DISCORD_OAUTH_CLIENT_ID: string = this.getEnv('DISCORD_OAUTH_CLIENT_ID');
readonly DISCORD_GUILD_ID: string = this.getEnv('DISCORD_GUILD_ID');
readonly NOTIFICATION_CHANNEL_ID: string = this.getEnv('NOTIFICATION_CHANNEL_ID');
readonly RADIO_DIRECTORY_KEY: string = this.getEnv('RADIO_DIRECTORY_KEY');
readonly ADMIN_ID: string = this.getEnv('ADMIN_ID');
readonly TOPGG_TOKEN: string = this.getEnv('TOPGG_TOKEN');
public VOICE_MANAGERS: Map<string, VoiceManager> = new Map();
public RADIO_PLAYERS: Map<string, RadioPlayer> = new Map();
public CLIENT: Client | null = null;
private featuredStations: FeaturedStation[] = [];
private getEnv(envVar: string): string {
const p = process.env[envVar];
if (p !== undefined) {
return p;
}
else {
throw new ReferenceError(`Environment Variable {${envVar}} is not defined.`);
}
}
public getVoiceManager(guild: Guild): VoiceManager | null {
const player = this.VOICE_MANAGERS.get(guild.id);
if (player) return player; else return null;
}
public async createVoiceManager(guild: Guild, notificationChannel: TextBasedChannel, voiceChannel: VoiceChannel, station: Station): Promise<VoiceManager> {
const rs = this.getVoiceManager(guild);
if (rs) {
if (voiceChannel.id !== rs.VOICE_CHANNEL.id || notificationChannel.id !== rs.NOTIFICATION_CHANNEL.id) {
rs.leaveVoiceChannel();
const newVm = new VoiceManager(guild, notificationChannel, voiceChannel, station);
await newVm.attachPlayer(station);
this.VOICE_MANAGERS.set(guild.id, newVm);
return newVm;
}
else {
await rs.attachPlayer(station);
return rs;
}
}
else {
const newVm = new VoiceManager(guild, notificationChannel, voiceChannel, station);
await newVm.attachPlayer(station);
this.VOICE_MANAGERS.set(guild.id, newVm);
logger.debug(`CREATE: There are currently ${this.VOICE_MANAGERS.size} voice managers in memory`);
return newVm;
}
}
public deleteVoiceManager(guildId: string): boolean {
const v = this.VOICE_MANAGERS.delete(guildId);
logger.debug(`DELETE: There are currently ${this.VOICE_MANAGERS.size} voice managers in memory`);
return v;
}
public async getRadioPlayer(station: Station): Promise<RadioPlayer> {
let rp = this.RADIO_PLAYERS.get(station.streamDownloadURL);
if (!rp) {
rp = new RadioPlayer();
await rp.play(station);
this.RADIO_PLAYERS.set(station.streamDownloadURL, rp);
}
logger.info(`GET: There are currently ${this.RADIO_PLAYERS.size} radio players in memory`);
return rp;
}
public deleteRadioPlayer(station: Station): boolean {
const v = this.RADIO_PLAYERS.delete(station.streamDownloadURL);
logger.info(`DELETE (${v}): There are currently ${this.RADIO_PLAYERS.size} radio players in memory`);
return v;
}
public getBotUser(): ClientUser {
const user = this.CLIENT?.user;
if (user) return user;
else throw new Error('Could not fetch bot user');
}
public newMsgEmbed(): MessageEmbed {
return new MessageEmbed()
.setAuthor('RadiYo!',
'https://cdn.discordapp.com/avatars/895354013116153876/90d756ddeab4c129d89b9f60df44ba95.png?size=32',
'https://radiyobot.com');
}
public stationListEmbed(stations: Station[]): { embed: MessageEmbed, component: MessageActionRow } {
const msg = this.newMsgEmbed();
const fields = [];
const selectOptions: MessageSelectOptionData[] = [];
if (stations) {
const length = stations.length <= 5 ? stations.length : 5;
for (let i = 0; i < length; i++) {
const id = stations[i].id;
const genre = stations[i].genre;
const subtext = stations[i].subtext;
if (stations[i] && id) {
const nameObj = {
name: 'Name',
value: stations[i].text,
inline: true
};
const descObj = {
name: 'Description',
value: subtext ? subtext.substring(0, 1024) : 'N/A',
inline: true
};
const genreObj = {
name: 'Genre',
value: genre ? genre : 'N/A',
inline: true
};
fields.push(nameObj, descObj, genreObj);
selectOptions.push({ label: stations[i].text.substring(0, 100), value: id });
}
}
}
const row = new MessageActionRow().addComponents(
new MessageSelectMenu().setCustomId('choose_station')
.setPlaceholder('Select station to play...')
.addOptions(selectOptions)
);
return { embed: msg.addFields(fields), component: row };
}
public nowPlayingListEmbed(stations: Station[]): { embed: MessageEmbed, component: MessageActionRow } {
const msg = this.newMsgEmbed();
const fields = [];
const selectOptions: MessageSelectOptionData[] = [];
if (stations) {
const length = stations.length <= 5 ? stations.length : 5;
for (let i = 0; i < length; i++) {
const np = stations[i].nowPlaying;
const id = stations[i].id;
if (stations[i] && np) {
let label = `${np.artist} - ${np.title}`.substring(0, 100);
if (np.title) {
label = `${np.artist} - ${np.title}`.substring(0, 100);
} else {
label = stations[i].subtext ? stations[i].subtext.substring(0, 1024) : 'N/A';
}
const nameObj = {
name: 'Name',
value: stations[i].text,
inline: true
};
const npObj = {
name: 'Now Playing',
value: label,
inline: true
};
const nopObj = {
name: '\u200b',
value: '\u200b',
inline: true
};
fields.push(nameObj, npObj, nopObj);
selectOptions.push({ label: label, value: id });
}
}
}
const row = new MessageActionRow().addComponents(
new MessageSelectMenu().setCustomId('choose_station')
.setPlaceholder('Select song to play...')
.addOptions(selectOptions)
);
return { embed: msg.addFields(fields), component: row };
}
public downloadFeaturedStations(): void {
logger.debug('Downloading Featured Stations');
try {
featuredStationsJSON.forEach((category) => {
const temp: FeaturedStation = {} as FeaturedStation;
temp.title = category.title;
temp.description = category.description;
temp.stations = [];
category.station_ids.forEach(async (stationId) => {
let result: Station;
try {
result = await RadioPlayer.searchByStationId(stationId);
temp.stations.push(result);
}
catch (err) {
throw new Error(`There was an issue downloading a featured station ${err}`);
}
});
this.featuredStations.push(temp);
});
}
catch (err) {
logger.error('There was an error downloading featured stations', err);
this.featuredStations = [];
}
}
public getFeaturedStations(): FeaturedStation[] {
if (this.featuredStations.length !== 0) {
return this.featuredStations;
}
else {
//TODO: This currently doesn't really work
logger.debug('No features stations...downloading');
this.downloadFeaturedStations();
return this.featuredStations;
}
}
public getCurrentlyPlayingStations(): Station[] {
const stations: Station[] = [];
this.RADIO_PLAYERS.forEach(player => {
if (player.listenerCount('metadataChange') === 0) {
logger.info(`Found zombie station ${player.CURRENT_STATION.text}, deleting`);
this.deleteRadioPlayer(player.CURRENT_STATION);
}
else {
const station = player.CURRENT_STATION;
station.listenerCount = player.listenerCount('metadataChange');
stations.push(station);
}
});
return stations;
}
}
export default new RadiYo();