├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── jsdoc.json ├── lib ├── Constants.js ├── DJ.js ├── Discord.js ├── Utils.js ├── audio │ ├── AudioHelper.js │ ├── converter │ │ ├── ChiptuneDecoder.js │ │ ├── FFmpegConverter.js │ │ ├── LameDecoder.js │ │ ├── OpusEncoder.js │ │ └── OpusToolsConverter.js │ └── playable │ │ ├── FilePlayable.js │ │ ├── IcyPlayable.js │ │ ├── SoundcloudPlayable.js │ │ └── YouTubePlayable.js ├── components │ └── ComponentManager.js ├── interfaces │ ├── Component.js │ ├── Converter.js │ ├── Decoder.js │ ├── Encoder.js │ ├── Playable.js │ └── Playlist.js └── ws │ ├── APISocket.js │ ├── DiscordSocket.js │ ├── VoiceSocket.js │ └── VoiceUDPSocket.js └── package.json /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | 7 | [*.{js,json,md,bat,sh}] 8 | charset = utf-8 9 | 10 | [*.js] 11 | indent_style = space 12 | indent_size = 4 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .jshintrc 3 | .tern-project 4 | node_modules 5 | docs 6 | old 7 | site 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | {signature of Ty Coon}, 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [DiscordDJ](http://guichaguri.github.io/DiscordDJ/) 2 | Discord DJ Bot. Let you play music in your server. Inspired by PlugDJ 3 | 4 | **NEWS** DiscordDJ is being totally recoded! Check [here](https://github.com/Guichaguri/DiscordDJ/projects/1) for the progress 5 | 6 | ## Features 7 | * Play a video or playlist from YouTube 8 | * Play a track or set from Soundcloud 9 | * Play a track or playlist from Spotify 10 | * Play a stream from Icecast/Shoutcast/Radionomy 11 | * Play audio and video files 12 | * Play a playlist file 13 | * Full control over the behavior with **Components** 14 | * Built on its own API wrapper for a faster experience 15 | * Open Source 16 | * Developer API (Soon, you will be able to implement your own components, playables, playlists, encoders and decoders) 17 | 18 | ## Optional Modules 19 | Most of the modules below require node-gyp, which is known for causing problems mainly on Windows, that's why they're optional 20 | * `musicmetadata`: For reading file metadata 21 | * `lame`: For native mp3 decoding (no FFmpeg/avconv needed) 22 | * `node-chiptune`: For decoding tracker music 23 | * `node-opus`: For faster Opus encoding 24 | * `sodium`: For faster audio encryption 25 | * `bufferutil`: For faster WebSockets 26 | * `utf-8-validate`: For faster WebSockets 27 | -------------------------------------------------------------------------------- /jsdoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "tags": { 3 | "allowUnknownTags": true, 4 | "dictionaries": ["jsdoc","closure"] 5 | }, 6 | "source": { 7 | "include": ["lib"], 8 | "includePattern": ".+\\.js$" 9 | }, 10 | "plugins": [], 11 | "templates": { 12 | "cleverLinks": true, 13 | "monospaceLinks": false 14 | }, 15 | "opts": { 16 | "template": "templates/default", 17 | "encoding": "utf8", 18 | "destination": "./docs/", 19 | "recurse": true, 20 | "readme": "README.md" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lib/Constants.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Discord Constants 4 | * @typedef {Constants} 5 | */ 6 | module.exports = { 7 | API_VERSION: 6, 8 | 9 | // OPCODES 10 | // https://discordapp.com/developers/docs/topics/gateway#gateway-op-codes 11 | OP_DISPATCH: 0, 12 | OP_HEARTBEAT: 1, 13 | OP_IDENTITY: 2, 14 | OP_VOICE_STATE_UPDATE: 4, 15 | OP_HELLO: 10, 16 | OP_HEARTBEAT_ACK: 11, 17 | 18 | // VOICE OPCODES 19 | // https://discordapp.com/developers/docs/topics/voice-connections#voice-payloads-and-events 20 | VOP_IDENTITY: 0, 21 | VOP_SELECT_PROTOCOL: 1, 22 | VOP_READY: 2, 23 | VOP_HEARTBEAT: 3, 24 | VOP_SESSION_DESCRIPTION: 4, 25 | VOP_SPEAKING: 5, 26 | VOP_IGNORE: 8, // Unknown, but can be safely ignored 27 | 28 | // EVENTS 29 | // https://discordapp.com/developers/docs/topics/gateway#events 30 | EVENT_READY: 'READY', 31 | EVENT_GUILD_CREATE: 'GUILD_CREATE', 32 | EVENT_VOICE_SERVER_UPDATE: 'VOICE_SERVER_UPDATE', 33 | 34 | // VOICE IP_DISCOVERY/RTP PACKETS 35 | // IP DISCOVERY: https://discordapp.com/developers/docs/topics/voice-connections#ip-discovery 36 | // RTP Header: http://www.rfcreader.com/#rfc3550_line548 37 | IP_DISCOVERY_SIZE: 70, 38 | IP_DISCOVERY_SSRC_OFFSET: 0, 39 | RTP_HEADER_SIZE: 12, 40 | RTP_NONCE_SIZE: 12, 41 | RTP_HEADER_VERSION_OFFSET: 0, 42 | RTP_HEADER_TYPE_OFFSET: 1, 43 | RTP_HEADER_SEQ_OFFSET: 2, 44 | RPT_HEADER_TIMESTAMP_OFFSET: 4, 45 | RTP_HEADER_SSRC_OFFSET: 8, 46 | 47 | // VOICE ENCRYPTION MODES 48 | VOICE_ENCRYPTION_PLAIN: 'plain', 49 | VOICE_ENCRYPTION_SODIUM: 'xsalsa20_poly1305' 50 | }; 51 | -------------------------------------------------------------------------------- /lib/DJ.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const EventEmitter = require('events').EventEmitter; 4 | const stream = require('stream'); 5 | 6 | const Playable = require('./interfaces/Playable.js'); 7 | const Constants = require('./Constants.js'); 8 | const VoiceUDPSocket = require('./ws/VoiceUDPSocket.js'); 9 | const AudioHelper = require('./audio/AudioHelper.js'); 10 | const Utils = require('./Utils.js'); 11 | 12 | /** 13 | * Represents a voice connection. 14 | * @class 15 | * @extends EventEmitter 16 | */ 17 | class DJ extends EventEmitter { 18 | 19 | /** @private */ 20 | constructor(discord, guildId, channelId) { 21 | super(); 22 | this._discord = discord; // Discord instance 23 | this._guildId = guildId; // Guild ID 24 | this._channelId = channelId; // Voice Channel ID 25 | this._socket = null; // VoiceSocket instance 26 | this._token = null; // Token 27 | this._endpoint = null; // Endpoint URL 28 | 29 | this._playableStream = null; // Loaded Playable stream 30 | this._audioTimer = null; // Audio clock 31 | this._state = 0; // 0: Stopped - 1: Paused - 2: Playing 32 | this._currentFrame = 0; // Current Frame 33 | this._startTime = 0; // Start Time 34 | 35 | // Opus Audio Options 36 | this._audioOptions = { 37 | frameduration: 60, // milliseconds 38 | samplerate: 48000, // hertz 39 | bitdepth: 16, // bits 40 | channels: 2 41 | }; 42 | this._audioOptions['samplecount'] = AudioHelper.getSampleCount(this._audioOptions); 43 | this._audioOptions['readsize'] = AudioHelper.getReadSize(this._audioOptions); 44 | 45 | /** 46 | * Custom Data 47 | * @member {?object} 48 | */ 49 | this.data = null; 50 | 51 | this.on('update-connection', function(token, endpoint) { 52 | this._token = token; 53 | this._endpoint = endpoint; 54 | 55 | // Reconnect to the new endpoint 56 | if(this._socket != null && this._socket.url != endpoint) { 57 | this.disconnect(); 58 | this.connect(); 59 | } 60 | }.bind(this)); 61 | } 62 | 63 | /** 64 | * Guild ID 65 | * @type {string} 66 | * @readonly 67 | */ 68 | get guildId() { 69 | return this._guildId; 70 | } 71 | 72 | /** 73 | * Voice Channel ID 74 | * @type {string} 75 | * @readonly 76 | */ 77 | get channelId() { 78 | return this._channelId; 79 | } 80 | 81 | /** 82 | * Currently loaded audio stream 83 | * @type {Stream} 84 | * @readonly 85 | */ 86 | get audioStream() { 87 | return this._playableStream; 88 | } 89 | 90 | /** 91 | * Whether it's playing 92 | * @type {boolean} 93 | * @readonly 94 | */ 95 | get playing() { 96 | return this._playableInterval != null; 97 | } 98 | 99 | /** 100 | * Whether it's connected to the voice channel 101 | * @type {boolean} 102 | * @readonly 103 | */ 104 | get connected() { 105 | return this._socket != null; 106 | } 107 | 108 | /** 109 | * Connects to the voice channel 110 | * @return {Promise} 111 | */ 112 | connect() { 113 | if(this.connected) return Promise.reject('Already connected!'); 114 | 115 | return new Promise(function(resolve, reject) { 116 | 117 | let createSocket = function(token, endpoint) { 118 | 119 | let socket = new VoiceUDPSocket(this, endpoint, token, Constants.VOICE_ENCRYPTION_SODIUM); 120 | socket.once('open', function() { 121 | this._socket = socket; 122 | resolve(); 123 | }.bind(this)); 124 | 125 | }.bind(this); 126 | 127 | if(this._token == null || this._endpoint == null) { 128 | this._discord._socket.connectVoice(this.guildId, this.channelId); 129 | this.once('update-connection', createSocket); 130 | } else { 131 | createSocket(this._token, this._endpoint); 132 | } 133 | 134 | }.bind(this)); 135 | } 136 | 137 | /** 138 | * Disconnects from the voice channel 139 | * @return {Promise} 140 | */ 141 | disconnect() { 142 | if(!this.connected) return Promise.reject('Already disconnected!'); 143 | 144 | this._socket.terminate(); 145 | this._socket = null; 146 | 147 | return Promise.resolve(); 148 | } 149 | 150 | /** 151 | * Starts buffering a playable 152 | * @param {Playable} playable 153 | * @return {Promise} 154 | */ 155 | buffer(playable) { 156 | return AudioHelper.buffer(this._discord, playable, this._audioOptions); 157 | } 158 | 159 | /** 160 | * Loads a Playable or an Opus stream 161 | * @param {(Playable|Stream)} p 162 | * @return {Promise} 163 | */ 164 | load(p) { 165 | if(p instanceof Playable) { 166 | return this.buffer(p).then(function(stream) { 167 | this._playableStream = stream; 168 | }.bind(this)); 169 | } else if(Utils.isStream(p)) { 170 | this._playableStream = p; 171 | return Promise.resolve(); 172 | } else { 173 | return Promise.reject('Invalid Playable or stream'); 174 | } 175 | } 176 | 177 | /** @private */ 178 | _processAudio() { 179 | if(this._state != 2) return; 180 | 181 | const nextTime = (this._currentFrame + 1) * this._audioOptions['frameduration'] + this._startTime; 182 | const currentTime = Utils.hrtime(); 183 | 184 | if(currentTime < nextTime) { 185 | const timeleft = Math.round(nextTime - currentTime); 186 | if(this._audioTimer) clearTimeout(this._audioTimer); 187 | this._audioTimer = setTimeout(this._processAudio.bind(this), Math.max(timeleft, 0)); 188 | return; 189 | } 190 | 191 | this._currentFrame++; 192 | 193 | let buffer = this._playableStream.read(this._audioOptions['readsize']); 194 | 195 | if(buffer == null) { 196 | // No audio to be read. 197 | this._interpolateBreak(); 198 | return; 199 | } else if(!Buffer.isBuffer(buffer)) { 200 | buffer = Buffer.from(buffer); 201 | } 202 | 203 | this._socket.sendAudio(buffer, this._audioOptions['samplecount']); 204 | 205 | return setImmediate(this._processAudio.bind(this)); 206 | } 207 | 208 | /** @private */ 209 | _interpolateBreak() { 210 | // We'll send 5 silent packets for interpolation 211 | for(var i = 0; i < 5; i++) { 212 | this._socket.sendAudio(Buffer.from([0xF8, 0xFF, 0xFE]), this._audioOptions['samplecount']); 213 | } 214 | 215 | this._socket.setSpeaking(false); 216 | } 217 | 218 | /** 219 | * Starts playing or resume the loaded playable 220 | */ 221 | play() { 222 | this._state = 2; 223 | this._playableStream.once('readable', function() { 224 | this._socket.setSpeaking(true); 225 | this._currentFrame = 0; 226 | this._startTime = Utils.hrtime(); 227 | setImmediate(this._processAudio.bind(this)); 228 | }.bind(this)); 229 | } 230 | 231 | /** 232 | * Stops playing the loaded playable 233 | */ 234 | stop() { 235 | this._state = 0; 236 | clearTimeout(this._audioTimer); 237 | this._audioTimer = null; 238 | this._playableStream.removeAllListeners('readable'); 239 | this._playableStream = null; 240 | this._interpolateBreak(); 241 | } 242 | 243 | /** 244 | * Pauses the loaded playable 245 | */ 246 | pause() { 247 | this._state = 1; 248 | clearTimeout(this._audioTimer); 249 | this._audioTimer = null; 250 | this._interpolateBreak(); 251 | } 252 | } 253 | 254 | module.exports = DJ; 255 | -------------------------------------------------------------------------------- /lib/Discord.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const EventEmitter = require('events').EventEmitter; 4 | const DiscordSocket = require('./ws/DiscordSocket.js'); 5 | const DJ = require('./DJ.js'); 6 | 7 | /** 8 | * Represents a Discord client. 9 | * @class 10 | * @extends EventEmitter 11 | */ 12 | class Discord extends EventEmitter { 13 | 14 | /** 15 | * @constructor 16 | * @param {string} token - Access token 17 | * @param {number} currentShard - Current shard entry number 18 | * @param {number} totalShards - Total amount of shards 19 | */ 20 | constructor(token, currentShard, totalShards) { 21 | super(); 22 | this._token = token; // Bot token 23 | this._currentShard = typeof currentShard == 'number' ? currentShard : 0; // Current shard 24 | this._totalShards = typeof totalShards == 'number' ? totalShards : 1; // Total shards 25 | this._gateway = null; // Gateway URL 26 | this._socket = null; // DiscordSocket instance 27 | this._djs = []; // DJ instances 28 | 29 | /** @member {Component[]} */ 30 | this.components = []; 31 | /** @member {Class[]} */ 32 | this.encoders = []; 33 | /** @member {Class[]} */ 34 | this.decoders = []; 35 | /** @member {Class[]} */ 36 | this.playables = []; 37 | /** @member {Class[]} */ 38 | this.playlists = []; 39 | } 40 | 41 | /** 42 | * Discord Access Token 43 | * @type {string} 44 | * @readonly 45 | */ 46 | get token() { 47 | return this._token; 48 | } 49 | 50 | /** 51 | * Current shard entry 52 | * @type {number} 53 | * @readonly 54 | */ 55 | get shard() { 56 | return this._currentShard; 57 | } 58 | 59 | /** 60 | * The created DJs 61 | * @type {DJ[]} 62 | * @readonly 63 | */ 64 | get djs() { 65 | return this._djs; 66 | } 67 | 68 | /** 69 | * Whether it's connected to Discord 70 | * @type {boolean} 71 | * @readonly 72 | */ 73 | get connected() { 74 | return this.socket != null; 75 | } 76 | 77 | /** 78 | * Connects to Discord 79 | * This will not connect DJs 80 | * @return {Promise} 81 | */ 82 | connect() { 83 | if(this.connected) return Promise.reject('Already connected!'); 84 | 85 | return new Promise(function(resolve, reject) { 86 | var r = function(socket) { 87 | this._socket = socket; 88 | resolve(); 89 | }.bind(this); 90 | 91 | if(this._gateway == null) { 92 | DiscordSocket.retrieveGatewayURL().then(function(gateway) { 93 | this._gateway = gateway; 94 | DiscordSocket.createSocket(gateway, this).then(r, reject); 95 | }.bind(this), reject); 96 | } else { 97 | DiscordSocket.createSocket(this._gateway, this).then(r, reject); 98 | } 99 | }.bind(this)); 100 | } 101 | 102 | /** 103 | * Disconnects from Discord 104 | * This will not disconnect DJs, so make sure you disconnect them too. 105 | * @return {Promise} 106 | */ 107 | disconnect() { 108 | if(!this.connected) return Promise.reject('Already disconnected!'); 109 | 110 | this._socket.terminate(); 111 | this._socket = null; 112 | 113 | return Promise.resolve(); 114 | } 115 | 116 | /** 117 | * Creates a DJ 118 | * @param {string} guildId - Guild ID 119 | * @param {string} channelId - Voice Channel ID 120 | * @return {DJ} 121 | */ 122 | createDJ(guildId, channelId) { 123 | var dj = new DJ(this, guildId, channelId); 124 | this._djs.push(dj); 125 | return dj; 126 | } 127 | 128 | } 129 | 130 | module.exports = Discord; 131 | -------------------------------------------------------------------------------- /lib/Utils.js: -------------------------------------------------------------------------------- 1 | 2 | const url = require('url'); 3 | const http = require('http'); 4 | const https = require('https'); 5 | const child_process = require('child_process'); 6 | 7 | module.exports = { 8 | 9 | request(theUrl, method, data, headers) { 10 | return new Promise(function(resolve, reject) { 11 | 12 | var cb = function(res) { 13 | res.once('error', reject); 14 | let result = ''; 15 | res.on('data', function(chunk) { 16 | result += chunk; 17 | }); 18 | res.once('end', function() { 19 | resolve(result); 20 | }); 21 | }; 22 | theUrl = url.parse(theUrl); 23 | if(method) theUrl['method'] = method; 24 | if(headers) theUrl['headers'] = headers; 25 | 26 | var req; 27 | if(theUrl.protocol == 'http:') { 28 | req = http.request(theUrl, cb); 29 | } else { 30 | req = https.request(theUrl, cb); 31 | } 32 | req.once('error', reject); 33 | if(data) req.write(data); 34 | req.end(); 35 | 36 | }); 37 | }, 38 | 39 | hrtime() { 40 | // Thanks to discordie for this function 41 | const t = process.hrtime(); 42 | return t[0] * 1000 + t[1] / 1000000; 43 | }, 44 | 45 | isStream(stream) { 46 | return stream != null && typeof stream === 'object' && typeof stream.pipe === 'function'; 47 | }, 48 | 49 | findCommand(cmds) { 50 | if(process.platform == 'win32') { 51 | // Adds .exe extension for each command 52 | let winCmds = cmds.map((cmd) => cmd + '.exe'); 53 | cmds = winCmds.concat(cmds); 54 | } 55 | 56 | for(var i = 0; i < cmds.length; i++) { 57 | // Tries every command trying to find one that works 58 | var p = child_process.spawnSync(cmds[i]); 59 | if(!p.error) return cmds[i]; 60 | } 61 | return null; 62 | }, 63 | 64 | createProcess(stream, cmd, args) { 65 | const process = child_process.spawn(cmd, args); 66 | 67 | stream.pipe(process.stdin); 68 | return process.stdout; 69 | } 70 | 71 | }; 72 | -------------------------------------------------------------------------------- /lib/audio/AudioHelper.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const stream = require('stream'); 4 | 5 | const Converter = require('../interfaces/Converter.js'); 6 | const Utils = require('../Utils.js'); 7 | 8 | class AudioHelper { 9 | 10 | /** @private */ 11 | static _selectConverters(discord, mimetype) { 12 | let decoder = null, encoder = null; 13 | 14 | // Find a decoder or converter 15 | for(let d of discord.decoders) { 16 | if(!d.available) continue; 17 | 18 | if(d.prototype instanceof Converter && d.converts(mimetype)) { 19 | return d; // It's a converter! 20 | } 21 | 22 | if(d.decodes(mimetype)) { 23 | decoder = d; 24 | break; 25 | } 26 | } 27 | if(decoder == null) return null; // No Decoder 28 | 29 | // Find an encoder 30 | for(let e of discord.encoders) { 31 | if(e.available) { 32 | encoder = e; 33 | break; 34 | } 35 | } 36 | if(encoder == null) return null; // No Encoder 37 | 38 | return [decoder, encoder]; 39 | } 40 | 41 | /** @private */ 42 | static _getStream(stream, resolve, reject) { 43 | if(Utils.isStream(stream)) { 44 | resolve(stream); 45 | } else if(stream instanceof Promise) { 46 | stream.then(resolve, reject); 47 | } else { 48 | reject("Invalid stream"); 49 | } 50 | } 51 | 52 | /** 53 | * Starts buffering a playable 54 | * @param {Discord} discord 55 | * @param {Playable} playable 56 | * @param {object} options 57 | * @param {number} options.samplerate 58 | * @param {number} options.channels 59 | * @param {number} options.frameduration 60 | * @return {Promise} 61 | */ 62 | static buffer(discord, playable, options) { 63 | return new Promise(function(resolve, reject) { 64 | playable.createStream().then(function(stream, mimetype) { 65 | 66 | const converters = AudioHelper._selectConverters(discord, mimetype); 67 | if(converters == null) return reject("No Encoder or Decoder was found"); 68 | 69 | const samplerate = options['samplerate'] || 48000; 70 | const channels = options['channels'] || 2; 71 | const frameduration = options['frameduration'] || 60; 72 | 73 | if(converters instanceof Array) { // It's an array, so we have an encoder and decoder 74 | 75 | AudioHelper._getStream(converters[0].decode(stream, samplerate, channels), function(pcmStream) { 76 | AudioHelper._getStream(converters[1].encode(pcmStream, samplerate, channels, frameduration), resolve, reject); 77 | }, reject); 78 | 79 | } else { // It's probably a converter! Let's use it efficiently 80 | 81 | AudioHelper._getStream(converters.convert(stream, samplerate, channels, frameduration), resolve, reject); 82 | 83 | } 84 | }, reject); 85 | }); 86 | } 87 | 88 | /** 89 | * Calculates the sample count from an opus format 90 | * @param {object} options 91 | * @param {number} options.samplerate 92 | * @param {number} options.frameduration 93 | * @return {number} 94 | */ 95 | static getSampleCount(options) { 96 | const samplerate = options['samplerate'] || 48000; 97 | const frameduration = options['frameduration'] || 60; 98 | 99 | return samplerate / 1000 * frameduration; 100 | } 101 | 102 | /** 103 | * Calculates the read size in bytes per second from an opus format 104 | * @param {object} options 105 | * @param {number} options.frameduration 106 | * @return {number} 107 | */ 108 | static getReadSize(options) { 109 | const frameduration = options['frameduration'] || 60; 110 | 111 | return 16 * frameduration; // (128 * frameduration) / 8 112 | } 113 | 114 | } 115 | 116 | module.exports = AudioHelper; 117 | -------------------------------------------------------------------------------- /lib/audio/converter/ChiptuneDecoder.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Decoder = require('../../../interfaces/Decoder.js'); 4 | 5 | const chiptune = (function() { 6 | try { 7 | return require('node-chiptune'); 8 | } catch(e) { 9 | return null; 10 | } 11 | })(); 12 | 13 | const formats = ['mod', 's3m', 'xm', 'it', 'mptm', 'stm', 'nst', 'm15', 'stk', 'wow', 'ult', '669', 'mtm', 14 | 'med', 'far', 'mdl', 'ams', 'dsm', 'amf', 'okt', 'dmf', 'ptm', 'psm', 'mt2', 'dbm', 'digi', 'imf', 15 | 'j2b', 'gdm', 'umx', 'plm', 'mo3', 'xpk', 'ppm', 'mmcmp']; 16 | 17 | const mimetypes = formats.map(function(format) { 18 | return 'audio/' + format; 19 | }); 20 | 21 | class ChiptuneDecoder extends Decoder { 22 | 23 | static get available() { 24 | return chiptune != null; 25 | } 26 | 27 | static decodes(mimetype) { 28 | return mimetypes.includes(mimetype); 29 | } 30 | 31 | static decode(stream, rate, channels) { 32 | return stream.pipe(chiptune({ 33 | sampleRate: rate, 34 | channels: channels 35 | })); 36 | } 37 | 38 | 39 | } 40 | 41 | module.exports = ChiptuneDecoder; 42 | -------------------------------------------------------------------------------- /lib/audio/converter/FFmpegConverter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Converter = require('../../interfaces/Converter.js'); 4 | const Utils = require('../../Utils.js'); 5 | const child_process = require('child_process'); 6 | 7 | const ffmpegCmd = Utils.findCommand([ 8 | process.cwd() + '/binary/avconv', 9 | process.cwd() + '/binary/ffmpeg', 10 | 'avconv', 'ffmpeg' 11 | ]); 12 | 13 | class FFmpegConverter extends Converter { 14 | 15 | static get available() { 16 | return ffmpegCmd != null; 17 | } 18 | 19 | static converts(mimetype) { 20 | // FFmpeg decodes so many formats, it's easier to always return true 21 | return true; 22 | } 23 | 24 | static decodes(mimetype) { 25 | // FFmpeg decodes so many formats, it's easier to always return true 26 | return true; 27 | } 28 | 29 | static convert(stream, rate, channels, frameDuration) { 30 | // Converts directly from raw audio to Opus. Only one process needed 31 | return Utils.createProcess(stream, ffmpegCmd, [ 32 | '-hide_banner', 33 | '-loglevel', 'error', 34 | '-i', 'pipe:0', 35 | '-map', '0:a', 36 | '-acodec', 'libopus', 37 | '-f', 'data', 38 | '-sample_fmt', 's16', 39 | '-vbr', 'off', 40 | '-compression_level', '10', 41 | '-ar', rate, 42 | '-ac', channels, 43 | '-frame_duration', frameDuration, 44 | '-b:a', '128000', 45 | 'pipe:1' 46 | ]); 47 | } 48 | 49 | static encode(stream, rate, channels, frameDuration) { 50 | return Utils.createProcess(stream, ffmpegCmd, [ 51 | "-c:a", "libopus", 52 | "-frame_duration", frameDuration, 53 | "-f", "webm", 54 | "pipe:1", 55 | "-i", "-" 56 | ]); 57 | } 58 | 59 | static decode(stream, rate, channels) { 60 | return Utils.createProcess(stream, ffmpegCmd, [ 61 | "-f", "s16le", 62 | "-ar", rate, 63 | "-ac", channels, 64 | "-af", "volume=1", 65 | "pipe:1", 66 | "-i", "-" 67 | ]); 68 | } 69 | 70 | } 71 | 72 | module.exports = FFmpegConverter; 73 | -------------------------------------------------------------------------------- /lib/audio/converter/LameDecoder.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Decoder = require('../../../interfaces/Decoder.js'); 4 | 5 | const lame = (function() { 6 | try { 7 | return require('lame'); 8 | } catch(e) { 9 | return null; 10 | } 11 | })(); 12 | 13 | const mimetypes = ['audio/mpeg', 'audio/mp3', 'audio/mpeg3', 'audio/x-mpeg-3', 'video/mpeg', 'video/x-mpeg']; 14 | 15 | class LameDecoder extends Decoder { 16 | 17 | static get available() { 18 | return lame != null; 19 | } 20 | 21 | static decodes(mimetype) { 22 | return mimetypes.includes(mimetype); 23 | } 24 | 25 | static decode(stream) { 26 | return stream.pipe(new lame.Decoder()); 27 | } 28 | 29 | } 30 | 31 | module.exports = LameDecoder; 32 | -------------------------------------------------------------------------------- /lib/audio/converter/OpusEncoder.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Encoder = require('../../interfaces/Encoder.js'); 4 | const Transform = require('stream').Transform; 5 | 6 | const Opus = (function() { 7 | try { 8 | return require('node-opus').OpusEncoder; 9 | } catch(e) { 10 | return require('opusscript'); 11 | } 12 | })(); 13 | 14 | class OpusEncoder extends Encoder { 15 | 16 | static get available() { 17 | return true; 18 | } 19 | 20 | static encode(stream, rate, channels, frameDuration) { 21 | return stream.pipe(new OpusTransformer(rate, channels, frameDuration)); 22 | } 23 | 24 | } 25 | 26 | /** 27 | * Opus transformer based on Opusscript and node-opus APIs 28 | * Thanks to abalabahaha for creating Opusscript and putting this together with the code of this class 29 | * This class is based on eris' PCMOpusTransformer with a few changes 30 | */ 31 | class OpusTransformer extends Transform { 32 | 33 | constructor(rate, channels, frameDuration) { 34 | this._opus = new Opus(rate, channels); 35 | this._framesize = rate * frameDuration / 1000; // 2880 36 | this._pcmSize = this._framesize * channels * 2; // 11520 37 | } 38 | 39 | _transform(chunk, encoding, cb) { 40 | // If there's a remainder, we'll combine it with the chunk 41 | if(this._remainder) { 42 | chunk = Buffer.concat([this._remainder, chunk]); 43 | this._remainder = null; 44 | } 45 | 46 | // If the chunk size is below the required size, we'll set it as the remainder and wait for more chunks 47 | if(chunk.length < this._pcmSize) { 48 | this._remainder = chunk; 49 | return cb(); 50 | } 51 | 52 | let index = 0; 53 | 54 | // Encodes every frame it can possibly encode 55 | while(index + this._pcmSize < chunk.length) { 56 | index += this._pcmSize; 57 | this.push(this._opus.encode(chunk.slice(index - this._pcmSize, index), this._framesize)); 58 | } 59 | 60 | // Sets the rest of the chunk as the remainder 61 | if(index < chunk.length) { 62 | this._remainder = chunk.slice(index); 63 | } 64 | 65 | cb(); 66 | } 67 | 68 | _flush(cb) { 69 | // If there is a remainder, we'll encode it even though it's not complete in size 70 | if(this._remainder) { 71 | let buf = Buffer.alloc(this._pcmSize, 0); 72 | this._remainder.copy(buf); 73 | this.push(this._opus.encode(buf, this._framesize)); 74 | this._remainder = null; 75 | } 76 | 77 | cb(); 78 | 79 | // Cleanup resources 80 | if(this._opus.delete) { 81 | this._opus.delete(); 82 | } 83 | } 84 | 85 | } 86 | 87 | module.exports = OpusEncoder; 88 | -------------------------------------------------------------------------------- /lib/audio/converter/OpusToolsConverter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Converter = require('../../interfaces/Converter.js'); 4 | const Utils = require('../../Utils.js'); 5 | const child_process = require('child_process'); 6 | 7 | const opusencCmd = Utils.findCommand([ 8 | process.cwd() + '/binary/opusenc', 9 | 'opusenc' 10 | ]); 11 | 12 | const mimetypes = ['audio/wav', 'audio/x-wav', 'audio/aiff', 'audio/x-aiff', 'audio/flac', 13 | 'audio/L16', 'audio/L8', 'audio/L20', 'audio/L24', 'audio/ogg']; 14 | 15 | class OpusToolsConverter extends Converter { 16 | 17 | static get available() { 18 | return opusencCmd != null; 19 | } 20 | 21 | static converts(mimetype) { 22 | return mimetypes.includes(mimetype); 23 | } 24 | 25 | static decodes(mimetype) { 26 | // Opus Tools can't decode anything to PCM, it can only convert it 27 | return false; 28 | } 29 | 30 | static convert(stream, rate, channels, frameDuration) { 31 | return Utils.createProcess(stream, opusencCmd, [ 32 | '--framesize', frameDuration, 33 | '--vbr', 34 | '--raw-rate', rate, 35 | '--raw-chan', channels, 36 | '-', '-' // Set input and output to stdin and stdout 37 | ]); 38 | } 39 | 40 | static encode(stream, rate, channels, frameDuration) { 41 | return Utils.createProcess(stream, opusencCmd, [ 42 | '--framesize', frameDuration, 43 | '--vbr', 44 | '--raw', // We know it's a PCM stream 45 | '--raw-rate', rate, 46 | '--raw-chan', channels, 47 | '-', '-' // Set input and output to stdin and stdout 48 | ]); 49 | } 50 | 51 | } 52 | 53 | module.exports = OpusToolsConverter; 54 | -------------------------------------------------------------------------------- /lib/audio/playable/FilePlayable.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Playable = require('../../interfaces/Playable.js'); 4 | 5 | const fs = require('fs'); 6 | const path = require('path'); 7 | const mime = require('mime'); 8 | 9 | const musicmetadata = (function() { 10 | try { 11 | return require('musicmetadata'); 12 | } catch(err) { 13 | return null; 14 | } 15 | })(); 16 | 17 | class FilePlayable extends Playable { 18 | 19 | constructor(file) { 20 | super(); 21 | this.file = file; 22 | 23 | let name = path.basename(file, path.extname(file)); 24 | let title = name.split(' - ', 2); 25 | this._title = title.length > 1 ? title[1] : name; 26 | this._artist = title.length > 1 ? title[0] : []; 27 | this._description = null; 28 | } 29 | 30 | get title() { 31 | return this._title; 32 | } 33 | 34 | get artist() { 35 | return this._artist; 36 | } 37 | 38 | get description() { 39 | return this._description; 40 | } 41 | 42 | loadData() { 43 | if(!musicmetadata) return Promise.reject(); 44 | 45 | return new Promise(function(resolve, reject) { 46 | let stream = fs.createReadStream(this.file); 47 | 48 | musicmetadata(stream, function(err, metadata) { 49 | if(err) return reject(err); 50 | 51 | this._title = metadata.title; 52 | this._artist = metadata.artist; 53 | this._description = metadata.album; 54 | this.emit('data-changed'); 55 | 56 | stream.close(); 57 | resolve(); 58 | 59 | }.bind(this)); 60 | }.bind(this)); 61 | } 62 | 63 | createStream() { 64 | try { 65 | return Promise.resolve(fs.createReadStream(this.file), mime.lookup(this.file)); 66 | } catch(e) { 67 | return Promise.reject(e); 68 | } 69 | } 70 | 71 | } 72 | 73 | module.exports = FilePlayable; 74 | -------------------------------------------------------------------------------- /lib/audio/playable/IcyPlayable.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Playable = require('../../interfaces/Playable.js'); 4 | 5 | const icy = require('icy'); 6 | 7 | class IcyPlayable extends Playable { 8 | 9 | constructor(url) { 10 | super(); 11 | this.url = url; 12 | } 13 | 14 | get title() { 15 | return this._title; 16 | } 17 | 18 | get artist() { 19 | return this._artist; 20 | } 21 | 22 | updateMetadata(metadata) { 23 | let md = icy.parse(metadata); 24 | 25 | let streamTitle = md['StreamTitle'] || 'Unknown'; 26 | let title = streamTitle.split(' - ', 2); 27 | 28 | if(title.length >= 2) { 29 | this._artist = title[0]; 30 | this._title = title[1]; 31 | } else { 32 | this._title = streamTitle; 33 | } 34 | 35 | this.emit('data-changed'); 36 | } 37 | 38 | loadData() { 39 | return Promise.reject('Icy only receives data in the stream'); 40 | } 41 | 42 | createStream() { 43 | return new Promise(function(resolve, reject) { 44 | icy.get(this.url, function(res) { 45 | 46 | res.on('metadata', this.updateMetadata.bind(this)); 47 | resolve(res, res.headers['Content-Type']); 48 | 49 | }.bind(this)); 50 | }.bind(this)); 51 | } 52 | 53 | } 54 | 55 | module.exports = IcyPlayable; 56 | -------------------------------------------------------------------------------- /lib/audio/playable/SoundcloudPlayable.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Playable = require('../../interfaces/Playable.js'); 4 | const Utils = require('../../Utils.js'); 5 | 6 | const https = require('https'); 7 | 8 | class SoundcloudPlayable extends Playable { 9 | 10 | constructor(key, url) { 11 | super(); 12 | this.key = key; 13 | this.url = url; 14 | } 15 | 16 | get title() { 17 | return this._title; 18 | } 19 | 20 | get artist() { 21 | return this._artist; 22 | } 23 | 24 | get description() { 25 | return this._description; 26 | } 27 | 28 | loadData() { 29 | return new Promise(function(resolve, reject) { 30 | https.get('https://api.soundcloud.com/resolve?' + 31 | 'client_id=' + encodeURIComponent(this.key) + 32 | '&url=' + encodeURIComponent(this.url), function(res) { 33 | 34 | Utils.request(res.headers.location).then(function(data) { 35 | this.readInfo(JSON.parse(data)); 36 | resolve(); 37 | }, reject); 38 | 39 | }); 40 | }); 41 | } 42 | 43 | readData(json) { 44 | this._title = json['title']; 45 | this._artist = json['label_name'] || json['user']['username']; 46 | this._description = json['description']; 47 | 48 | this.streamUrl = json['stream_url'] + "?client_id=" + encodeURIComponent(this.key); 49 | this.url = json['permalink_url']; 50 | 51 | this.emit('data-changed'); 52 | } 53 | 54 | loadStream(resolve, reject) { 55 | https.get(this.streamUrl, function(res) { 56 | resolve(res, res.headers['Content-Type']); 57 | }); 58 | } 59 | 60 | createStream() { 61 | return new Promise(function(resolve, reject) { 62 | if(this.streamUrl) { 63 | this.loadStream(resolve, reject); 64 | } else { 65 | this.loadData().then(function() { 66 | this.loadStream(resolve, reject); 67 | }.bind(this), reject); 68 | } 69 | }.bind(this)); 70 | } 71 | 72 | } 73 | 74 | module.exports = SoundcloudPlayable; 75 | -------------------------------------------------------------------------------- /lib/audio/playable/YouTubePlayable.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Playable = require('../../interfaces/Playable.js'); 4 | 5 | const ytdl = require('ytdl-core'); 6 | 7 | class YouTubePlayable extends Playable { 8 | 9 | constructor(url) { 10 | super(); 11 | this.url = url; 12 | } 13 | 14 | get title() { 15 | return this._title; 16 | } 17 | 18 | get artist() { 19 | return this._artist; 20 | } 21 | 22 | get description() { 23 | return this._description; 24 | } 25 | 26 | loadData() { 27 | return new Promise(function(resolve, reject) { 28 | ytdl.getInfo(this.url, function(err, info) { 29 | if(err) return reject(err); 30 | 31 | this.loadInfo(info); 32 | resolve(); 33 | 34 | }.bind(this)); 35 | }.bind(this)); 36 | } 37 | 38 | loadInfo(info) { 39 | let title = info.title.split(' - ', 2); 40 | 41 | if(title.length >= 2) { 42 | this._artist = title[0]; 43 | this._title = title[1]; 44 | } else { 45 | this._title = info.title; 46 | } 47 | 48 | this._description = info.description; 49 | 50 | this.url = info.loaderUrl; 51 | this.emit('data-changed'); 52 | } 53 | 54 | filterVideo(format) { 55 | return format.container === 'mp4' && format.audioEncoding != null; 56 | } 57 | 58 | createStream() { 59 | try { 60 | // Since 2014, video quality does not affect audio quality anymore, so we'll use the lowest quality 61 | const stream = ytdl(this.url, {filter: this.filterVideo, quality: 'lowest'}); 62 | stream.on('info', this.loadInfo.bind(this)); 63 | return Promise.resolve(stream); 64 | } catch(e) { 65 | return Promise.reject(e); 66 | } 67 | } 68 | 69 | } 70 | 71 | module.exports = YouTubePlayable; 72 | -------------------------------------------------------------------------------- /lib/components/ComponentManager.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const EventEmitter = require('events').EventEmitter; 4 | 5 | class ComponentManager extends EventEmitter { 6 | 7 | constructor() { 8 | super(); 9 | this._commands = {}; 10 | this._converters = []; 11 | this.on('command', this._handleCommand); 12 | } 13 | 14 | /** @private */ 15 | _handleCommand(label) {//TODO arguments 16 | const handler = this._commands[label]; 17 | if(handler) handler(label); 18 | } 19 | 20 | /** 21 | * Registers a converter 22 | * @param {Class|Class|Class} converter - A converter class 23 | */ 24 | registerConverter(converter) { 25 | this._converters.push(converter); 26 | } 27 | 28 | /** 29 | * Registers a command handler for the labels 30 | * @param {string|Array} labels - The labels that will be handled 31 | * @param {Function} handler - The function which will receive commands 32 | */ 33 | registerCommand(labels, handler) { 34 | if(labels instanceof Array) { 35 | for(let i = 0; i < labels.length; i++) { 36 | this._commands[labels[i]] = handler; 37 | } 38 | } else { 39 | this._commands[labels] = handler; 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /lib/interfaces/Component.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const EventEmitter = require('events').EventEmitter; 4 | 5 | /** 6 | * Represents a object that changes the behavior 7 | * A component adds functionality to the bot. 8 | * @class 9 | */ 10 | class Component extends EventEmitter { 11 | constructor() {//TODO 12 | 13 | } 14 | } 15 | 16 | module.exports = Component; 17 | -------------------------------------------------------------------------------- /lib/interfaces/Converter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const Decoder = require('./Decoder.js'); 4 | const Encoder = require('./Encoder.js'); 5 | const Utils = require('../Utils.js'); 6 | 7 | /** 8 | * A converter is an audio decoder and opus encoder at the same time 9 | * @class 10 | * @extends Decoder 11 | * @extends Encoder 12 | */ 13 | class Converter { 14 | 15 | /** 16 | * Whether this converter is available 17 | * @member {boolean} 18 | * @readonly 19 | * @static 20 | */ 21 | static get available() { 22 | return false; 23 | } 24 | 25 | /** 26 | * Whether the mime type can be converted 27 | * @static 28 | * @param {string} mimetype 29 | * @return {boolean} 30 | */ 31 | static converts(mimetype) { 32 | return false; 33 | } 34 | 35 | /** 36 | * Whether the mime type can be decoded 37 | * @static 38 | * @param {string} mimetype 39 | * @return {boolean} 40 | */ 41 | static decodes(mimetype) { 42 | return false; 43 | } 44 | 45 | /** 46 | * Converts an audio stream to Opus packets 47 | * @static 48 | * @param {Stream} stream 49 | * @param {number} rate - Sample Rate 50 | * @param {number} channels - Number of channels 51 | * @param {number} frameDuration 52 | * @return {Stream} - The Opus stream 53 | */ 54 | static convert(stream, rate, channels, frameDuration) { 55 | return null; 56 | } 57 | 58 | /** 59 | * Encodes a PCM stream to opus packets 60 | * @static 61 | * @param {Stream} stream 62 | * @param {number} rate - Sample Rate 63 | * @param {number} channels - Number of channels 64 | * @param {number} frameDuration 65 | * @return {Stream} - The Opus stream 66 | */ 67 | static encode(stream, rate, channels, frameDuration) { 68 | return null; 69 | } 70 | 71 | /** 72 | * Decodes an audio stream to PCM 73 | * @static 74 | * @param {Stream} stream 75 | * @param {number} rate - Sample Rate 76 | * @param {number} channels - Number of channels 77 | * @return {Stream} - The PCM stream 78 | */ 79 | static decode(stream, rate, channels) { 80 | return null; 81 | } 82 | 83 | } 84 | 85 | module.exports = Converter; 86 | -------------------------------------------------------------------------------- /lib/interfaces/Decoder.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Represents an audio to PCM decoder 5 | * @class 6 | */ 7 | class Decoder { 8 | 9 | /** 10 | * Whether this decoder is available 11 | * @member {boolean} 12 | * @readonly 13 | * @static 14 | */ 15 | static get available() { 16 | return false; 17 | } 18 | 19 | /** 20 | * Whether the mime type is accepted by this decoder 21 | * @static 22 | * @param {string} mimetype 23 | * @return {boolean} 24 | */ 25 | static decodes(mimetype) { 26 | return false; 27 | } 28 | 29 | /** 30 | * Decodes an audio stream to PCM 31 | * @static 32 | * @param {Stream} stream 33 | * @param {number} rate - Sample Rate 34 | * @param {number} channels - Number of channels 35 | * @return {Stream} - The PCM stream 36 | */ 37 | static decode(stream, rate, channels) { 38 | return null; 39 | } 40 | 41 | } 42 | 43 | module.exports = Decoder; 44 | -------------------------------------------------------------------------------- /lib/interfaces/Encoder.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Represents a PCM to Opus packets encoder 5 | * @class 6 | */ 7 | class Encoder { 8 | 9 | /** 10 | * Whether this encoder is available 11 | * @member {boolean} 12 | * @readonly 13 | * @static 14 | */ 15 | static get available() { 16 | return false; 17 | } 18 | 19 | /** 20 | * Encodes a PCM stream to opus packets 21 | * @static 22 | * @param {Stream} stream 23 | * @param {number} rate - Sample Rate 24 | * @param {number} channels - Number of channels 25 | * @param {number} frameDuration 26 | * @return {Stream} - The Opus stream 27 | */ 28 | static encode(stream, rate, channels, frameDuration) { 29 | return null; 30 | } 31 | 32 | } 33 | 34 | module.exports = Encoder; 35 | -------------------------------------------------------------------------------- /lib/interfaces/Playable.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const EventEmitter = require('events').EventEmitter; 4 | 5 | /** 6 | * Represents a track/stream link. 7 | * @class 8 | */ 9 | class Playable extends EventEmitter { 10 | 11 | constructor() { 12 | super(); 13 | /** 14 | * Custom Data 15 | * @member {?object} 16 | */ 17 | this.data = null; 18 | } 19 | 20 | /** @member {string} */ 21 | get title() { 22 | return "Unknown"; 23 | } 24 | 25 | /** @member {string|Array} */ 26 | get artist() { 27 | return []; 28 | } 29 | 30 | /** @member {?string} */ 31 | get description() { 32 | return null; 33 | } 34 | 35 | /** 36 | * Loads playable information 37 | * @return {Promise} 38 | */ 39 | loadData() { 40 | return Promise.reject('No implementation for this function'); 41 | // resolve shouldn't return anything. 'data-changed' should be emitted 42 | } 43 | 44 | /** 45 | * Creates a stream 46 | * @return {Promise} 47 | */ 48 | createStream() { 49 | return Promise.reject('No implementation for this function'); 50 | // resolve should return (stream, mimetype) 51 | // set the mimetype to "audio/L16", "audio/L8", "audio/L20" or "audio/L24" to skip the decoding process 52 | // set the mimetype to "audio/opus" to skip the decoding and encoding process 53 | } 54 | 55 | } 56 | 57 | module.exports = Playable; 58 | -------------------------------------------------------------------------------- /lib/interfaces/Playlist.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * Represents a Playlist. 5 | * @class 6 | */ 7 | class Playlist extends Array { 8 | 9 | constructor() { 10 | super(); 11 | this._index = 0; 12 | /** 13 | * Custom Data 14 | * @member {?object} 15 | */ 16 | this.data = null; 17 | } 18 | 19 | /** @member {string} */ 20 | get title() { 21 | return "Unknown"; 22 | } 23 | 24 | /** @member {?string} */ 25 | get author() { 26 | return null; 27 | } 28 | 29 | /** @member {?string} */ 30 | get description() { 31 | return null; 32 | } 33 | 34 | /** @member {?Playable} */ 35 | get currentPlayable() { 36 | if(this._index >= this.length) return null; 37 | return this[this._index]; 38 | } 39 | 40 | /** 41 | * Skips to the next playable 42 | * @return {boolean} Whether the playlist has reached the end 43 | */ 44 | skip() { 45 | return this._index++ >= this.length; 46 | } 47 | 48 | /** 49 | * Resets the playlist to the first playable 50 | */ 51 | reset() { 52 | this._index = 0; 53 | } 54 | 55 | /** 56 | * Shuffles the track order 57 | */ 58 | shuffle() { 59 | // TODO 60 | } 61 | 62 | } 63 | 64 | module.exports = Playlist; 65 | -------------------------------------------------------------------------------- /lib/ws/APISocket.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const WebSocket = require('ws'); 4 | 5 | class APISocket extends WebSocket { 6 | 7 | constructor(url) { 8 | super(url); 9 | this.hearbeatInterval = 1000; // The time in milliseconds to send heartbeats 10 | this.heartbeaten = true; // Whether the heartbeat was successful 11 | this.heartbeat = null; // Heartbeat interval 12 | 13 | this.on('error', this.handleError.bind(this)); 14 | this.on('message', this.handleMessage.bind(this)); 15 | this.once('close', this.handleClosing.bind(this)); 16 | } 17 | 18 | sendHeartbeat() { 19 | // NOOP 20 | } 21 | 22 | startHeartbeating() { 23 | if(this.heartbeat != null) clearInterval(this.heartbeat); 24 | this.heartbeat = setInterval(this.sendHeartbeat.bind(this), this.hearbeatInterval); 25 | } 26 | 27 | handleError(error) { 28 | console.log('Error: ', error); 29 | } 30 | 31 | handleMessage(data, flags) { 32 | // NOOP 33 | } 34 | 35 | handleClosing(code, message) { 36 | clearInterval(this.heartbeat); 37 | this.heartbeat = null; 38 | 39 | console.log('Close:', code, message); 40 | } 41 | 42 | } 43 | 44 | module.exports = APISocket; 45 | -------------------------------------------------------------------------------- /lib/ws/DiscordSocket.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const urlutils = require('url'); 4 | const pako = require('pako'); 5 | 6 | const APISocket = require('./APISocket.js'); 7 | const Constants = require('../Constants.js'); 8 | const Utils = require('../Utils.js'); 9 | 10 | class DiscordSocket extends APISocket { 11 | constructor(url, discord, compress) { 12 | super(url); 13 | this.discord = discord; // Discord instance 14 | this.compress = compress; // Compress 15 | this.sessionId = null; // Session ID 16 | this.userId = null; // User ID 17 | this.seq = 0; // Sequence number 18 | } 19 | 20 | send(op, data) { 21 | super.send(JSON.stringify({op: op, d: data})); 22 | } 23 | 24 | sendHeartbeat() { 25 | if(!this.heartbeaten) { 26 | console.log('NO DISCORD CONNECTION!'); 27 | return; // TODO 28 | } 29 | this.send(Constants.OP_HEARTBEAT, this.seq); 30 | this.heartbeaten = false; 31 | } 32 | 33 | connectVoice(guildId, channelId) { 34 | this.send(Constants.OP_VOICE_STATE_UPDATE, { 35 | guild_id: guildId, 36 | channel_id: channelId, 37 | self_mute: false, 38 | self_deaf: false 39 | }); 40 | } 41 | 42 | handleHello(data) { 43 | this.send(Constants.OP_IDENTITY, { 44 | token: this.discord.token, 45 | properties: { 46 | '$browser': 'DiscordDJ', 47 | '$device': 'DiscordDJ' 48 | }, 49 | compress: this.compress, // TODO use compression 50 | large_threshold: 50, // TODO leave it as is? 51 | shard: [this.discord._currentShard, this.discord._totalShards] 52 | }); 53 | 54 | this.hearbeatInterval = data['heartbeat_interval']; 55 | this.startHeartbeating(); 56 | } 57 | 58 | handleEvents(seq, type, data) { 59 | if(seq && this.sessionId) { 60 | this.seq = seq; 61 | } 62 | 63 | switch(type) { 64 | case Constants.EVENT_READY: 65 | this.sessionId = data['session_id']; 66 | this.userId = data['user']['id']; 67 | this.discord.emit('ready'); 68 | break; 69 | case Constants.EVENT_VOICE_SERVER_UPDATE: 70 | var djs = this.discord.djs; 71 | for(var i = 0; i < djs.length; i++) { 72 | if(djs[i].guildId == data['guild_id']) { 73 | djs[i].emit('update-connection', data['token'], data['endpoint']); 74 | break; 75 | } 76 | } 77 | break; 78 | default: 79 | console.log('Event:', type); 80 | break; 81 | } 82 | } 83 | 84 | handleMessage(data, flags) { 85 | if(this.compress && (data instanceof Buffer || data instanceof ArrayBuffer)) { 86 | data = pako.inflate(data, {to: "string"}); 87 | } 88 | 89 | var json = JSON.parse(data); 90 | switch(json['op']) { 91 | case Constants.OP_DISPATCH: 92 | this.handleEvents(json['s'], json['t'], json['d']); 93 | break; 94 | case Constants.OP_HEARTBEAT_ACK: 95 | this.heartbeaten = true; 96 | break; 97 | case Constants.OP_HELLO: 98 | this.handleHello(json['d']); 99 | break; 100 | default: 101 | console.log('Unknown OP code:', json['op']); 102 | break; 103 | } 104 | } 105 | 106 | } 107 | 108 | DiscordSocket.retrieveGatewayURL = function() { 109 | return new Promise(function(resolve, reject) { 110 | Utils.request('https://discordapp.com/api/gateway', 'GET').then(function(result) { 111 | resolve(JSON.parse(result).url); 112 | }.bind(this), reject); 113 | }.bind(this)); 114 | }; 115 | 116 | DiscordSocket.createSocket = function(url, discord) { 117 | return new Promise(function(resolve, reject) { 118 | 119 | url = urlutils.parse(url); 120 | url.query = {encoding: 'json', v: Constants.API_VERSION}; 121 | url.pathname = url.pathname || "/"; 122 | 123 | var socket = new DiscordSocket(urlutils.format(url), discord); 124 | socket.once('open', function() { 125 | resolve(socket); 126 | }); 127 | 128 | }.bind(this)); 129 | }; 130 | 131 | module.exports = DiscordSocket; 132 | -------------------------------------------------------------------------------- /lib/ws/VoiceSocket.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const urlutils = require('url'); 4 | 5 | const APISocket = require('./APISocket.js'); 6 | const Constants = require('../Constants.js'); 7 | 8 | const secretbox = (function() { 9 | try { 10 | return require('sodium').api.crypto_secretbox; 11 | } catch(e) { 12 | return require('tweetnacl').secretbox; 13 | } 14 | })(); 15 | 16 | class VoiceSocket extends APISocket { 17 | 18 | constructor(dj, url, token, encryption) { 19 | super(VoiceSocket.formatWSAddr(url)); 20 | this.url = url; // The socket URL 21 | this.dj = dj; // DJ instance 22 | this.encryption = encryption; // Encryption 23 | 24 | this.secret = null; // Secret Key 25 | this.ssrc = null; // SSRC 26 | this.seq = 0; // Sequence Number 27 | this.timestamp = 0; // Timestamp 28 | this.rtpHeader = null; // RTP Header Buffer 29 | 30 | this.once('open', function() { 31 | // Identify ourselves :) 32 | this.send(Constants.VOP_IDENTITY, { 33 | server_id: dj.guildId, 34 | user_id: dj._discord._socket.userId, 35 | session_id: dj._discord._socket.sessionId, 36 | token: token 37 | }); 38 | }.bind(this)); 39 | } 40 | 41 | send(op, data) { 42 | super.send(JSON.stringify({op: op, d: data})); 43 | } 44 | 45 | sendAudio(buffer, sampleCount) { 46 | // NOOP 47 | } 48 | 49 | setSpeaking(speaking) { 50 | this.send(Constants.VOP_SPEAKING, { 51 | delay: 0, 52 | speaking: speaking 53 | }); 54 | } 55 | 56 | /** @private */ 57 | _initHeader() { 58 | // RTP Header 59 | this.rtpHeader = Buffer.alloc(Constants.RTP_HEADER_SIZE + Constants.RTP_NONCE_SIZE, 0); 60 | this.rtpHeader[Constants.RTP_HEADER_VERSION_OFFSET] = 0x80; // Version 2 61 | this.rtpHeader[Constants.RTP_HEADER_TYPE_OFFSET] = 0x78; // Type 120 62 | this.rtpHeader.writeUInt32BE(this.ssrc, Constants.RTP_HEADER_SSRC_OFFSET); // SSRC 63 | } 64 | 65 | /** 66 | * Creates a packet based on a Opus encoded buffer 67 | */ 68 | createPacket(buffer, sampleCount) { 69 | if(this.rtpHeader == null) this._initHeader(); 70 | 71 | // Write packet data 72 | this.rtpHeader.writeUInt16BE(this.seq, Constants.RTP_HEADER_SEQ_OFFSET); // Sequence 73 | this.rtpHeader.writeUInt32BE(this.timestamp, Constants.RPT_HEADER_TIMESTAMP_OFFSET); // Timestamp 74 | 75 | // Use encryption when necessary 76 | if(this.encryption == Constants.VOICE_ENCRYPTION_SODIUM) { 77 | buffer = secretbox(buffer, this.rtpHeader, this.secret); 78 | } 79 | 80 | // Thanks to discordie, again, for the code below 81 | // Copies the header and then the audio buffer 82 | const rtpPacket = VoiceSocket.rtpPacket; 83 | const bufferLength = buffer.length; 84 | this.rtpHeader.copy(rtpPacket, 0, 0, Constants.RTP_HEADER_SIZE); 85 | for(var i = 0; i < bufferLength; i++) { 86 | rtpPacket[Constants.RTP_HEADER_SIZE + i] = buffer[i]; 87 | } 88 | 89 | // Increases sequence and timestamp, clamping them to not overflow its packets sizes 90 | this.seq++; 91 | this.timestamp += sampleCount; 92 | if(this.seq >= 0xFFFF) this.seq %= 0xFFFF + 1; // Prevents overflowing 2 unsigned bytes 93 | if(this.timestamp >= 0xFFFFFFFF) this.timestamp %= 0xFFFFFFFF + 1; // Prevents overflowing 4 unsigned bytes 94 | 95 | // Slices the packet data from the buffer 96 | return rtpPacket.slice(0, bufferLength + Constants.RTP_HEADER_SIZE); 97 | } 98 | 99 | sendHeartbeat() { 100 | if(!this.heartbeaten) { 101 | console.log('NO VOICE CONNECTION!'); 102 | return; // TODO 103 | } 104 | this.send(Constants.VOP_HEARTBEAT, Date.now()); 105 | this.heartbeaten = false; 106 | } 107 | 108 | handleReady(data) { 109 | this.hearbeatInterval = data['heartbeat_interval']; 110 | this.startHeartbeating(); 111 | 112 | this.ssrc = data['ssrc']; 113 | this.rtpHeader = null; 114 | } 115 | 116 | handleMessage(data, flags) { 117 | let json = JSON.parse(data); 118 | 119 | switch(json['op']) { 120 | case Constants.VOP_SPEAKING: 121 | case Constants.VOP_IGNORE: 122 | // Just ignore it 123 | break; 124 | case Constants.VOP_HEARTBEAT: 125 | this.heartbeaten = true; 126 | break; 127 | case Constants.VOP_READY: 128 | this.handleReady(json['d']); 129 | break; 130 | case Constants.VOP_SESSION_DESCRIPTION: 131 | this.secret = Buffer.from(json['d']['secret_key']); 132 | this.setSpeaking(false); 133 | this.dj.emit('ready'); // We are finally ready to send voice packets! 134 | break; 135 | default: 136 | console.log('Unknown Voice OP Code:', json['op']); 137 | break; 138 | } 139 | } 140 | 141 | } 142 | 143 | VoiceSocket.formatWSAddr = function(url) { 144 | // Removes port 80 to prevent EPROTO errors 145 | let i = url.lastIndexOf(':'); 146 | if(url.substring(i + 1) == '80') url = url.substring(0, i); 147 | 148 | return 'wss://' + url; // Adds websocket protocol 149 | }; 150 | 151 | VoiceSocket.rtpPacket = Buffer.alloc(2048, 0); // Pre-allocate the buffer 152 | 153 | module.exports = VoiceSocket; 154 | -------------------------------------------------------------------------------- /lib/ws/VoiceUDPSocket.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const dns = require('dns'); 4 | const dgram = require('dgram'); 5 | 6 | const VoiceSocket = require('./VoiceSocket.js'); 7 | const Constants = require('../Constants.js'); 8 | 9 | class VoiceUDPSocket extends VoiceSocket { 10 | 11 | constructor(dj, url, token, encryption) { 12 | super(dj, url, token, encryption); 13 | 14 | this.udp = null; // UDP Socket 15 | this.udpIp = null; // UDP IP 16 | this.udpPort = 80; // UDP Port 17 | this.localIp = null; // Local IP 18 | this.localPort = null; // Local Port 19 | } 20 | 21 | sendUDP(data) { 22 | this.udp.send(data, 0, data.length, this.udpPort, this.udpIp); 23 | } 24 | 25 | sendAudio(buffer, sampleCount) { 26 | let packet = this.createPacket(buffer, sampleCount); 27 | 28 | if(packet.length == Constants.IP_DISCOVERY_SIZE) { 29 | // Prevent the audio packet from looking as an ip discovery packet by adding one extra byte 30 | packet = Buffer.concat([packet, Buffer.alloc(1, 0)]); 31 | } 32 | 33 | this.sendUDP(packet); 34 | } 35 | 36 | handleReady(data) { 37 | super.handleReady(data); 38 | 39 | dns.resolve(VoiceUDPSocket.formatUDPAddr(this.url), function(err, addresses) { 40 | if(err) return console.err('Could not connect to a voice channel:', err); //TODO handle this in a better way 41 | 42 | this.udpIp = addresses[0]; 43 | this.udpPort = data['port']; 44 | 45 | this.udp = dgram.createSocket('udp4'); 46 | this.udp.on('message', this.handleUDPMessage.bind(this)); 47 | 48 | // Send an ip discovery packet to the server to get the local ip and port 49 | let packet = Buffer.alloc(Constants.IP_DISCOVERY_SIZE, 0); 50 | packet.writeUInt32BE(this.ssrc, Constants.IP_DISCOVERY_SSRC_OFFSET); 51 | this.sendUDP(packet); 52 | 53 | }.bind(this)); 54 | } 55 | 56 | handleUDPMessage(msg, from) { 57 | if(msg.length == Constants.IP_DISCOVERY_SIZE) { // Receive the local ip 58 | if(msg.readUInt32LE(Constants.IP_DISCOVERY_SSRC_OFFSET) != this.ssrc) return; 59 | 60 | // Thanks to discordie for the code below that retrieves the local ip and port 61 | this.localIp = msg.slice(4, 68).toString().split("\x00")[0]; 62 | this.localPort = msg[68] | msg[69] << 8; 63 | 64 | // Select the protocol 65 | this.send(Constants.VOP_SELECT_PROTOCOL, { 66 | protocol: 'udp', 67 | data: { 68 | address: this.localIp, 69 | port: this.localPort, 70 | mode: this.encryption 71 | } 72 | }); 73 | } 74 | } 75 | 76 | terminate() { 77 | super.terminate(); 78 | this.udp.close(); 79 | this.udp = null; 80 | } 81 | 82 | } 83 | 84 | VoiceUDPSocket.formatUDPAddr = function(url) { 85 | // Removes port to prevent ENOTFOUND errors 86 | return url.substring(0, url.lastIndexOf(':')); 87 | }; 88 | 89 | module.exports = VoiceUDPSocket; 90 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "discord-dj", 3 | "description": "Discord DJ Bot. Let you play music in your server. Inspired by PlugDJ", 4 | "version": "0.1.0", 5 | "main": "lib/test.js", 6 | "author": "Guichaguri", 7 | "license": "LGPL-2.0", 8 | "dependencies": { 9 | "icy": "2.1.0", 10 | "opusscript": "0.0.2", 11 | "pako": "1.0.3", 12 | "tweetnacl": "0.14.3", 13 | "ws": "1.1.1", 14 | "ytdl-core": "^0.7.24" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/Guichaguri/DiscordDJ.git" 19 | }, 20 | "keywords": [ 21 | "discord", 22 | "bot", 23 | "dj", 24 | "music", 25 | "discorddj", 26 | "discord-dj" 27 | ], 28 | "scripts": { 29 | "start": "node ./runtime/DiscordDJ.js", 30 | "gen-docs": "jsdoc -c jsdoc.json" 31 | }, 32 | "bugs": { 33 | "url": "https://github.com/Guichaguri/DiscordDJ/issues" 34 | }, 35 | "homepage": "https://github.com/Guichaguri/DiscordDJ#readme" 36 | } 37 | --------------------------------------------------------------------------------