Compare commits

..

No commits in common. "3.0" and "v2.3.1" have entirely different histories.
3.0 ... v2.3.1

368 changed files with 38627 additions and 176121 deletions

View file

@ -1,45 +0,0 @@
/* ESLint Config */
module.exports = {
env: {
'es2017': true,
// others envs defined by cascading .eslintrc files
},
extends: 'eslint:recommended',
parser: '@babel/eslint-parser',
parserOptions: {
'sourceType': 'module',
},
rules: {
'brace-style': ['error','1tbs',{ 'allowSingleLine': true }],
'indent': [
'off', // temporary... a lot of stuff needs to be reformatted | 2020-08-21: I guess it's not so temporary...
4,
{ 'SwitchCase': 1 }
],
'linebreak-style': ['error','unix'],
'no-control-regex': ['off'],
'no-prototype-builtins': ['off'], // should consider cleaning up the code and turning this back on at some point
'no-trailing-spaces': ['error'],
'no-unused-vars': [
'error', {
'argsIgnorePattern': '^_',
'varsIgnorePattern': '^_|^Promise$'
}
],
'semi': ['error','always'],
'quotes': ['off'] // Old code uses double quotes, new code uses single / template
},
ignorePatterns: [
// These are not ours
'www/js/dash.all.min.js',
'www/js/jquery-1.12.4.min.js',
'www/js/jquery-ui.js',
'www/js/peertube.js',
'www/js/playerjs-0.0.12.js',
'www/js/sc.js',
'www/js/video.js',
'www/js/videojs-contrib-hls.min.js',
'www/js/videojs-dash.js',
'www/js/videojs-resolution-switcher.js',
],
}

24
.gitignore vendored
View file

@ -1,24 +0,0 @@
*.swp
cfg.json
config.yaml
chandump
chanlogs
*.log
node_modules
*.crt
*.cert
*.key
torlist
www/cache
google-drive-subtitles
lib/
integration-test-config.json
conf/*.toml
www/js/cytube-google-drive.user.js
www/js/cytube-google-drive.meta.js
www/js/player.js
tor-exit-list.json
*.patch
examples/demo-bot/.env
mysql/
peertube-hosts.json

View file

@ -1,14 +0,0 @@
language: node_js
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-9
- g++-9
env:
- CXX="g++-9"
node_js:
- "15"
- "14"
- "12"

View file

@ -1,18 +0,0 @@
FROM node:20
RUN apt update && apt install -y build-essential git wget
COPY ./ /app
WORKDIR /app
RUN rm -rf node_modules lib package-lock.json
RUN npm cache clean --force
RUN npm install
RUN /bin/sh /app/postinstall.sh
RUN npm run build-server
RUN npm rebuild
RUN wget https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -O /usr/local/bin/yt-dlp
RUN chmod a+rx /usr/local/bin/yt-dlp
CMD ["node", "index.js"]

View file

@ -1,47 +0,0 @@
Please fill out the templates below to the best of your ability, based on whether your problem is with using the website or with running your own server.
## Website Problem ##
**Please confirm whether you've tried the following debugging steps:**
- [ ] Clearing cache and refreshing the page (On Firefox, press Ctrl+F5. On Chrome, press F12, then right click the refresh button and click "Empty Cache and Hard Reload")
- [ ] Disabling all browser extensions
- [ ] Using a clean channel with no customizations
### Description of the Problem ###
- What triggers the problem?
- What happens?
- What do you expect to happen instead?
### System Information ###
- **Operating System (Windows / Mac / Linux / Android / iOS):**
- **Web Browser (Firefox / Chrome / Other):**
- **Error Messages Displayed:**
- **Screenshot of JavaScript Console:**
_On Firefox, press `Ctrl+Shift+K` to open the JavaScript console. On Chrome, press `Ctrl+Shift+J`._
## Server Problem ##
_If your issue is related to using the website and not about running a server, you can remove this section._
**Please confirm whether you've tried the following debugging steps:**
- [ ] Run `npm run build-server` to regenerate `lib/` from `src/`
- [ ] Run `rm -rf node_modules && npm install` to get a fresh install of dependencies
- [ ] Restarted the server
### Description of the Problem ###
- What triggers the problem?
- What happens?
- What do you expect to happen instead?
### System Information ###
- **Operating System:**
- **Node Version:** _(run `node -v`)_
- **CyTube Version:** _(displayed at startup)_
- **Error Messages Displayed:**

View file

@ -1,6 +1,6 @@
/*
The MIT License (MIT)
Copyright (c) 2013-2022 Calvin Montgomery and contributors
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

501
NEWS.md
View file

@ -1,501 +0,0 @@
2022-09-21
==========
**Upgrade intervention required**
This release adds a feature to ban channels, replacing the earlier (hastily
added) configuration-based `channel-blacklist`. If you have any entries in
`channel-blacklist` in your `config.yaml`, you will need to migrate them to the
new bans table by using a command after upgrading (the ACP web interface hasn't
been updated for this feature):
./bin/admin.js ban-channel <channel-name> <external-reason> <internal-reason>
The external reason will be displayed when users attempt to join the banned
channel, while the internal reason is only displayed when using the
`show-channel-ban` command.
You can later use `unban-channel` to remove a ban. The owner of the banned
channel can still delete it, but the banned state will persist, so the channel
cannot be re-registered later.
2022-08-28
==========
This release integrates Xaekai's added support for Bandcamp, BitChute, Odysee,
and Nicovideo playback support into the main repository. The updated support
for custom fonts and audio tracks in custom media manifests is also included,
but does not work out of the box -- it requires a separate channel script; this
may be addressed in the future.
2021-08-14
==========
CyTube has been upgraded to socket.io v4 (from v2).
**Breaking change:** Newer versions of socket.io require CORS to validate the
origin initiating the socket connection. CyTube allows the origins specified in
the `io.domain` and `https.domain` configuration keys by default, which should
work for many use cases, however, if you host your website on a different domain
than the socket connection, you will need to configure the allowed origins (see
config.template.yaml under `io.cors`).
CyTube enables the `allowEIO3` configuration in socket.io by default, which
means that existing clients and bots using socket.io-client v2 should continue
to work.
2021-08-12
==========
The legacy metrics recorder (`counters.log` file) has been removed. For over 4
years now, CyTube has integrated with [Prometheus](https://prometheus.io/),
which provides a superior way to monitor the application. Copy
`conf/example/prometheus.toml` to `conf/prometheus.toml` and edit it to
configure CyTube's Prometheus support.
2021-08-12
==========
Due to changes in Soundcloud's authorization scheme, support has been dropped
from core due to requiring each server owner to register an API key (which is
currently impossible as they have not accepted new API key registrations for
*years*).
If you happen to already have an API key registered, or if Soundcloud reopens
registration at some point in the future, feel free to reach out to me for
patches to reintroduce support for it.
2020-08-21
==========
Some of CyTube's dependencies depends on features in newer versions of node.js.
Accordingly, node 10 is no longer supported. Administrators are recommended to
use node 12 (the active LTS), or node 14 (the current version).
2020-06-22
==========
Twitch has [updated their embed
player](https://discuss.dev.twitch.tv/t/twitch-embedded-player-migration-timeline-update/25588),
which adds new requirements for embedding Twitch:
1. The origin website must be served over HTTPS
2. The origin website must be served over the default port (i.e., the hostname
cannot include a port; https://example.com:8443 won't work)
Additionally, third-party cookies must be enabled for whatever internal
subdomains Twitch is using.
CyTube now sets the parameters expected by Twitch, and displays an error message
if it detects (1) or (2) above are not met.
2020-02-15
==========
Old versions of CyTube defaulted to storing channel state in flatfiles located
in the `chandump` directory. The default was changed a while ago, and the
flatfile storage mechanism has now been removed.
Admins who have not already migrated their installation to the "database"
channel storage type can do so by following these instructions:
1. Run `git checkout e3a9915b454b32e49d3871c94c839899f809520a` to temporarily
switch to temporarily revert to the previous version of the code that
supports the "file" channel storage type
2. Run `npm run build-server` to build the old version
3. Run `node lib/channel-storage/migrator.js |& tee migration.log` to migrate
channel state from files to the database
4. Inspect the output of the migration tool for errors
5. Set `channel-storage`/`type` to `"database"` in `config.yaml` and start the
server. Load a channel to verify the migration worked as expected
6. Upgrade back to the latest version with `git checkout 3.0` and `npm run
build-server`
7. Remove the `channel-storage` block from `config.yaml` and remove the
`chandump` directory since it is no longer needed (you may wish to archive
it somewhere in case you later discover the migration didn't work as
expected).
If you encounter any errors during the process, please file an issue on GitHub
and attach the output of the migration tool (which if you use the above commands
will be written to `migration.log`).
2019-12-01
==========
In accordance with node v8 LTS becoming end-of-life on 2019-12-31, CyTube no
longer supports v8.
Please upgrade to v10 or v12 (active LTS); refer to
https://nodejs.org/en/about/releases/ for the node.js support timelines.
2018-12-07
==========
Users can now self-service request their account to be deleted, and it will be
automatically purged after 7 days. In order to send a notification email to
the user about the request, copy the [email
configuration](https://github.com/calzoneman/sync/blob/3.0/conf/example/email.toml#L43)
to `conf/email.toml` (the same file used for password reset emails).
2018-10-21
==========
The `sanitize-html` dependency has made a change that results in `"` no longer
being replaced by `&quot;` when not inside an HTML attribute value. This
potentially breaks any chat filters matching quotes as `&quot;` (on my
particular instance, this seems to be quite rare). These filters will need to
be updated in order to continue matching quotes.
2018-08-27
==========
Support for node.js 6.x has been dropped, in order to bump the babel preset to
generate more efficient code (8.x supports async-await and other ES6+ features
natively and is the current node.js LTS).
If you are unable to upgrade to node.js 8.x, you can revert the changes to
package.json in this commit, however, be warned that I no longer test on 6.x.
2018-06-03
==========
## Dependency upgrades
In order to support node.js 10, the `bcrypt` dependency has been upgraded to
version 2. `bcrypt` version 2 defaults to the `$2b$` algorithm, whereas version
1 defaults to the `$2a$` algorithm. Existing password hashes will continue to
be readable, however hashes created with version 2 will not be readable by
version 1. See https://github.com/kelektiv/node.bcrypt.js for details.
In addition, the optional dependency on `v8-profiler` has been removed, since
this is not compatible with newer versions of v8.
## Supported node.js versions
In accordance with the node.js release schedule, node.js 4.x, 5.x, 7.x, and 9.x
are end-of-life and are no longer maintained upstream. Accordingly, these
versions are no longer supported by CyTube.
Please upgrade to 8.x (LTS) or 10.x (current). 6.x is still supported, but is
in the "maintenance" phase upstream, and should be phased out.
2018-01-07
==========
**Build changes:** When the `babel` dependency was first added to transpile ES6
code to ES5, an interactive prompt was added to the `postinstall` script before
transpilation, in case the user had made local modifications to the files in
`lib` which previously would have been detected as a git conflict when pulling.
It has now been sufficiently long that this is no longer needed, so I've removed
it. As always, users wishing to make local modifications (or forks) should edit
the code in `src/` and run `npm run build-server` to regenerate `lib/`.
This commit also removes the bundled `www/js/player.js` file in favor of having
`postinstall` generate it from the sources in `player/`.
2017-12-24
==========
As of December 2017, Vid.me is no longer in service. Accordingly, Vid.me
support in CyTube has been deprecated.
2017-11-27
==========
The Google Drive userscript has been updated once again. Violentmonkey is
now explicitly supported. Google login redirects are caught and handled.
See directly below on how to regenerate the user script again.
2017-11-15
==========
The Google Drive userscript has been updated due to breaking changes in
Greasemonkey 4.0. Remember to generate the script by running:
$ npm run generate-userscript "Your Site Name" http://your-site.example.com/r/*
2017-11-05
==========
The latest commit introduces a referrer check in the account page handlers.
This is added as a short-term mitigation for a recent report that account
management functions (such as deleting channels) can be executed without the
user's consent if placed in channel JS.
Longer term options are being considered, such as moving account management to a
separate subdomain to take advantage of cross-origin checks in browsers, and
requiring the user to re-enter their password to demonstrate intent. As always,
I recommend admins take extreme caution when accepting channel JS.
2017-09-26
==========
**Breaking change:** the `nodemailer` dependency has been upgraded to version
4.x. I also took this opportunity to make some modifications to the email
configuration and move it out of `config.yaml` to `conf/email.toml`.
To upgrade:
* Run `npm upgrade` (or `rm -rf node_modules; npm install`)
* Copy `conf/example/email.toml` to `conf/email.toml`
* Edit `conf/email.toml` to your liking
* Remove the `mail:` block from `config.yaml`
This feature only supports sending via SMTP for now. If there is demand for
other transports, feel free to open an issue or submit a pull request.
2017-09-19
==========
The `/useragreement` default page has been removed. Server administrators can
substitute their own terms of service page by editing `templates/footer.pug`
2017-09-19
==========
This commit removes an old kludge that redirected users to HTTPS (when enabled)
specifically for the account authorization pages (e.g., `/login`). The code for
doing this was to work around limitations that no longer exist, and does not
represent current security best practices.
The recommended solution to ensure that users are logged in securely (assuming
you've configured support for HTTPS) is to use
[Strict-Transport-Security](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security)
to direct browsers to access the HTTPS version of the website at all times. You
can enable this by configuring a reverse proxy (e.g. nginx) in front of CyTube
to intercept HTTP traffic and redirect it to HTTPS, and add the
`Strict-Transport-Security` header when returning the response from CyTube.
2017-07-22
==========
Support for the old version of Vimeo's OAuth API (the `vimeo-oauth`
configuration block) has been dropped. It's unlikely anyone was using this,
since you haven't been able to register new API keys for it in years (it was
superseded by a newer OAuth API, which CyTube does not support), and in fact I
lost my credentials for this API and no longer have a way to test it.
Vimeo videos can still be added -- the metadata will be queried from the
anonymous API which has been the default since the beginning.
2017-07-17
==========
The `stats` database table and associated ACP subpage have been removed in favor
of integration with [Prometheus](https://prometheus.io/). You can enable
Prometheus reporting by copying `conf/example/prometheus.toml` to
`conf/prometheus.toml` and editing it to your liking. I recommend integrating
Prometheus with [Grafana](https://grafana.com/) for dashboarding needs.
The particular metrics that were saved in the `stats` table are reported by the
following Prometheus metrics:
* Channel count: `cytube_channels_num_active` gauge.
* User count: `cytube_sockets_num_connected` gauge (labeled by socket.io
transport).
* CPU/Memory: default metrics emitted by the
[`prom-client`](https://github.com/siimon/prom-client) module.
More Prometheus metrics will be added in the future to make CyTube easier to
monitor :)
2017-07-15
==========
The latest commit upgrades `socket.io` to version 2.0, a major version change
from 1.4. This release improves performance by switching to `uws` for the
websocket transport, and fixes several bugs; you can read about it
[here](https://github.com/socketio/socket.io/releases/tag/2.0.0).
For browser clients, the upgrade should basically just work with no
intervention. For node.js clients, all that is needed is to upgrade
`socket.io-client` to 2.0. For other clients, work required may vary depending
on whether the implementation has compatibility problems with 2.0.
2017-06-20
==========
The latest commit drops support for node.js versions below 6 (the [current
LTS](https://github.com/nodejs/LTS#lts-schedule1)). This is to allow the babel
preset to avoid generating inefficient code to polyfill ES2015+ features that
are now implemented in the node.js core.
New versions of node.js can be downloaded from the [node.js
website](https://nodejs.org/en/download/), if they are not already available in
your distribution's package manager.
2017-03-20
==========
Polls are now more strictly validated, including the number of options. The
default limit is 50 options, which you can configure via `poll.max-options`.
2017-03-11
==========
Commit f8183bea1b37154d79db741ac2845adf282e7514 modifes the schema of the
`users` table to include a new column (`name_dedupe`) which has a `UNIQUE`
constraint. This column is populated with a modified version of the user's name
to prevent the registration of usernames which are bitwise distinct but visually
similar. 'l', 'L', and '1' are all mapped to '1'; 'o', 'O', and '0' are all
mapped to '0'; '\_' and '-' are mapped to '\_'. On first startup after
upgrading, the new column will be added and populated.
This replaces the earlier solution which was put in place to mitigate PR#489 but
was overly-restrictive since it wildcarded these characters against *any*
character, not just characters in the same group.
2017-03-03
==========
The dependency on `sanitize-html`, which previously pointed to a fork, has now
been switched back to the upstream module. XSS filtering has been turned off
for the chat filter replacement itself (since this provides no additional
security), and is now only run on the final chat message after filtering.
Certain chat filters and MOTDs which relied on syntactically incorrect HTML,
such as unclosed tags, may have different behavior now, since `sanitize-html`
fixes these.
2016-11-02
==========
After upgrading the dependency on `yamljs`, you may see this error if you didn't
notice and correct a typo in the config.yaml template:
Error loading config file config.yaml:
{ [Error: Unexpected characters near ",".]
message: 'Unexpected characters near ",".',
parsedLine: 88,
snippet: 'title: \'CyTube\',' }
The fix is to edit config.yaml and remove the trailing comma for the `title:`
property under `html-template`. If there are other syntax errors that the old
version didn't detect, you will need to correct those as well.
Longer term, I am looking to move away from using `yamljs` to parse
configuration because it's a little buggy and the current configuration system
is confusing.
2016-10-20
==========
Google Drive changed the URL schema for retrieving video metadata, which broke
CyTube's Google Drive support, even with the userscript. I have updated the
userscript source with the new URL, so server administrators will have to
regenerate the userscript for their site and users will be prompted to install
the newer version.
Additionally, fixing Drive lookups required an update to the `mediaquery`
module, so you will have to do an `npm install` to pull that fix in.
2016-08-23
==========
A few weeks ago, the previous Google Drive player stopped working. This is
nothing new; Google Drive has consistently broken a few times a year ever since
support for it was added. However, it's becoming increasingly difficult and
complicated to provide good support for Google Drive, so I've made the decision
to phase out the native player and require a userscript for it, in order to
bypass CORS and allow each browser to request the video stream itself.
See [the updated documentation](docs/gdrive-userscript-serveradmins.md) for
details on how to enable this for your users.
2016-04-27
==========
A new dependency has been added on `cytube-common`, a module that will hold
common code shared between the current version of CyTube and the upcoming work
around splitting it into multiple services. You will need to be sure to run
`npm install` after pulling in this change to pull in the new dependency.
2016-01-06
==========
This release updates socket.io to version 1.4.0. The updates to socket.io
include a few security-related fixes, so please be sure to run `npm install`
to ensure the updated version is installed before restarting your CyTube server.
* https://nodesecurity.io/advisories/67
* https://github.com/socketio/engine.io/commit/391ce0dc8b88a6609d88db83ea064040a05ab803
2015-10-25
==========
In order to support future clustering support, the legacy `/sioconfig`
endpoint is being deprecated. Instead, you should make a request to
`/socketconfig/<channel name>.json`. See [the
documentation](docs/socketconfig.md) for more information.
2015-10-04
==========
* The channel data storage system has been refactored a bit. For
compatibility, the default remains to store JSON objects for each channel in
the `chandump` folder, however there is now also the option of storing
channel data in the database. You can take advantage of this by setting
`channel-storage: type: 'database'` in your `config.yaml`.
- In order to migrate existing channel data from the `chandump` files to the
database, run `node lib/channel-storage/migrate.js`.
* The database storage method uses foreign keys to associate the channel data
with the corresponding row in the `channels` table. This requires that the
tables be stored using the InnoDB engine rather than MyISAM. If your CyTube
tables defaulted to MyISAM, you can fix them by running
```sql
ALTER TABLE `channels` ENGINE = InnoDB;
```
2015-09-21
==========
* CyTube is now transpiled with [babel] to allow the use of ES6/ES2015
features. All source files have been moved from `lib` to `src`.
* Running `npm install` or `npm run postinstall` will prompt you to
build from `src` to `lib`.
* Running `npm run build-server` will run the build script without any
prompts.
* After updating with `git pull`, you should run `npm install` or `npm run
build-server` in order to rebuild after the changes.
[babel]: https://babeljs.io/
2015-07-25
==========
* CyTube now supports subtitles for Google Drive videos. In order to take
advantage of this, you must upgrade mediaquery by running `npm install
cytube/mediaquery`. Subtitles are cached in the google-drive-subtitles
folder.
2015-07-07
==========
* CyTube and CyTube/mediaquery have both been updated to use
calzoneman/status-message-polyfill to polyfill res.statusMessage on older
versions of node (e.g., v0.10). After pulling, run `npm install` to update
this dependency. This fixes an issue where HTTP status messages from
mediaquery were reported as `undefined`, and removes the need for manually
looking up status messages in `lib/ffmpeg.js`.
2015-07-06
==========
* As part of the video player rewrite, Google Drive and Google+ metadata
lookups are now offloaded to CyTube/mediaquery. After pulling the new
changes, run `npm install` or `npm update` to update the mediaquery
dependency.
* `www/js/player.js` is now built from the CoffeeScript source files in the
`player/` directory. Instead of modifying it directly, modify the relevant
player implementations in `player/` and run `npm run build-player` (or `node
build-player.js`) to generate `www/js/player.js`.
* Also as part of the video player rewrite, the schema for custom embeds
changed so any custom embeds stored in the `channel_libraries` table need to
be updated. The automatic upgrade script will convert any custom embeds
that are parseable (i.e., not truncated by the width of the `id` field using
the old format) and will delete the rest (you may see a lot of WARNING:
unable to convert xxx messages-- this is normal). Custom embeds in channel
playlists in the chandumps will be converted when the channel is loaded.

View file

@ -1,46 +1,77 @@
CyTube
======
Read before submitting an issue: https://github.com/calzoneman/sync/wiki/Reporting-an-Issue
===========================================================================================
CyTube is a project I started in early 2013 as a hobby project to build my own
clone of synchtube.com (which shut down in March 2013).
calzoneman/sync
===============
The basic concept is that users register channels where connected viewers can
watch videos from different video hosts (e.g., YouTube, Twitch) and the playback
is synchronized for all the viewers in the channel.
About
-----
Each channel has a playlist where users can queue up videos to play, as well as
an integrated chatroom for discussion.
CyTube (formerly Sync) is a server/client combination providing media synchronization, chat,
and administration for an arbitrary number of channels.
I began developing this as a hobby project, and when Synchtube announced their closure, I
began polishing it and readying it for the public.
The official server is located at https://cytu.be, but there are other public
servers hosted for various communities.
I am hosting a CyTube server at http://cytu.be
## Installation
The serverside is written in JavaScript and runs on Node.JS. It makes use
of a MySQL database to store user registrations, cached media metadata, and
data about each channel.
The installation guide for server administrators is located [on the
wiki](https://github.com/calzoneman/sync/wiki/CyTube-3.0-Installation-Guide).
The clientside is written in JavaScript and makes use of Socket.IO and
jQuery as well as the APIs for various media providers.
The web interface uses Bootstrap for layout and styling.
## Contact
The following media sources are currently supported:
- YouTube (individual videos)
- YouTube Playlists
- Vimeo
- Dailymotion
- Soundcloud
- Livestream.com
- Twitch.tv
- Justin.tv
- Ustream
- RTMP livestreams
**Please check if the
[FAQ](https://github.com/calzoneman/sync/wiki/Frequently-Asked-Questions)
answers your question already.**
Installing
----------
For bug reports and feature requests, please open a GitHub issue. To report a
security vulnerability, or to discuss an issue with https://cytu.be itself
(unrelated to the code), please send me an email: cyzon@cytu.be
Installation instructions for specific distributions are available here: https://github.com/calzoneman/sync/wiki/Installing
Please be courteous and search through [the open and closed
issues](https://github.com/calzoneman/sync/issues?utf8=%E2%9C%93&q=is%3Aissue)
for your request before submitting a new one.
This assumes you have Node.JS installed.
I'm using v0.10, please feel free to report which versions do/do not work.
I recommend using at least v0.8.20 due to a bug in previous versions of node
that caused sketchy client connections to crash the server.
General help with the software and the website is also available on the IRC
channel at [irc.esper.net#cytube](http://webchat.esper.net/?channels=cytube)
during US daytime hours.
First install MySQL on the server. There are many online tutorials for setting up MySQL on
various operating systems.
I recommend installing phpMyAdmin so that you have a nice database administration interface.
Create a new user and database, and make sure the user has full permissions for the database.
## License
Then, follow these instructions to install CyTube:
Original source code in this repository is provided under the MIT license
(see the LICENSE file for the full text).
1. Clone this repository (`git clone https://github.com/calzoneman/sync`)
2. cd to the directory containing the source files
3. Install your distribution's `libmysqlclient` package.
3. Install dependencies: `npm install`
4. Edit `config.js` and input your database details and connection port. Optionally, configure an SMTP transport to use for sending password reset emails (see https://github.com/andris9/Nodemailer).
5. Edit `www/assets/js/iourl.js` and change the value of `IO_URL` to `yourhostname:port` where `port` is the port defined in `config.js`. Also change `WEB_URL` to `yourhostname:web_port` where `web_port` is the websocket port you defined in `config.js`
Bundled source code, such as third-party CSS and JavaScript libraries, are
provided under their respective licenses.
Running
-------
Start the server: `node server.js`
You should now be able to connect via `yourhostname:port` where `port` is
the port you defined in config.js
Feedback
--------
Please open a GitHub Issue.
License
-------
Licensed under MIT
See LICENSE for the full license text

209
acp.js Normal file
View file

@ -0,0 +1,209 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Auth = require("./auth");
var ActionLog = require("./actionlog");
module.exports = function (Server) {
return {
init: function(user) {
ActionLog.record(user.ip, user.name, "acp-init");
user.socket.on("acp-announce", function(data) {
ActionLog.record(user.ip, user.name, "acp-announce", data);
Server.announcement = data;
Server.io.sockets.emit("announcement", data);
});
user.socket.on("acp-announce-clear", function() {
ActionLog.record(user.ip, user.name, "acp-announce-clear");
Server.announcement = null;
});
user.socket.on("acp-global-ban", function(data) {
ActionLog.record(user.ip, user.name, "acp-global-ban", data.ip);
Server.db.globalBanIP(data.ip, data.note);
user.socket.emit("acp-global-banlist", Server.db.refreshGlobalBans());
});
user.socket.on("acp-global-unban", function(ip) {
ActionLog.record(user.ip, user.name, "acp-global-unban", ip);
Server.db.globalUnbanIP(ip);
user.socket.emit("acp-global-banlist", Server.db.refreshGlobalBans());
});
user.socket.emit("acp-global-banlist", Server.db.refreshGlobalBans());
user.socket.on("acp-lookup-user", function(name) {
var db = Server.db.getConnection();
if(!db) {
return;
}
var query = Server.db.createQuery(
"SELECT id,uname,global_rank,profile_image,profile_text,email FROM registrations WHERE uname LIKE ?",
["%"+name+"%"]
);
var res = db.querySync(query);
if(!res)
return;
var rows = res.fetchAllSync();
user.socket.emit("acp-userdata", rows);
});
user.socket.on("acp-lookup-channel", function (data) {
var db = Server.db.getConnection();
if(!db) {
return;
}
var query;
if(data.field === "owner") {
query = Server.db.createQuery(
"SELECT * FROM channels WHERE owner LIKE ?",
["%" + data.value + "%"]
);
} else if (data.field === "name") {
query = Server.db.createQuery(
"SELECT * FROM channels WHERE name LIKE ?",
["%" + data.value + "%"]
);
} else {
return;
}
var results = db.querySync(query);
if(!results)
return;
var rows = results.fetchAllSync();
user.socket.emit("acp-channeldata", rows);
});
user.socket.on("acp-reset-password", function(data) {
if(Auth.getGlobalRank(data.name) >= user.global_rank)
return;
try {
var hash = Server.db.generatePasswordReset(user.ip, data.name, data.email);
ActionLog.record(user.ip, user.name, "acp-reset-password", data.name);
}
catch(e) {
user.socket.emit("acp-reset-password", {
success: false,
error: e
});
return;
}
if(hash) {
user.socket.emit("acp-reset-password", {
success: true,
hash: hash
});
}
else {
user.socket.emit("acp-reset-password", {
success: false,
error: "Reset failed"
});
}
});
user.socket.on("acp-set-rank", function(data) {
if(data.rank < 1 || data.rank >= user.global_rank)
return;
if(Auth.getGlobalRank(data.name) >= user.global_rank)
return;
var db = Server.db.getConnection();
if(!db)
return;
ActionLog.record(user.ip, user.name, "acp-set-rank", data);
var query = Server.db.createQuery(
"UPDATE registrations SET global_rank=? WHERE uname=?",
[data.rank, data.name]
);
var res = db.querySync(query);
if(!res)
return;
user.socket.emit("acp-set-rank", data);
});
user.socket.on("acp-list-loaded", function() {
var chans = [];
var all = Server.channels;
for(var c in all) {
var chan = all[c];
chans.push({
name: chan.name,
title: chan.opts.pagetitle,
usercount: chan.users.length,
mediatitle: chan.playlist.current ? chan.playlist.current.media.title : "-",
is_public: chan.opts.show_public,
registered: chan.registered
});
}
user.socket.emit("acp-list-loaded", chans);
});
user.socket.on("acp-channel-unload", function(data) {
if(Server.channelLoaded(data.name)) {
var c = Server.getChannel(data.name);
if(!c)
return;
ActionLog.record(user.ip, user.name, "acp-channel-unload");
c.initialized = data.save;
c.users.forEach(function(u) {
c.kick(u, "Channel shutting down");
});
// At this point c should be unloaded
// if it's still loaded, kill it
if(Server.channelLoaded(data.name))
Server.unloadChannel(Server.getChannel(data.name));
}
});
user.socket.on("acp-actionlog-list", function () {
user.socket.emit("acp-actionlog-list",
ActionLog.getLogTypes()
);
});
user.socket.on("acp-actionlog-clear", function(data) {
ActionLog.clear(data);
ActionLog.record(user.ip, user.name, "acp-actionlog-clear", data);
});
user.socket.on("acp-actionlog-clear-one", function(data) {
ActionLog.clearOne(data);
ActionLog.record(user.ip, user.name, "acp-actionlog-clear-one", data);
});
user.socket.on("acp-view-stats", function () {
var db = Server.db.getConnection();
if(!db)
return;
var query = "SELECT * FROM stats ORDER BY time ASC";
var results = db.querySync(query);
if(results)
user.socket.emit("acp-view-stats", results.fetchAllSync());
});
}
}
}

151
actionlog.js Normal file
View file

@ -0,0 +1,151 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Database = require("./database");
var Logger = require("./logger");
exports.record = function(ip, name, action, args) {
if(typeof args === "undefined" || args === null) {
args = "";
} else {
try {
args = JSON.stringify(args);
} catch(e) {
args = "";
}
}
var db = Database.getConnection();
if(!db)
return false;
var query = Database.createQuery(
"INSERT INTO actionlog (ip, name, action, args, time) "+
"VALUES (?, ?, ?, ?, ?)",
[ip, name, action, args, Date.now()]
);
var result = db.querySync(query);
if(!result) {
Logger.errlog.log("! Failed to record action");
}
return result;
}
exports.clear = function(actions) {
var db = Database.getConnection();
if(!db)
return false;
var list = new Array(actions.length);
for(var i = 0; i < actions.length; i++)
list[i] = "?";
var query = Database.createQuery(
"DELETE FROM actionlog WHERE action IN ("+
list.join(",")+
")",
actions
);
var result = db.querySync(query);
if(!result) {
Logger.errlog.log("! Failed to clear action log");
}
return result;
}
exports.clearOne = function(e) {
var db = Database.getConnection();
if(!db)
return false;
var query = Database.createQuery(
"DELETE FROM actionlog WHERE ip=? AND time=?",
[e.ip, e.time]
);
var result = db.querySync(query);
if(!result) {
Logger.errlog.log("! Failed to clear action log");
}
return result;
}
exports.tooManyRegistrations = function (ip) {
var db = Database.getConnection();
if(!db)
return true;
var query = Database.createQuery(
"SELECT * FROM actionlog WHERE ip=? AND action='register-success'"+
"AND time > ?",
[ip, Date.now() - 48 * 3600 * 1000]
);
var results = db.querySync(query);
if(!results) {
Logger.errlog.log("! Failed to check tooManyRegistrations");
return true;
}
var rows = results.fetchAllSync();
// TODO Config value for this
return rows.length > 4;
}
exports.getLogTypes = function () {
var db = Database.getConnection();
if(!db)
return false;
var query = "SELECT DISTINCT action FROM actionlog";
var result = db.querySync(query);
if(!result) {
Logger.errlog.log("! Failed to read action log");
return [];
}
result = result.fetchAllSync();
var actions = [];
for(var i in result)
actions.push(result[i].action);
return actions;
}
exports.readLog = function (actions) {
var db = Database.getConnection();
if(!db)
return false;
var query = "SELECT * FROM actionlog";
if(actions !== undefined) {
var list = new Array(actions.length);
for(var i in actions)
list[i] = "?";
list = list.join(",");
query += Database.createQuery(
" WHERE action IN ("+list+")",
actions
);
}
var result = db.querySync(query);
if(!result) {
Logger.errlog.log("! Failed to read action log");
return [];
}
return result.fetchAllSync();
}

619
api.js Normal file
View file

@ -0,0 +1,619 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Auth = require("./auth");
var Logger = require("./logger");
var apilog = new Logger.Logger("api.log");
var ActionLog = require("./actionlog");
var fs = require("fs");
module.exports = function (Server) {
function getIP(req) {
var raw = req.connection.remoteAddress;
var forward = req.header("x-forwarded-for");
if(Server.cfg["trust-x-forward"] && forward) {
var ip = forward.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
return raw;
}
var API = function () {
}
API.prototype = {
handle: function (path, req, res) {
var parts = path.split("/");
var last = parts[parts.length - 1];
var params = {};
if(last.indexOf("?") != -1) {
parts[parts.length - 1] = last.substring(0, last.indexOf("?"));
var plist = last.substring(last.indexOf("?") + 1).split("&");
for(var i = 0; i < plist.length; i++) {
var kv = plist[i].split("=");
if(kv.length != 2) {
res.send(400);
return;
}
params[unescape(kv[0])] = unescape(kv[1]);
}
}
for(var i = 0; i < parts.length; i++) {
parts[i] = unescape(parts[i]);
}
if(parts.length != 2) {
res.send(400);
return;
}
if(parts[0] == "json") {
res.callback = params.callback || false;
if(!(parts[1] in this.jsonHandlers)) {
res.end(JSON.stringify({
error: "Unknown endpoint: " + parts[1]
}, null, 4));
return;
}
this.jsonHandlers[parts[1]](params, req, res);
}
else if(parts[0] == "plain") {
if(!(parts[1] in this.plainHandlers)) {
res.send(404);
return;
}
this.plainHandlers[parts[1]](params, req, res);
}
else {
res.send(400);
}
},
sendJSON: function (res, obj) {
var response = JSON.stringify(obj, null, 4);
if(res.callback) {
response = res.callback + "(" + response + ")";
}
var len = unescape(encodeURIComponent(response)).length;
res.setHeader("Content-Type", "application/json");
res.setHeader("Content-Length", len);
res.end(response);
},
sendPlain: function (res, str) {
if(res.callback) {
str = res.callback + "('" + str + "')";
}
var len = unescape(encodeURIComponent(str)).length;
res.setHeader("Content-Type", "text/plain");
res.setHeader("Content-Length", len);
res.end(response);
},
handleChannelData: function (params, req, res) {
var clist = params.channel || "";
clist = clist.split(",");
var data = [];
for(var j = 0; j < clist.length; j++) {
var cname = clist[j];
if(!cname.match(/^[a-zA-Z0-9-_]+$/)) {
continue;
}
var d = {
name: cname,
loaded: Server.channelLoaded(cname)
};
if(d.loaded) {
var chan = Server.getChannel(cname);
d.pagetitle = chan.opts.pagetitle;
d.media = chan.playlist.current ? chan.playlist.current.media.pack() : {};
d.usercount = chan.users.length;
d.users = [];
for(var i = 0; i < chan.users.length; i++) {
if(chan.users[i].name) {
d.users.push(chan.users[i].name);
}
}
d.chat = [];
for(var i = 0; i < chan.chatbuffer.length; i++) {
d.chat.push(chan.chatbuffer[i]);
}
}
data.push(d);
}
this.sendJSON(res, data);
},
handleChannelList: function (params, req, res) {
if(params.filter == "public") {
var all = Server.channels;
var clist = [];
for(var key in all) {
if(all[key].opts.show_public) {
clist.push(all[key].name);
}
}
this.handleChannelData({channel: clist.join(",")}, req, res);
}
var session = params.session || "";
var name = params.name || "";
var pw = params.pw || "";
var row = Auth.login(name, pw, session);
if(!row || row.global_rank < 255) {
res.send(403);
return;
}
var clist = [];
for(var key in Server.channels) {
clist.push(Server.channels[key].name);
}
this.handleChannelData({channel: clist.join(",")}, req, res);
},
handleLogin: function (params, req, res) {
var session = params.session || "";
var name = params.name || "";
var pw = params.pw || "";
if(pw == "" && session == "") {
if(!Auth.isRegistered(name)) {
this.sendJSON(res, {
success: true,
session: ""
});
return;
}
else {
this.sendJSON(res, {
success: false,
error: "That username is already taken"
});
return;
}
}
var row = Auth.login(name, pw, session);
if(row) {
if(row.global_rank >= 255)
ActionLog.record(getIP(req), name, "login-success");
this.sendJSON(res, {
success: true,
session: row.session_hash
});
}
else {
ActionLog.record(getIP(req), name, "login-failure");
this.sendJSON(res, {
error: "Invalid username/password",
success: false
});
}
},
handlePasswordChange: function (params, req, res) {
var name = params.name || "";
var oldpw = params.oldpw || "";
var newpw = params.newpw || "";
if(oldpw == "" || newpw == "") {
this.sendJSON(res, {
success: false,
error: "Old password and new password cannot be empty"
});
return;
}
var row = Auth.login(name, oldpw);
if(row) {
ActionLog.record(getIP(req), name, "password-change");
var success = Auth.setUserPassword(name, newpw);
this.sendJSON(res, {
success: success,
error: success ? "" : "Change password failed",
session: row.session_hash
});
}
else {
this.sendJSON(res, {
success: false,
error: "Invalid username/password"
});
}
},
handlePasswordReset: function (params, req, res) {
var name = params.name || "";
var email = params.email || "";
var ip = getIP(req);
var hash = false;
try {
hash = Server.db.generatePasswordReset(ip, name, email);
ActionLog.record(ip, name, "password-reset-generate", email);
}
catch(e) {
this.sendJSON(res, {
success: false,
error: e
});
return;
}
if(!Server.cfg["enable-mail"]) {
this.sendJSON(res, {
success: false,
error: "This server does not have email enabled. Contact an administrator"
});
return;
}
if(!email) {
this.sendJSON(res, {
success: false,
error: "You don't have a recovery email address set. Contact an administrator"
});
return;
}
var msg = [
"A password reset request was issued for your account `",
name,
"` on ",
Server.cfg["domain"],
". This request is valid for 24 hours. ",
"If you did not initiate this, there is no need to take action. ",
"To reset your password, copy and paste the following link into ",
"your browser: ",
Server.cfg["domain"],
"/reset.html?",
hash
].join("");
var mail = {
from: "CyTube Services <" + Server.cfg["mail-from"] + ">",
to: email,
subject: "Password reset request",
text: msg
};
var api = this;
Server.cfg["nodemailer"].sendMail(mail, function(err, response) {
if(err) {
Logger.errlog.log("Mail fail: " + err);
api.sendJSON(res, {
success: false,
error: "Email failed. Contact an admin if this persists."
});
}
else {
api.sendJSON(res, {
success: true
});
if(Server.cfg["debug"]) {
Logger.syslog.log(response);
}
}
});
},
handlePasswordRecover: function (params, req, res) {
var hash = params.hash || "";
var ip = getIP(req);
try {
var info = Server.db.recoverPassword(hash);
this.sendJSON(res, {
success: true,
name: info[0],
pw: info[1]
});
ActionLog.record(ip, info[0], "password-recover-success");
Logger.syslog.log(ip + " recovered password for " + info[0]);
return;
}
catch(e) {
ActionLog.record(ip, "", "password-recover-failure");
this.sendJSON(res, {
success: false,
error: e
});
}
},
handleProfileGet: function (params, req, res) {
var name = params.name || "";
try {
var prof = Server.db.getProfile(name);
this.sendJSON(res, {
success: true,
profile_image: prof.profile_image,
profile_text: prof.profile_text
});
}
catch(e) {
this.sendJSON(res, {
success: false,
error: e
});
}
},
handleProfileChange: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
var img = params.profile_image || "";
var text = params.profile_text || "";
var row = Auth.login(name, pw, session);
if(!row) {
this.sendJSON(res, {
success: false,
error: "Invalid login"
});
return;
}
var result = Server.db.setProfile(name, {
image: img,
text: text
});
this.sendJSON(res, {
success: result,
error: result ? "" : "Internal error. Contact an administrator"
});
var all = Server.channels;
for(var n in all) {
var chan = all[n];
for(var i = 0; i < chan.users.length; i++) {
if(chan.users[i].name.toLowerCase() == name) {
chan.users[i].profile = {
image: img,
text: text
};
chan.broadcastUserUpdate(chan.users[i]);
break;
}
}
}
},
handleEmailChange: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var email = params.email || "";
// perhaps my email regex isn't perfect, but there's no freaking way
// I'm implementing this monstrosity:
// <http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html>
if(!email.match(/^[a-z0-9_\.]+@[a-z0-9_\.]+[a-z]+$/)) {
this.sendJSON(res, {
success: false,
error: "Invalid email"
});
return;
}
if(email.match(/.*@(localhost|127\.0\.0\.1)/i)) {
this.sendJSON(res, {
success: false,
error: "Nice try, but no."
});
return;
}
if(pw == "") {
this.sendJSON(res, {
success: false,
error: "Password cannot be empty"
});
return;
}
var row = Auth.login(name, pw);
if(row) {
var success = Server.db.setUserEmail(name, email);
ActionLog.record(getIP(req), name, "email-update", email);
this.sendJSON(res, {
success: success,
error: success ? "" : "Email update failed",
session: row.session_hash
});
}
else {
this.sendJSON(res, {
success: false,
error: "Invalid username/password"
});
}
},
handleRegister: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
if(ActionLog.tooManyRegistrations(getIP(req))) {
ActionLog.record(getIP(req), name, "register-failure",
"Too many recent registrations from this IP");
this.sendJSON(res, {
success: false,
error: "Your IP address has registered several accounts in "+
"the past 48 hours. Please wait a while or ask an "+
"administrator for assistance."
});
return;
}
if(pw == "") {
this.sendJSON(res, {
success: false,
error: "You must provide a password"
});
return;
}
else if(Auth.isRegistered(name)) {
ActionLog.record(getIP(req), name, "register-failure",
"Name taken");
this.sendJSON(res, {
success: false,
error: "That username is already taken"
});
return false;
}
else if(!Auth.validateName(name)) {
ActionLog.record(getIP(req), name, "register-failure",
"Invalid name");
this.sendJSON(res, {
success: false,
error: "Invalid username. Usernames must be 1-20 characters long and consist only of alphanumeric characters and underscores"
});
}
else {
var session = Auth.register(name, pw);
if(session) {
ActionLog.record(getIP(req), name, "register-success");
Logger.syslog.log(getIP(req) + " registered " + name);
this.sendJSON(res, {
success: true,
session: session
});
}
else {
this.sendJSON(res, {
success: false,
error: "Registration error. Contact an admin for assistance."
});
}
}
},
handleListUserChannels: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
var row = Auth.login(name, pw, session);
if(!row) {
this.sendJSON(res, {
success: false,
error: "Invalid login"
});
return;
}
var channels = Server.db.listUserChannels(name);
this.sendJSON(res, {
success: true,
channels: channels
});
},
handleAdmReports: function (params, req, res) {
this.sendJSON(res, {
error: "Not implemented"
});
},
handleReadActionLog: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
var types = params.actions || "";
var row = Auth.login(name, pw, session);
if(!row || row.global_rank < 255) {
res.send(403);
return;
}
var actiontypes = types.split(",");
var actions = ActionLog.readLog(actiontypes);
this.sendJSON(res, actions);
},
// Helper function
pipeLast: function (res, file, len) {
fs.stat(file, function(err, data) {
if(err) {
res.send(500);
return;
}
var start = data.size - len;
if(start < 0) {
start = 0;
}
var end = data.size - 1;
fs.createReadStream(file, {start: start, end: end}).pipe(res);
});
},
handleReadLog: function (params, req, res) {
var name = params.name || "";
var pw = params.pw || "";
var session = params.session || "";
var row = Auth.login(name, pw, session);
if(!row || row.global_rank < 255) {
res.send(403);
return;
}
res.setHeader("Access-Control-Allow-Origin", "*");
var type = params.type || "";
if(type == "sys") {
this.pipeLast(res, "sys.log", 1024*1024);
}
else if(type == "err") {
this.pipeLast(res, "error.log", 1024*1024);
}
else if(type == "channel") {
var chan = params.channel || "";
fs.exists("chanlogs/" + chan + ".log", function(exists) {
if(exists) {
this.pipeLast(res, "chanlogs/" + chan + ".log", 1024*1024);
}
else {
res.send(404);
}
}.bind(this));
}
else {
res.send(400);
}
}
};
var api = new API();
api.plainHandlers = {
"readlog" : api.handleReadLog.bind(api)
};
api.jsonHandlers = {
"channeldata" : api.handleChannelData.bind(api),
"listloaded" : api.handleChannelList.bind(api),
"login" : api.handleLogin.bind(api),
"register" : api.handleRegister.bind(api),
"changepass" : api.handlePasswordChange.bind(api),
"resetpass" : api.handlePasswordReset.bind(api),
"recoverpw" : api.handlePasswordRecover.bind(api),
"setprofile" : api.handleProfileChange.bind(api),
"getprofile" : api.handleProfileGet.bind(api),
"listuserchannels": api.handleListUserChannels.bind(api),
"setemail" : api.handleEmailChange.bind(api),
"admreports" : api.handleAdmReports.bind(api),
"readactionlog" : api.handleReadActionLog.bind(api)
};
return api;
}

226
auth.js Normal file
View file

@ -0,0 +1,226 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var mysql = require("mysql-libmysqlclient");
var Database = require("./database.js");
var bcrypt = require("bcrypt");
var hashlib = require("node_hash");
var Logger = require("./logger.js");
// Check if a name is taken
exports.isRegistered = function(name) {
var db = Database.getConnection();
if(!db) {
throw "Database failure";
}
var query = Database.createQuery(
"SELECT * FROM `registrations` WHERE uname=?",
[name]
);
var results = db.querySync(query);
if(!results) {
return true;
}
var rows = results.fetchAllSync();
return rows.length > 0;
}
// Check if a name is valid
// Valid names are 1-20 characters, alphanumeric and underscores
exports.validateName = function(name) {
if(name.length > 20)
return false;
const VALID_REGEX = /^[a-zA-Z0-9_]+$/;
return name.match(VALID_REGEX) != null;
}
// Try to register a new account
exports.register = function(name, pw) {
if(!exports.validateName(name))
return false;
if(exports.isRegistered(name))
return false;
var db = Database.getConnection();
if(!db) {
return false;
}
var hash = bcrypt.hashSync(pw, 10);
var query = Database.createQuery(
["INSERT INTO `registrations` VALUES ",
"(NULL, ?, ?, 1, '', 0, '', '', '')"].join(""),
[name, hash]
);
var results = db.querySync(query);
if(results) {
return exports.createSession(name);
}
return false;
}
exports.login = function(name, pw, session) {
if(session) {
var res = exports.loginSession(name, session);
if(res) {
return res;
}
else if(!pw) {
return false;
}
}
var row = exports.loginPassword(name, pw);
if(row) {
var hash = exports.createSession(name);
row.session_hash = hash;
return row;
}
}
// Try to login
exports.loginPassword = function(name, pw) {
var db = Database.getConnection();
if(!db) {
throw "Database failure";
}
var query = Database.createQuery(
"SELECT * FROM `registrations` WHERE uname=?",
[name]
);
var results = db.querySync(query);
if(!results) {
return false;
}
var rows = results.fetchAllSync();
if(rows.length > 0) {
try {
if(bcrypt.compareSync(pw, rows[0].pw)) {
return rows[0];
}
else {
// Check if the sha256 is in the database
// If so, migrate to bcrypt
var sha256 = hashlib.sha256(pw);
if(sha256 == rows[0].pw) {
var newhash = bcrypt.hashSync(pw, 10);
var query = Database.createQuery(
["UPDATE `registrations` SET pw=?",
"WHERE uname=?"].join(""),
[newhash, name]
);
var results = db.querySync(query);
if(!results) {
Logger.errlog.log("Failed to migrate password! user=" + name);
return false;
}
return rows[0];
}
return false;
}
}
catch(e) {
Logger.errlog.log("Auth.login fail");
Logger.errlog.log(e);
}
}
return false;
}
exports.createSession = function(name) {
var salt = sessionSalt();
var hash = hashlib.sha256(salt + name);
var db = Database.getConnection();
if(!db) {
throw "Database failure";
}
var query = Database.createQuery(
["UPDATE `registrations` SET ",
"`session_hash`=?,",
"`expire`=? ",
"WHERE uname=?"].join(""),
[hash, Date.now() + 604800000, name]
);
var results = db.querySync(query);
return results ? hash : false;
}
exports.loginSession = function(name, hash) {
var db = Database.getConnection();
if(!db) {
throw "Database failure";
}
var query = Database.createQuery(
"SELECT * FROM `registrations` WHERE `uname`=?",
[name]
);
var results = db.querySync(query);
if(!results) {
return false;
}
var rows = results.fetchAllSync();
if(rows.length != 1) {
return false;
}
var dbhash = rows[0].session_hash;
if(hash != dbhash) {
return false;
}
var timeout = rows[0].expire;
if(timeout < new Date().getTime()) {
return false;
}
return rows[0];
}
function sessionSalt() {
var chars = "abcdefgihjklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "0123456789!@#$%^&*_+=~";
var salt = [];
for(var i = 0; i < 32; i++) {
salt.push(chars[parseInt(Math.random()*chars.length)]);
}
return salt.join('');
}
exports.setUserPassword = function(name, pw) {
var db = Database.getConnection();
if(!db) {
return false;
}
var hash = bcrypt.hashSync(pw, 10);
var query = Database.createQuery(
"UPDATE `registrations` SET `pw`=? WHERE `uname`=?",
[hash, name]
);
var result = db.querySync(query);
return result;
}
exports.getGlobalRank = function(name) {
var db = Database.getConnection();
if(!db) {
return false;
}
var query = Database.createQuery(
"SELECT * FROM `registrations` WHERE `uname`=?",
[name]
);
var results = db.querySync(query);
if(!results) {
return 0;
}
var rows = results.fetchAllSync();
if(rows.length > 0) {
return rows[0].global_rank;
}
return 0;
}

View file

@ -1,176 +0,0 @@
#!/usr/bin/env node
const Config = require('../lib/config');
Config.load('config.yaml');
if (!Config.get('service-socket.enabled')){
console.error('The Service Socket is not enabled.');
process.exit(1);
}
const net = require('net');
const path = require('path');
const readline = require('node:readline/promises');
const socketPath = path.resolve(__dirname, '..', Config.get('service-socket.socket'));
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function doCommand(params) {
return new Promise((resolve, reject) => {
const client = net.createConnection(socketPath);
client.on('connect', () => {
client.write(JSON.stringify(params) + '\n');
});
client.on('data', data => {
client.end();
resolve(JSON.parse(data));
});
client.on('error', error => {
reject(error);
});
});
}
let commands = [
{
command: 'ban-channel',
handler: async args => {
if (args.length !== 3) {
console.log('Usage: ban-channel <name> <externalReason> <internalReason>');
process.exit(1);
}
let [name, externalReason, internalReason] = args;
let answer = await rl.question(`Ban ${name} with external reason "${externalReason}" and internal reason "${internalReason}"? `);
if (!/^[yY]$/.test(answer)) {
console.log('Aborted.');
process.exit(1);
}
let res = await doCommand({
command: 'ban-channel',
name,
externalReason,
internalReason
});
switch (res.status) {
case 'error':
console.log('Error:', res.error);
process.exit(1);
break;
case 'success':
console.log('Ban succeeded.');
process.exit(0);
break;
default:
console.log(`Unknown result: ${res.status}`);
process.exit(1);
break;
}
}
},
{
command: 'unban-channel',
handler: async args => {
if (args.length !== 1) {
console.log('Usage: unban-channel <name>');
process.exit(1);
}
let [name] = args;
let answer = await rl.question(`Unban ${name}? `);
if (!/^[yY]$/.test(answer)) {
console.log('Aborted.');
process.exit(1);
}
let res = await doCommand({
command: 'unban-channel',
name
});
switch (res.status) {
case 'error':
console.log('Error:', res.error);
process.exit(1);
break;
case 'success':
console.log('Unban succeeded.');
process.exit(0);
break;
default:
console.log(`Unknown result: ${res.status}`);
process.exit(1);
break;
}
}
},
{
command: 'show-banned-channel',
handler: async args => {
if (args.length !== 1) {
console.log('Usage: show-banned-channel <name>');
process.exit(1);
}
let [name] = args;
let res = await doCommand({
command: 'show-banned-channel',
name
});
switch (res.status) {
case 'error':
console.log('Error:', res.error);
process.exit(1);
break;
case 'success':
if (res.ban != null) {
console.log(`Channel: ${name}`);
console.log(`Ban issued: ${res.ban.createdAt}`);
console.log(`Banned by: ${res.ban.bannedBy}`);
console.log(`External reason:\n${res.ban.externalReason}`);
console.log(`Internal reason:\n${res.ban.internalReason}`);
} else {
console.log(`Channel ${name} is not banned.`);
}
process.exit(0);
break;
default:
console.log(`Unknown result: ${res.status}`);
process.exit(1);
break;
}
}
}
];
let found = false;
commands.forEach(cmd => {
if (cmd.command === process.argv[2]) {
found = true;
cmd.handler(process.argv.slice(3)).then(() => {
process.exit(0);
}).catch(error => {
console.log('Error in command:', error.stack);
});
}
});
if (!found) {
console.log('Available commands:');
commands.forEach(cmd => {
console.log(` * ${cmd.command}`);
});
process.exit(1);
}

View file

@ -1,52 +0,0 @@
#!/usr/bin/env node
var coffee = require('coffeescript');
var fs = require('fs');
var path = require('path');
var order = [
'base.coffee',
'dailymotion.coffee',
'niconico.coffee',
'peertube.coffee',
'soundcloud.coffee',
'twitch.coffee',
'vimeo.coffee',
'youtube.coffee',
// playerjs-based players
'playerjs.coffee',
'iframechild.coffee',
'odysee.coffee',
'whepplayer.coffee',
'streamable.coffee',
// iframe embed-based players
'embed.coffee',
'custom-embed.coffee',
'livestream.com.coffee',
'twitchclip.coffee',
// video.js-based players
'videojs.coffee',
'gdrive-player.coffee',
'hls.coffee',
'raw-file.coffee',
'rtmp.coffee',
// mediaUpdate handler
'update.coffee'
];
var buffer = '';
order.forEach(function (file) {
buffer += fs.readFileSync(
path.join(__dirname, '..', 'player', file)
) + '\n';
});
fs.writeFileSync(
path.join(__dirname, '..', 'www', 'js', 'player.js'),
coffee.compile(buffer)
);

2026
channel.js Normal file

File diff suppressed because it is too large Load diff

233
chatcommand.js Normal file
View file

@ -0,0 +1,233 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Rank = require("./rank.js");
var Poll = require("./poll.js").Poll;
var Logger = require("./logger.js");
function handle(chan, user, msg, data) {
if(msg.indexOf("/me ") == 0)
chan.sendMessage(user.name, msg.substring(4), "action", data);
else if(msg.indexOf("/sp ") == 0)
chan.sendMessage(user.name, msg.substring(4), "spoiler", data);
else if(msg.indexOf("/say ") == 0) {
if(Rank.hasPermission(user, "shout") || chan.leader == user) {
chan.sendMessage(user.name, msg.substring(5), "shout", data);
}
}
else if(msg.indexOf("/afk") == 0) {
user.setAFK(!user.meta.afk);
}
else if(msg.indexOf("/m ") == 0) {
if(user.rank >= Rank.Moderator) {
chan.chainMessage(user, msg.substring(3), {modflair: user.rank})
}
}
else if(msg.indexOf("/a ") == 0) {
if(user.rank >= Rank.Siteadmin) {
var flair = {
superadminflair: {
labelclass: "label-important",
icon: "icon-globe"
}
};
var args = msg.substring(3).split(" ");
var cargs = [];
for(var i = 0; i < args.length; i++) {
var a = args[i];
if(a.indexOf("!icon-") == 0)
flair.superadminflair.icon = a.substring(1);
else if(a.indexOf("!label-") == 0)
flair.superadminflair.labelclass = a.substring(1);
else {
cargs.push(a);
}
}
chan.chainMessage(user, cargs.join(" "), flair);
}
}
else if(msg.indexOf("/mute ") == 0) {
handleMute(chan, user, msg.substring(6).split(" "));
}
else if(msg.indexOf("/unmute ") == 0) {
handleUnmute(chan, user, msg.substring(8).split(" "));
}
else if(msg.indexOf("/kick ") == 0) {
handleKick(chan, user, msg.substring(6).split(" "));
}
else if(msg.indexOf("/ban ") == 0) {
handleBan(chan, user, msg.substring(5).split(" "));
}
else if(msg.indexOf("/ipban ") == 0) {
handleIPBan(chan, user, msg.substring(7).split(" "));
}
else if(msg.indexOf("/unban ") == 0) {
handleUnban(chan, user, msg.substring(7).split(" "));
}
else if(msg.indexOf("/poll ") == 0) {
handlePoll(chan, user, msg.substring(6));
}
else if(msg.indexOf("/d") == 0 && msg.length > 2 &&
msg[2].match(/[-0-9 ]/)) {
if(msg[2] == "-") {
if(msg.length == 3)
return;
if(!msg[3].match(/[0-9]/))
return;
}
handleDrink(chan, user, msg.substring(2), data);
}
else if(msg.indexOf("/clear") == 0) {
handleClear(chan, user);
}
}
function handleMute(chan, user, args) {
if(chan.hasPermission(user, "mute") && args.length > 0) {
args[0] = args[0].toLowerCase();
var person = false;
for(var i = 0; i < chan.users.length; i++) {
if(chan.users[i].name.toLowerCase() == args[0]) {
person = chan.users[i];
break;
}
}
if(person) {
if(person.rank >= user.rank) {
user.socket.emit("errorMsg", {
msg: "You don't have permission to mute that person."
});
return;
}
person.meta.icon = "icon-volume-off";
person.muted = true;
chan.broadcastUserUpdate(person);
chan.logger.log("*** " + user.name + " muted " + args[0]);
}
}
}
function handleUnmute(chan, user, args) {
if(chan.hasPermission(user, "mute") && args.length > 0) {
args[0] = args[0].toLowerCase();
var person = false;
for(var i = 0; i < chan.users.length; i++) {
if(chan.users[i].name.toLowerCase() == args[0]) {
person = chan.users[i];
break;
}
}
if(person) {
if(person.rank >= user.rank) {
user.socket.emit("errorMsg", {
msg: "You don't have permission to unmute that person."
});
return;
}
person.meta.icon = false;
person.muted = false;
chan.broadcastUserUpdate(person);
chan.logger.log("*** " + user.name + " unmuted " + args[0]);
}
}
}
function handleKick(chan, user, args) {
if(chan.hasPermission(user, "kick") && args.length > 0) {
args[0] = args[0].toLowerCase();
var kickee;
for(var i = 0; i < chan.users.length; i++) {
if(chan.users[i].name.toLowerCase() == args[0] &&
chan.getRank(chan.users[i].name) < user.rank) {
kickee = chan.users[i];
break;
}
}
if(kickee) {
chan.logger.log("*** " + user.name + " kicked " + args[0]);
args[0] = "";
var reason = args.join(" ");
chan.kick(kickee, reason);
}
}
}
function handleIPBan(chan, user, args) {
chan.tryIPBan(user, args[0], args[1]);
// Ban the name too for good measure
chan.tryNameBan(user, args[0]);
}
function handleBan(chan, user, args) {
chan.tryNameBan(user, args[0]);
}
function handleUnban(chan, user, args) {
if(chan.hasPermission(user, "ban") && args.length > 0) {
chan.logger.log("*** " + user.name + " unbanned " + args[0]);
if(args[0].match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/)) {
chan.unbanIP(user, args[0]);
}
else {
chan.unbanName(user, args[0]);
}
}
}
function handlePoll(chan, user, msg) {
if(chan.hasPermission(user, "pollctl")) {
var args = msg.split(",");
var title = args[0];
args.splice(0, 1);
var poll = new Poll(user.name, title, args);
chan.poll = poll;
chan.broadcastPoll();
chan.logger.log("*** " + user.name + " Opened Poll: '" + poll.title + "'");
}
}
function handleDrink(chan, user, msg, data) {
if(!chan.hasPermission(user, "drink")) {
return;
}
var count = msg.split(" ")[0];
msg = msg.substring(count.length + 1);
if(count == "")
count = 1;
else
count = parseInt(count);
chan.drinks += count;
chan.broadcastDrinks();
if(count < 0 && msg.trim() == "") {
return;
}
msg = msg + " drink!";
if(count != 1)
msg += " (x" + count + ")";
chan.sendMessage(user.name, msg, "drink", data);
}
function handleClear(chan, user) {
if(user.rank < Rank.Moderator) {
return;
}
chan.chatbuffer = [];
chan.sendAll("clearchat");
}
exports.handle = handle;

View file

@ -1,15 +0,0 @@
# Configuration for proxying images to a camo (or camo-compatible) proxy server.
# To use, copy to conf/camo.toml.
# More info on camo: https://github.com/atmos/camo
[camo]
enabled = true
server = 'https://my-camo-server'
# The key must match the `CAMO_KEY` environment variable passed to the camo server.
key = 'ABCDEFGH'
# Bypass the proxy for domains you trust that already support HTTPS and won't be harmful to users.
whitelisted-domains = [
'i.imgur.com',
'i.4cdn.org'
]
# Whether to use URL encoding ("url") or hex encoding ("hex") for the target URL.
encoding = 'url'

View file

@ -1,9 +0,0 @@
[hcaptcha]
# Site key from hCaptcha. The value here by default is the dummy test key for local testing
site-key = "10000000-ffff-ffff-ffff-000000000001"
# Secret key from hCaptcha. The value here by default is the dummy test key for local testing
secret = "0x0000000000000000000000000000000000000000"
[register]
# Whether to require a captcha for registration
enabled = true

View file

@ -1,66 +0,0 @@
# SMTP configuration for sending mail
[smtp]
host = 'smtp.gmail.com'
port = 465
secure = true
user = 'some-user@example.com'
password = 'secretpassword'
# Email configuration for password reset emails
# Be sure to update both html-template AND text-template
# nodemailer will send both and the email client will render whichever one is supported
[password-reset]
enabled = true
# Template to use for HTML-formatted emails
# $user$ will be replaced by the username for which the reset was requested
# $url$ will be replaced by the password reset confirmation link
html-template = """
Hi $user$,<br>
<br>
A password reset was requested for your account on CHANGE ME. You can complete the reset by opening the following link in your browser: <a href="$url$">$url$</a><br>
<br>
This link will expire in 24 hours.<br>
<br>
This email address is not monitored for replies. For assistance with password resets, please <a href="http://example.com/contact">contact an administrator</a>.
"""
# Template to use for plaintext emails
# Same substitutions as the HTML template
text-template = """
Hi $user$,
A password reset was requested for your account on CHANGE ME. You can complete the reset by opening the following link in your browser: $url$
This link will expire in 24 hours.
This email address is not monitored for replies. For assistance with password resets, please contact an administrator. See http://example.com/contact for contact information.
"""
from = "Example Website <website@example.com>"
subject = "Password reset request"
# Email configuration for account deletion request notifications
[delete-account]
enabled = true
html-template = """
Hi $user$,
<br>
<br>
Account deletion was requested for your account on CHANGE ME. Your account will be automatically deleted in 7 days without any further action from you.
<br>
<br>
This email address is not monitored for replies. For assistance, please <a href="http://example.com/contact">contact an administrator</a>.
"""
text-template = """
Hi $user$,
Account deletion was requested for your account on CHANGE ME. Your account will be automatically deleted in 7 days without any further action from you.
This email address is not monitored for replies. For assistance, please contact an administrator. See http://example.com/contact for contact information.
"""
from = "Example Website <website@example.com>"
subject = "Account deletion request"

View file

@ -1,14 +0,0 @@
# Configuration for binding an HTTP server to export prometheus metrics.
# See https://prometheus.io/ and https://github.com/siimon/prom-client
# for more details.
[prometheus]
enabled = true
# Host, port to bind. This is separate from the main CyTube HTTP server
# because it may be desirable to bind a different IP/port for monitoring
# purposes. Default: localhost port 19820 (arbitrary port chosen not to
# conflict with existing prometheus exporters).
host = '127.0.0.1'
port = 19820
# Request path to serve metrics. All other paths are rejected with
# 400 Bad Request.
path = '/metrics'

99
config.js Normal file
View file

@ -0,0 +1,99 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var fs = require("fs");
var Logger = require("./logger");
var nodemailer = require("nodemailer");
var defaults = {
"mysql-server" : "localhost",
"mysql-db" : "cytube",
"mysql-user" : "cytube",
"mysql-pw" : "supersecretpass",
"express-host" : "0.0.0.0",
"asset-cache-ttl" : 0,
"web-port" : 8080,
"io-port" : 1337,
"ip-connection-limit" : 10,
"guest-login-delay" : 60,
"trust-x-forward" : false,
"enable-mail" : false,
"mail-transport" : "SMTP",
"mail-config" : {
"service" : "Gmail",
"auth" : {
"user" : "some.user@gmail.com",
"pass" : "supersecretpassword"
}
},
"mail-from" : "some.user@gmail.com",
"domain" : "http://localhost",
"ytv3apikey" : "",
"enable-ytv3" : false,
"ytv2devkey" : ""
}
function save(cfg, file) {
var x = {};
for(var k in cfg) {
if(k !== "nodemailer")
x[k] = cfg[k];
}
fs.writeFile(file, JSON.stringify(x, null, 4), function (err) {
if(err) {
Logger.errlog.log("Failed to save config");
Logger.errlog.log(err);
}
});
}
exports.load = function (Server, file, callback) {
var cfg = {};
for(var k in defaults)
cfg[k] = defaults[k];
fs.readFile(file, function (err, data) {
if(err) {
if(err.code == "ENOENT") {
Logger.syslog.log("Config file not found, generating default");
Logger.syslog.log("Edit cfg.json to configure");
data = "{}";
}
else {
Logger.errlog.log("Config load failed");
Logger.errlog.log(err);
return;
}
}
try {
data = JSON.parse(data + "");
} catch(e) {
Logger.errlog.log("Config JSON is invalid: ");
Logger.errlog.log(e);
return;
}
for(var k in data)
cfg[k] = data[k];
if(cfg["enable-mail"]) {
cfg["nodemailer"] = nodemailer.createTransport(
cfg["mail-transport"],
cfg["mail-config"]
);
}
save(cfg, file);
Server.cfg = cfg;
callback();
});
}

View file

@ -1,228 +0,0 @@
# MySQL server details
# server: domain, IP or unix socket path of MySQL server. If a unix socket, it be like so `unix:/path/to/sock.sock`
# database: a MySQL database that the user specified has read/write access to
# user: username to authenticate as
# password: password for user
mysql:
server: 'mysql'
port: 3306
database: 'cytube3'
user: 'cytube3'
password: 'strong-password-here'
pool-size: 10
# Define IPs/ports to listen on
# Each entry MUST define ip and port (ip can be '' to bind all available addresses)
# Each entry should set http, https, and/or io to true to listen for the corresponding
# service on that port. http/io and https/io can be combined, but if http and https
# are both specified, only https will be bound to that port.
#
# If you don't specify a url, the url io.domain:port or https.domain:port will be assumed
# for non-ssl and ssl websockets, respectively. You can override this by specifying the
# url for a websocket listener.
listen:
# Default HTTP server - default interface, port 8080
- ip: ''
port: 8080
http: true
# Uncomment below to enable HTTPS/SSL websockets
# Note that you must also set https->enabled = true in the https definition
# - ip: ''
# port: 8443
# https: true
# io: true
# Default Socket.IO server - default interface, port 1337
- ip: ''
port: 1337
io: true
# Example of how to bind an extra port to HTTP and Socket.IO
# - ip: ''
# port: 8081
# http: true
# io: true
# url: 'http://my-other-thing.site.com:8081'
# HTTP server details
http:
# Even though you may specify multiple ports to listen on for HTTP above,
# one port must be specified as default for the purposes of generating
# links with the appropriate port
default-port: 8080
# Specifies the root domain for cookies. If you have multiple domains
# e.g. a.example.com and b.example.com, the root domain is example.com
root-domain: 'localhost'
# Specify alternate domains/hosts that are allowed to set the login cookie
# Leave out the http://
alt-domains:
- '127.0.0.1'
# Use express-minify to minify CSS and Javascript
minify: false
# Max-Age for caching. Value should be an integer in milliseconds or a string accepted by
# the `ms` module. Set to 0 to disable caching.
max-age: '7d'
# Set to false to disable gzip compression
gzip: true
# Customize the threshold byte size for applying gzip
gzip-threshold: 1024
# Secret used for signed cookies. Can be anything, but make it unique and hard to guess
cookie-secret: 'change-me'
index:
# Maximum number of channels to display on the index page public channel list
max-entries: 50
# Configure trusted proxy addresses to map X-Forwarded-For to the client IP.
# See also: https://github.com/jshttp/proxy-addr
trust-proxies: ['loopback']
# HTTPS server details
https:
enabled: false
# Even though you may specify multiple ports to listen on for HTTPS above,
# one port must be specified as default for the purposes of generating
# links with the appropriate port
default-port: 8443
domain: 'https://localhost'
keyfile: 'localhost.key'
passphrase: ''
certfile: 'localhost.cert'
cafile: ''
ciphers: 'HIGH:!DSS:!aNULL@STRENGTH'
# Page template values
# title goes in the upper left corner, description goes in a <meta> tag
html-template:
title: 'Sync'
description: 'Free, open source synchtube'
# Socket.IO server details
io:
# In most cases this will be the same as the http.domain.
# However, if your HTTP traffic is going through a proxy (e.g. cloudflare)
# you will want to set up a passthrough domain for socket.io.
# If the root of this domain is not the same as the root of your HTTP domain
# (or HTTPS if SSL is enabled), logins won't work.
domain: 'http://localhost'
# Even though you may specify multiple ports to listen on for HTTP above,
# one port must be specified as default for the purposes of generating
# links with the appropriate port
default-port: 1337
# limit the number of concurrent socket connections per IP address
ip-connection-limit: 10
cors:
# Additional origins to allow socket connections from (io.domain and
# https.domain are included implicitly).
allowed-origins: []
# YouTube v3 API key
# 1. Go to https://console.developers.google.com/, create a new "project" (or choose an existing one)
# 2. Make sure the YouTube Data v3 API is "enabled" for your project: https://console.developers.google.com/apis/library/youtube.googleapis.com
# 3. Go to "Credentials" on the sidebar of https://console.developers.google.com/, click "Create credentials" and choose type "API key"
# 4. Optionally restrict the key for security, or just copy the key.
# 5. Test your key (may take a few minutes to become active):
#
# $ export YOUTUBE_API_KEY="your key here"
# $ curl "https://www.googleapis.com/youtube/v3/search?key=$YOUTUBE_API_KEY&part=id&maxResults=1&q=test+video&type=video"
youtube-v3-key: ''
# Limit for the number of channels a user can register
max-channels-per-user: 5
# Limit for the number of accounts an IP address can register
max-accounts-per-ip: 5
# Minimum number of seconds between guest logins from the same IP
guest-login-delay: 60
# Maximum character length of a chat message, capped at 1000 characters
max-chat-message-length: 320
# Allows you to customize the path divider. The /r/ in http://localhost/r/yourchannel
# Acceptable characters are a-z A-Z 0-9 _ and -
channel-path: 'r'
# Allows you to blacklist certain channels. Users will be automatically kicked
# upon trying to join one.
channel-blacklist: []
# Minutes between saving channel state to disk
channel-save-interval: 5
# Configure periodic clearing of old alias data
aliases:
# Interval (in milliseconds) between subsequent runs of clearing
purge-interval: 3600000
# Maximum age of an alias (in milliseconds) - default 1 month
max-age: 2592000000
# Workaround for Vimeo blocking my domain
vimeo-workaround: false
# Regular expressions for defining reserved user and channel names and page titles
# The list of regular expressions will be joined with an OR, and compared without
# case sensitivity.
#
# Default: reserve any name containing "admin[istrator]" or "owner" as a word
# but only if it is separated by a dash or underscore (e.g. dadmin is not reserved
# but d-admin is)
reserved-names:
usernames:
- '^(.*?[-_])?admin(istrator)?([-_].*)?$'
- '^(.*?[-_])?owner([-_].*)?$'
channels:
- '^(.*?[-_])?admin(istrator)?([-_].*)?$'
- '^(.*?[-_])?owner([-_].*)?$'
pagetitles: []
# Provide a contact list for the /contact page
# Example:
# contacts:
# - name: 'my_name'
# title: 'administrator
# email: 'me@my.site'
contacts: []
playlist:
max-items: 4000
# How often (in seconds), mediaUpdate packets are broadcast to clients
update-interval: 5
# If set to true, when the ipThrottle and lastguestlogin rate limiters are cleared
# periodically, the garbage collector will be invoked immediately.
# The server must be invoked with node --expose-gc index.js for this to have any effect.
aggressive-gc: false
# If you have ffmpeg installed, you can query metadata from raw files, allowing
# server-synched raw file playback. This requires the following:
# * ffmpeg must be installed on the server
ffmpeg:
enabled: false
# Executable name for ffprobe if it is not "ffprobe". On Debian and Ubuntu (on which
# libav is used rather than ffmpeg proper), this is "avprobe"
ffprobe-exec: 'ffprobe'
link-domain-blacklist: []
# Drop root if started as root!!
setuid:
enabled: false
group: 'users'
user: 'user'
# how long to wait in ms before changing uid/gid
timeout: 15
# Allows for external services to access the system commandline
# Useful for setups where stdin isn't available such as when using PM2
service-socket:
enabled: false
socket: 'service.sock'
# Twitch Client ID for the data API (used for VOD lookups)
# https://github.com/justintv/Twitch-API/blob/master/authentication.md#developer-setup
twitch-client-id: null
poll:
max-options: 50
calendar-sync:
enabled: false
# 32-byte key encoded as base64. Prefer setting via env CALENDAR_SYNC_ENCRYPTION_KEY.
encryption-key: ''
google:
client-id: ''
client-secret: ''
# Must exactly match Google OAuth redirect URI
# Example: https://your-domain/api/v1/integrations/google/callback
redirect-uri: ''

17
customembed.js Normal file
View file

@ -0,0 +1,17 @@
const allowed = ["iframe", "object", "param", "embed"];
const tag_re = /<\s*\/?\s*([a-z]+)(\s*([a-z]+)\s*=\s*('[^']*'|"[^"]*"|[^"'>]*))*\s*>/ig;
function filter(str) {
str = str.replace(tag_re, function (match, tag) {
if(!~allowed.indexOf(tag.toLowerCase())) {
return match.replace("<", "&lt;").replace(">", "&gt;");
}
return match;
});
str = str.replace(/(\bon\w*\s*=\s*('[^']*'|"[^"]"|[^\s><]*))/ig, function () {
return "";
});
return str;
}
exports.filter = filter;

1084
database.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,35 +0,0 @@
version: "3.7"
services:
sync:
build: .
depends_on:
mysql:
condition: service_healthy
ports:
- "8080:8080"
- "1337:1337"
- "8443:8443"
volumes:
- "./templates/head.pug:/app/templates/head.pug"
- "./favicon.ico:/app/www/favicon.ico"
- "./config.yaml:/app/config.yaml"
mysql:
image: docker.io/library/mariadb:latest
healthcheck:
test: ["CMD", "mariadb-admin","ping","-h","localhost", "-u", "root", "--password=sync"]
interval: 5s
timeout: 3s
retries: 100
environment:
- MARIADB_AUTO_UPGRADE=1
- MARIADB_ROOT_PASSWORD=sync
- MARIADB_DATABASE=cytube3
- MARIADB_USER=cytube3
- MARIADB_PASSWORD=strong-password-here
volumes:
# This will create and mount the mysql files in the same folder as the docker-compose.yml file.
# You can change this to be anywhere.
# This will provide data persistence to your MariaDB database.
- "./mysql:/var/lib/mysql"
# If you are using a reverse proxy please do not forget to add the network here as well.
# Refer to the Readme for more information regarding using a Reverse Proxy.

View file

@ -1,20 +0,0 @@
## Registering an Account ##
To register an account, click the Account dropdown on the top bar, then click Register. This option will only appear if you are not already logged in. When choosing a username, make sure it meets the following requirements:
* Must be 1-20 characters long
* May only contain the letters 'A' through 'Z' (upper or lowercase), the digits '0' through '9', hyphens '-', and underscores '_'
Be sure to pick a strong password that is not easy to guess and is not the same as your accounts on other websites. Entering an email address is optional, and will allow you to recover your account if you ever forget your password.
## Changing your Password or Email Address ##
On the top bar of the website, click Account, then "Change Password/Email". You must provide your current password in order to change either of these. You can leave the email address box blank if you wish to remove the email address from your account (note that this means you will no longer be able to receive password reset emails).
## Recovering an Account If You Lost the Password ##
From the login page, click "Forgot password?" You will be prompted to enter your username and email address. The email address must match the one associated with your account. If you have not added an email address to your account, you cannot reset your password automatically and will need to contact an administrator for help. Otherwise, you will receive an email with a link to reset your password.
## Account Profile ##
Each CyTube account can set a profile photo and short description. On the top bar, click Account, then Profile. You can then enter the URL of a profile image, and enter a short text blurb that will be displayed when users hover over your name in the chat username list. Note that this is publicly visible to anyone, so don't use a private photo or include private information in your description.

View file

@ -1,570 +0,0 @@
# Bot API
Bots connect to a channel in two ways:
- **WebSocket** (socket.io) — real-time events: chat, user list, playlist changes, media updates
- **REST** (`/api/v1/...`) — commands: queue/delete/shuffle/clear playlist, manage emotes, read/write settings, kick/ban users
Chat can only be sent and received over the WebSocket. The REST API has no chat endpoint.
---
## Ranks
| Name | Value |
|-----------|-------|
| Moderator | 2 |
| Admin | 3 |
| Owner | 4 |
| Creator | 5 |
A bot's rank is capped at the rank of the user who issued its token. Every REST endpoint that modifies state has a minimum rank requirement listed in its description.
---
## Issuing a token
Tokens are issued in the channel settings modal on the **Bots** tab. You need at least moderator rank (2) to see this tab.
Fill in a name (120 alphanumeric, `-`, `_` characters), choose a rank, and click **Issue Token**. The token is shown **once** — copy it immediately. It looks like:
```
cbt_a3f8e2...64 hex characters...
```
To revoke a token, click **Revoke** next to it in the table. Any live WebSocket connections using that token are disconnected immediately.
---
## WebSocket connection
The bot authenticates by passing the token in the socket.io `auth` object:
```js
const io = require('socket.io-client');
const socket = io('http://your-server:1337', {
auth: { token: process.env.BOT_TOKEN }
});
```
> **Port note:** socket.io runs on the port defined by `io.port` in your server config (default 1337), which is separate from the HTTP port used for the web UI and REST API.
### Join sequence
After connecting you must wait for the `login` event before emitting `joinChannel`, otherwise the server will ignore it:
```js
socket.once('login', () => {
socket.emit('joinChannel', { name: 'your-channel-name' });
});
```
### Sending chat
```js
socket.emit('chatMsg', { msg: 'Hello from a bot!' });
// Action message:
socket.emit('chatMsg', { msg: '/me waves' });
```
### Events the bot receives
| Event | Payload | Description |
|------------------|----------------------------------------------|-------------------------------------|
| `login` | `{ success, name, guest }` | Server accepted the connection |
| `chatMsg` | `{ username, msg, meta, time }` | A chat message was sent |
| `userlist` | `[{ name, rank, meta }, ...]` | Full user list on join |
| `addUser` | `{ name, rank, meta }` | A user joined the channel |
| `userLeave` | `{ name }` | A user left the channel |
| `setUserMeta` | `{ name, meta }` | A user's meta (AFK, muted) changed |
| `changeMedia` | `{ id, type, title, seconds, ... }` | A new video started playing |
| `playlist` | `[{ uid, media, queueby, temp }, ...]` | Full playlist on join |
| `queue` | `{ item, after }` | An item was added to the playlist |
| `delete` | `{ uid }` | A playlist item was removed |
| `errorMsg` | `{ msg }` | An error from the server |
| `kick` | `{ reason }` | The bot was kicked |
| `announcement` | `{ title, text }` | Server-wide announcement |
`meta.is_bot` is set to `true` in `chatMsg` and user list payloads for bots, which the web UI renders as a `[bot]` badge.
---
## REST API
### Base URL
```
http://your-server:8080/api/v1
```
All channel-scoped endpoints are under `/channels/:channel/`.
### Authentication
Every REST request must include the bot token as a Bearer token:
```
Authorization: Bearer cbt_...
```
The token is validated against the channel in the URL — a token issued for `#general` will be rejected for `/channels/gaming/...`.
### Error responses
All errors return JSON:
```json
{ "error": "Human readable message" }
```
Common status codes:
| Code | Meaning |
|------|-------------------------------------------------------|
| 400 | Bad request (missing/invalid fields) |
| 401 | Missing or invalid token |
| 403 | Token not authorized for this channel, or rank too low |
| 404 | Resource not found |
| 503 | Channel is not currently active (no users in it) |
---
### Playlist
Playlist endpoints require the channel to be active (at least one user present).
#### `GET /channels/:channel/playlist`
Returns the current playlist and which item is playing.
No minimum rank.
**Response:**
```json
{
"items": [
{
"uid": 1,
"id": "dQw4w9WgXcQ",
"type": "yt",
"title": "Rick Astley - Never Gonna Give You Up",
"seconds": 212,
"duration": "3:32",
"thumb": { "url": "..." },
"meta": {}
}
],
"currentIndex": 0,
"locked": false
}
```
`uid` is the server-assigned unique ID for the playlist slot. Use it for delete/jump operations.
#### `POST /channels/:channel/playlist`
Queue a new item. Minimum rank: **2 (Mod)**.
Returns `202 Accepted` immediately because media lookup is asynchronous. If the bot's permissions don't allow the add (e.g. playlist is locked and rank is too low), a `400` is returned synchronously.
**Body:**
```json
{ "id": "dQw4w9WgXcQ", "type": "yt", "pos": "end" }
```
| Field | Required | Values | Default |
|-------|----------|---------------------|---------|
| `id` | yes | media ID string | |
| `type`| yes | see media types below | |
| `pos` | no | `"end"` or `"next"` | `"end"` |
**Media types:**
| Type | Source |
|------|----------------------|
| `yt` | YouTube |
| `sc` | SoundCloud |
| `tw` | Twitch stream |
| `tc` | Twitch clip |
| `rt` | Dailymotion |
| `vm` | Vimeo |
| `dm` | Dailymotion |
| `gd` | Google Drive |
| `fi` | Direct file URL |
| `cu` | Custom embed (HTML) |
#### `DELETE /channels/:channel/playlist/:uid`
Remove a playlist item by uid. Minimum rank: **3 (Admin)**.
#### `PUT /channels/:channel/playlist/playing`
Skip to a specific item. Minimum rank: **2 (Mod)**.
**Body:**
```json
{ "uid": 3 }
```
#### `POST /channels/:channel/playlist/shuffle`
Shuffle the playlist. Minimum rank: **3 (Admin)**.
#### `POST /channels/:channel/playlist/clear`
Clear the entire playlist. Minimum rank: **3 (Admin)**.
---
### Emotes
Emote endpoints read and write directly to the database and work even when the channel is offline. If the channel happens to be active, changes are broadcast live to connected users.
#### `GET /channels/:channel/emotes`
Returns the full emote list. No minimum rank.
**Response:**
```json
[
{ "name": "KEKW", "image": "https://cdn.example.com/kekw.png", "source": "..." }
]
```
#### `POST /channels/:channel/emotes`
Add a new emote. Minimum rank: **4 (Owner)**.
**Body:**
```json
{ "name": "KEKW", "image": "https://cdn.example.com/kekw.png" }
```
Returns `409 Conflict` if the name is already taken.
#### `PUT /channels/:channel/emotes/:name`
Update an emote's image or rename it. Minimum rank: **4 (Owner)**.
**Body** (all fields optional, but at least one must differ):
```json
{ "image": "https://cdn.example.com/kekw-v2.png", "newName": "KEKWait" }
```
Omit `newName` to keep the existing name. Returns `409` if the new name is already taken.
#### `DELETE /channels/:channel/emotes/:name`
Delete an emote by name. Minimum rank: **4 (Owner)**.
---
### Users / Moderation
These endpoints require the channel to be active.
#### `GET /channels/:channel/users`
List currently connected users. No minimum rank.
**Response:**
```json
[
{ "name": "Alice", "rank": 3, "afk": false, "is_bot": false },
{ "name": "MyBot", "rank": 2, "afk": false, "is_bot": true }
]
```
#### `POST /channels/:channel/users/:name/kick`
Kick a user. Minimum rank: **2 (Mod)**. Cannot kick users with equal or higher rank.
**Body:**
```json
{ "reason": "Spamming" }
```
`reason` is optional, defaults to `"Kicked by bot"`.
#### `POST /channels/:channel/users/:name/ban`
Ban a user by name. Minimum rank: **3 (Admin)**. Cannot ban users with equal or higher rank.
**Body:**
```json
{ "reason": "Ban evasion" }
```
`reason` is optional, defaults to `"Banned by bot"`.
#### `DELETE /channels/:channel/users/:name/ban`
Remove a ban. Minimum rank: **3 (Admin)**.
#### `PUT /channels/:channel/users/:name/rank`
Change a user's channel rank. Minimum rank: **4 (Owner)**. Cannot assign a rank equal to or higher than your own, and cannot target users with equal or higher rank.
**Body:**
```json
{ "rank": 2 }
```
---
### Settings
Settings endpoints require the channel to be active. Minimum rank: **4 (Owner)** for both read and write.
#### `GET /channels/:channel/settings`
Returns current channel options.
**Response:**
```json
{
"pagetitle": "My Channel",
"allow_voteskip": true,
"voteskip_ratio": 0.5,
"maxlength": 0,
"afk_timeout": 600,
"password": "",
"show_public": false,
...
}
```
**Available keys:**
`allow_voteskip`, `allow_dupes`, `voteskip_ratio`, `maxlength`, `playlist_max_duration_per_user`, `afk_timeout`, `enable_link_regex`, `chat_antiflood`, `chat_antiflood_burst`, `chat_antiflood_sustained`, `new_user_chat_delay`, `new_user_chat_link_delay`, `pagetitle`, `password`, `externalcss`, `externaljs`, `show_public`, `torbanned`, `block_anonymous_users`, `allow_ascii_control`, `playlist_max_per_user`
#### `PUT /channels/:channel/settings`
Update one or more settings. Unknown keys are silently ignored.
**Body:**
```json
{ "pagetitle": "Now Playing: Chill Beats", "allow_voteskip": false }
```
---
### Shows
Show endpoints manage scheduled playlist runs. These endpoints support bot Bearer auth and session auth.
#### `GET /channels/:channel/shows`
List shows for the channel. Minimum rank: **2 (Mod)**.
#### `GET /channels/:channel/shows/:id`
Get a single show. Minimum rank: **2 (Mod)**.
#### `GET /channels/:channel/shows/public`
List only public-facing shows (`scheduled`, `running`, `paused`, `completed`). No auth required.
#### `POST /channels/:channel/shows/resolve-media`
Resolve up to 50 media entries to display-ready titles before saving a show. Minimum rank: **2 (Mod)**.
**Body:**
```json
{
"items": [
{ "type": "yt", "id": "dQw4w9WgXcQ" }
]
}
```
**Response:**
```json
{
"items": [
{ "type": "yt", "id": "dQw4w9WgXcQ", "title": "Rick Astley - Never Gonna Give You Up", "ok": true }
]
}
```
#### `POST /channels/:channel/shows`
Create a show. Minimum rank: **2 (Mod)**.
#### `PUT /channels/:channel/shows/:id`
Update a show. Minimum rank: **2 (Mod)**.
#### `DELETE /channels/:channel/shows/:id`
Delete a show. Minimum rank: **3 (Admin)**.
#### `POST /channels/:channel/shows/:id/action`
Run control action.
| Action | Minimum rank |
|------------|--------------|
| `pause` | 2 |
| `resume` | 2 |
| `schedule` | 2 |
| `run` | 3 |
| `cancel` | 3 |
**Create/Update body schema:**
```json
{
"name": "Friday Prime",
"notes": "Opening block",
"color": "#337AB7",
"scheduled_for": "2026-05-22T19:00:00.000Z",
"estimated_end_at": "2026-05-22T21:00:00.000Z",
"timezone": "America/New_York",
"recurrence": "weekly",
"fill_mode": "replace",
"conflict_mode": "force",
"start_playback": true,
"playlist": [
{ "type": "yt", "id": "dQw4w9WgXcQ", "pos": "end" }
],
"status": "scheduled"
}
```
**Field constraints:**
- `name`: required, 1-100 chars
- `notes`: optional string, trimmed and capped to 20,000 chars
- `color`: optional `#RRGGBB` hex color
- `timezone`: required IANA timezone string (example: `Europe/Berlin`, `America/New_York`)
- `scheduled_for`: required date string or unix timestamp (ms)
- `estimated_end_at`: optional date string/timestamp, must be later than `scheduled_for` when present
- `recurrence`: `none | daily | weekly`
- `fill_mode`: `append | replace`
- `conflict_mode`: `force | skip`
- `playlist`: non-empty array of media entries (`type`, `id`, optional `pos: next|end`)
- `status`: one of `draft | scheduled | paused | running | completed | failed | canceled` (`running` is accepted but normalized to `scheduled` on write)
**Action body schema:**
```json
{ "action": "run" }
```
**Show response shape** (`GET`, `POST`, `PUT`, and `POST /action`):
```json
{
"id": 42,
"channel_name": "my-channel",
"channel_id": 10,
"name": "Friday Prime",
"notes": "Opening block",
"notes_html": "<p>Opening block</p>",
"color": "#337AB7",
"playlist": [{ "type": "yt", "id": "dQw4w9WgXcQ", "pos": "end" }],
"timezone": "America/New_York",
"scheduled_for": 1779476400000,
"estimated_end_at": 1779483600000,
"next_run_at": 1779476400000,
"status": "scheduled",
"recurrence": "weekly",
"recurrence_meta": null,
"fill_mode": "replace",
"conflict_mode": "force",
"start_playback": true,
"run_count": 0,
"last_run_at": null,
"created_at": 1779400000000,
"updated_at": 1779400000000,
"created_by": "my-bot",
"updated_by": "my-bot",
"last_error": null
}
```
---
### Bot management
These endpoints use **session cookie auth** (the normal logged-in web session), not a bot token. They are intended for the channel settings UI.
#### `GET /channels/:channel/bots`
List all bots for the channel. Returns id, name, rank, creator, creation time, last connection time. Requires channel rank ≥ 2.
#### `POST /channels/:channel/bots`
Issue a new bot token. Requires channel rank ≥ 2. The returned `token` is shown **once** and not stored.
**Body:**
```json
{ "name": "MyBot", "rank": 2 }
```
**Response:**
```json
{ "id": 7, "name": "MyBot", "rank": 2, "token": "cbt_..." }
```
#### `DELETE /channels/:channel/bots/:id`
Revoke a bot token. Any live socket connections for that bot are disconnected immediately. Requires channel rank ≥ 2 and your rank must be ≥ the bot's rank.
---
## Demo bot
A working example with a TUI is in `examples/demo-bot/`.
```
cd examples/demo-bot
npm install
cp .env.example .env
# Edit .env: fill in BOT_TOKEN, CHANNEL, SERVER_URL, API_BASE
node bot.js
```
**.env fields:**
| Variable | Description | Default |
|--------------|---------------------------------------------------------|-----------------------------------|
| `BOT_TOKEN` | Bot token from the channel settings Bots tab | — |
| `CHANNEL` | Channel name (lowercase, no `#`) | — |
| `SERVER_URL` | socket.io URL (use the io.port, not the HTTP port) | `http://localhost:1337` |
| `API_BASE` | Base URL for REST requests | `http://localhost:8080/api/v1` |
**TUI keybindings:** Enter to send, PgUp/PgDn to scroll, Ctrl-C to quit.
**Bot commands** (prefix with `/` in the input box):
| Command | Description |
|--------------------------|----------------------------------------|
| `/help` | List commands |
| `/playlist` | Show playlist via REST |
| `/emotes` | List emotes via REST |
| `/settings` | Show channel settings via REST |
| `/users` | Show connected user list |
| `/add <type> <id>` | Queue media, e.g. `/add yt dQw4w9WgXcQ` |
| `/skip` | Skip to next item |
| `/clear` | Clear the playlist |
| `/kick <name> [reason]` | Kick a user |
| `/me <text>` | Send an action message |

View file

@ -1,67 +0,0 @@
## Please do not use chat filters for emoticons! ##
CyTube has an emotes feature which is better-suited for adding emoticons.
Adding them as chat filters is more difficult to manage and uses more server
resources.
## Managing Chat Filters ##
You can access the Chat Filters editor by clicking on "Channel Settings" at the
top of the page, then the "Edit" dropdown, and selecting "Chat Filters".
### Adding a New Chat Filter ###
The first field allows you to enter a unique name for the filter. This can be
anything you like, but it must be unique among all filters on your channel.
The "Filter regex" field is where you input the [regular
expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
that you would like to match. Regular expressions allow you to build
sophisticated filters that can find and replace patterns rather than simple
words. If you simply want to filter a word, you can just use `\bword\b`, as
long as the word does not contain any of the special characters listed on the
linked regular expression guide. The leading and trailing `\b` ensure that you
only match the whole word "word", and do not match instances where it is nested
inside other words.
If you're looking for a way to test your regular expression, there are many free
tools available online, such as [this one](http://regexpal.com/).
The "Flags" field allows you to control certain aspects of matching. The "g"
flag specifies that replacement will be done "globally"-- it will replace all
instances of the regular expression instaed of just the first one. The "i" flag
makes matching case-insensitive, so that the capitalization of the message
doesn't matter. Flags can be combined by putting both of them in the box, e.g.
"gi".
The "Replacement" field is where you specify the text to be substituted for the
original messagse. This allows a limited subset of HTML tags to be used.
## Editing Filters ##
From the chat filter list, you can drag and drop filters to rearrange the order
in which they are executed. For each filter, there are two buttons. The left
button allows you to edit the filter, to update the regular expression, flags,
replacement, and whether or not the filter should be applied to links inside of
messages (this defaults to off). The red trash can button removes the filter.
## Export/Import ##
The export/import feature allows you to back up your filter list and restore it
later, or clone filters to a new channel. Clicking "Export filter list" will
populate the below textarea with a JSON encoded version of the filter list.
Copy this and save it somewhere safe. Later, you can paste this same text back
into the box and click "Import filter list" to overwrite your current filters
with the exported list.
## Notes ##
* By default, CyTube automatically replaces URLs in chat messages with
clickable links. You can disable this from the "Chat Settings" section
under the "General Settings" tab.
* By default, chat filters will not replace text inside of links, to prevent
them from being broken by the filter. You can override this by editing the
filter and checking the "Filter Links" box.
* Incoming messages have HTML special characters sanitized before messages are
filtered. You will have to account for this if you want to filter these
characters. For example, instead of matching `<`, you must match `&lt;`.

View file

@ -1,210 +0,0 @@
CyTube Custom Content Metadata
==============================
*Last updated: 2022-02-12*
## Purpose ##
CyTube currently supports adding custom audio/video content by allowing the user
to supply a direct URL to an audio/video file. The server uses `ffprobe` to
probe the file for various metadata, including the codec/container format and
the duration. This approach has a few disadvantages over the officially
supported media providers, namely:
* Since it accepts a single file, it is not possible to provide multiple
source URLs with varying formats or bitrates to allow viewers to select the
best source for their computer.
- It also means it is not possible to provide text tracks for subtitles or
closed captioning, or to provide image URLs for thumbnails/previews.
* Probing the file with `ffprobe` is slow, especially if the content is hosted
in a far away network location, which at best is inconvenient and at worst
results in timeouts and inability to add the content.
* Parsing the `ffprobe` output is inexact, and may sometimes result in
detecting the wrong format, or failing to detect the title.
This document specifies a new supported media provider which allows users to
provide a JSON manifest specifying the metadata for custom content in a way that
avoids the above issues and is more flexible for extension.
## Custom Manifest URLs ##
Custom media manifests are added to CyTube by adding a link to a public URL
hosting the JSON metadata manifest. Pasting the JSON directly into CyTube is
not supported. Valid JSON manifests must:
* Have a URL path ending with the file extension `.json` (not counting
querystring parameters)
* Be served with the `Content-Type` header set to `application/json`
* Be retrievable at any time while the item is on the playlist (CyTube may
re-request the metadata for an item already on the playlist to revalidate)
* Respond to valid requests with a 200 OK HTTP response code (redirects are
not supported)
* Respond within 10 seconds
* Not exceed 100 KiB in size
## Manifest Format ##
To add custom content, the user provides a JSON object with the following keys:
* `title`: A nonempty string specifying the title of the content. For legacy
reasons, CyTube currently truncates this to 100 UTF-8 characters.
* `duration`: A non-negative, finite number specifying the duration, in
seconds, of the content. This is what the server will use for timing
purposes. Decimals are allowed, but CyTube's timer truncates the value as
an integer number of seconds, so including fractional seconds lends no
advantage.
* `live`: An optional boolean (default: `false`) indicating whether the
content is live or pre-recorded. For live content, the `duration` is
ignored, and the server won't advance the playlist automatically.
* `thumbnail`: An optional string specifying a URL for a thumbnail image of
the content. CyTube currently does not support displaying thumbnails in the
playlist, but this functionality may be offered in the future.
* `sources`: A nonempty list of playable sources for the content. The format
is described below.
* `audioTracks`: An optional list of audio tracks for using demuxed audio
and providing multiple audio selections. The format is described below.
* `textTracks`: An optional list of text tracks for subtitles or closed
captioning. The format is described below.
### Source Format ###
Each source entry is a JSON object with the following keys:
* `url`: A valid URL that browsers can use to retrieve the content. The URL
must resolve to a publicly-routed IP address, and must the `https:` scheme.
* `contentType`: A string representing the MIME type of the content at `url`.
A list of acceptable MIME types is provided below.
* `quality`: A number representing the quality level of the source. The
supported quality levels are `240`, `360`, `480`, `540`, `720`, `1080`,
`1440`, and `2160`. This may be extended in the future.
* `bitrate`: An optional number indicating the bitrate (in Kbps) of the
content. It must be a positive, finite number if provided. The bitrate is
not currently used by CyTube, but may be used by extensions or custom
scripts to determine whether this source is feasible to play on the viewer's
internet connection.
#### Acceptable MIME Types ####
The following MIME types are accepted for the `contentType` field:
* `video/mp4`
* `video/webm`
* `video/ogg`
* `application/x-mpegURL` (HLS streams)
- HLS is only tested with livestreams. VODs are accepted, but I do not test
this functionality.
* `application/dash+xml` (DASH streams)
- Support for DASH is experimental
* ~~`rtmp/flv`~~
- In light of Adobe phasing out support for Flash, and many browsers
already dropping support, RTMP is not supported by this feature.
RTMP streams are only supported through the existing `rt:` media
type.
* `audio/aac`
* `audio/mp4`
* `audio/mpeg`
* `audio/ogg`
Other audio or video formats, such as AVI, MKV, and FLAC, are not supported due
to lack of common support across browsers for playing these formats. For more
information, refer to
[MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats#Browser_compatibility).
### Audio Track Format ###
Each audio track entry is a JSON object with the following keys:
* `label`: A label for the audio track. This is displayed in the menu for the
viewer to select a text track.
* `language`: A two or three letter IETF BCP 47 subtype code indicating the
language of the audio track.
* `url`: A valid URL that browsers can use to retrieve the track. The URL
must resolve to a publicly-routed IP address, and must use the `https:` scheme.
* `contentType`: A string representing the MIME type of the track at `url`.
Any type starting with `audio` from the list above is acceptable. However
the usage of audio/aac is known to cause audio syncrhonization problems
for some users. It is recommended to use an m4a file to wrap aac streams.
**Important note regarding audio tracks:**
Because of browsers trying to be too smart for their own good, you should
include a silent audio stream in the video sources when using separate audio
tracks. If you do not, the browser will automatically pause the video whenever
the browser detects the page as not visible. There is no way to instruct it to
not do so. You can readily accomplish the inclusion of a silent audio track
with ffmpeg using the anullsrc filter like so:
`ffmpeg -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=48000 -i input.mp4 -c:v copy -c:a aac -shortest output.mp4`
It is recommended to match the sample rate and codec you intend to use in your
audioTracks in your silent track.
### Text Track Format ###
Each text track entry is a JSON object with the following keys:
* `url`: A valid URL that browsers can use to retrieve the track. The URL
must resolve to a publicly-routed IP address, and must the `https:` scheme.
* `contentType`: A string representing the MIME type of the track at `url`.
The only currently supported MIME type is
[`text/vtt`](https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API).
* `name`: A name for the text track. This is displayed in the menu for the
viewer to select a text track.
* `default`: Enable track by default. Optional boolean attribute to enable
a subtitle track to the user by default.
**Important note regarding text tracks and CORS:**
By default, browsers block requests for WebVTT tracks hosted on different
domains than the current page. In order for text tracks to work cross-origin,
the `Access-Control-Allow-Origin` header needs to be set by the remote server
when serving the VTT file. See
[MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin)
for more information about setting this header.
## Example ##
{
"title": "Test Video",
"duration": 10,
"live": false,
"thumbnail": "https://example.com/thumb.jpg",
"sources": [
{
"url": "https://example.com/video.mp4",
"contentType": "video/mp4",
"quality": 1080,
"bitrate": 5000
}
],
"textTracks": [
{
"url": "https://example.com/subtitles.vtt",
"contentType": "text/vtt",
"name": "English Subtitles",
"default": true
}
]
}
## Permissions ##
The permission node to allow users to add custom content is the same as the
permission node for the existing raw file support. Custom content is considered
as an extension of the existing feature.
## Unsupported/Undefined Behavior ##
The behavior under any the following circumstances is not defined by this
specification, and any technical support in these cases is voided. This list is
non-exhaustive.
* Source URLs or text track URLs are hosted on a third-party website that does
not have knowledge of its content being played on CyTube.
* The webserver hosting the source or text track URLs serves a different MIME
type than the one specified in the manifest.
* The webserver hosting the source or text track URLs serves a file that does
not match the MIME type specified in the `Content-Type` HTTP header returned
to the browser.
* The manifest includes source URLs or text track URLs with expiration times,
session IDs, etc. in the URL querystring.
* The manifest provides source URLs with non-silent audio as well as a list
of audioTracks.

View file

@ -1,24 +0,0 @@
# Google Drive Userscript Setup
In response to increasing difficulty and complexity of maintaining Google Drive
support, the native player is being phased out in favor of requiring a
userscript to allow each client to fetch the video stream links for themselves.
Users will be prompted with a link to `/google_drive_userscript`, which explains
the situation and instructs how to install the userscript.
As a server admin, you must generate the userscript from the template by using
the following command:
```sh
npm run generate-userscript <site name> <url> [<url>...]
```
The first argument is the site name as it will appear in the userscript title.
The remaining arguments are the URL patterns on which the script will run. For
example, for cytu.be I use:
```sh
npm run generate-userscript CyTube http://cytu.be/r/* https://cytu.be/r/*
```
This will generate `www/js/cytube-google-drive.user.js`. If you've changed the channel path, be sure to take that into account.

View file

@ -1,24 +0,0 @@
Adding subtitles to Google Drive
================================
1. Upload your video to Google Drive
2. Right click the video in Google Drive and click Manage caption tracks
3. Click Add new captions or transcripts
4. Upload a supported subtitle file
* I have verified that Google Drive will accept .srt and .vtt subtitles. It
might accept others as well, but I have not tested them.
Once you have uploaded your subtitles, they should be available the next time
the video is refreshed by CyTube (either restart it or delete the playlist item
and add it again). On the video you should see a speech bubble icon in the
controls, which will pop up a menu of available subtitle tracks.
## Limitations ##
* Google Drive converts the subtitles you upload into a custom format which
loses some information from the original captions. For example, annotations
for who is speaking are not preserved.
* As far as I know, Google Drive is not able to automatically detect when
subtitle tracks are embedded within the video file. You must upload the
subtitles separately (there are plenty of tools to extract
captions/subtitles from MKV and MP4 files).

View file

@ -1,15 +0,0 @@
# User Guide #
This user guide is a work in progress rewrite of the old user guide. If you notice something is missing, it probably hasn't been ported over from [here](https://github.com/calzoneman/sync/wiki/CyTube-3.0-User-Guide) yet.
## I want to know more about... ##
* [Registering and managing my user account](account-mgmt.md)
* [Available user preferences](user-settings.md)
* [Adding subtitles to Google Drive videos](google-drive-subtitles.md)
* [Managing chat filters](chat-filters.md)
## I need help! ##
1. Please read the [FAQ](https://github.com/calzoneman/sync/wiki/Frequently-Asked-Questions) and check whether that answers your question.
2. If not, you can contact someone for help. IRC support is provided on `irc.esper.net #cytube` ([webchat](https://webchat.esper.net/?channels=cytube) available) for https://cytu.be and general questions about using the software. If nobody is available on IRC, or you want to speak privately, email one of the contacts on https://cytu.be/contact.

View file

@ -1,29 +0,0 @@
Restricting New Accounts from Chat
==================================
With the rising availability and popularity of VPNs and proxies, dedicated
trolls may often come back again and again with a new proxy after being IP
banned and continue spamming. In order to combat this, a new feature has been
added to make it more difficult to rejoin quickly and continue spamming.
Channel moderators now have the ability to configure 2 different settings:
* How long an account must be active before the user can send any chat message
* How long an account must be active before the user can send a chat message
containing a link
This limit applies to both chat messages sent to the channel as well as private
messages. Both of these settings can be configured from the Channel Settings
menu at the top of the page, under the General Settings tab. By default,
accounts must be at least 10 minutes old to chat, and 1 hour old to send links
in chat. Setting either restriction to 0 will disable that restriction.
The age of an account is determined as follows:
* If the user is logged in as a registered account, the registration time of
the account is used.
* Otherwise, the timestamp of the session cookie is used.
The session cookie is set whenever a user first joins a channel, and is reset
whenever the user's IP address changes. Different browsers will have different
session cookies.

View file

@ -1,59 +0,0 @@
# Raw Videos / Audio #
Want to host your own video/audio files for use on CyTube? For servers with the
ffprobe module enabled, CyTube supports this! However, in order to provide a
consistent experience, there are limitations.
## Hosting the File ##
CyTube requires a direct link to the file in order to query it for metadata such
as duration and encoding. The website where you host the file needs to be able
to serve the video directly (rather than embedding it in a flash
player/iframe/etc.). It also needs to serve the correct MIME type for the video
in the `Content-Type` HTTP header, e.g. `video/mp4`.
I don't recommend hosting videos on Dropbox-type services, as they aren't built
to distribute video to many users at a time and often have strict bandwidth
limits. File hosting sites such as Putlocker also cause problems due to being
unable to serve the file directly, or due to binding the link to the IP address
of the user who retrieved it. For best results when using raw video, host the
video yourself on a VPS or dedicated server with plenty of bandwidth.
Note that CyTube only queries the file for metadata, it does not proxy it for
users! Every user watching the video will be downloading it individually.
## Encoding the Video ##
Current internet browsers are very limited in what codecs they can play
natively. Accordingly, CyTube only supports a few codecs:
**Video**
* MP4 (AV1)
* MP4 (H.264)
* WebM (AV1)
* WebM (VP8)
* WebM (VP9)
* Ogg/Theora
**Audio**
* MP3
* Ogg/Vorbis
If your video is in some other format (such as MKV or AVI), then it will need to
be re-encoded. There are plenty of free programs available to re-encode video
files, such as [ffmpeg](http://ffmpeg.org/) and
[handbrake](http://handbrake.fr/).
For best results, encode as an MP4 using H.264. This is natively supported by
many browsers, and can also be played using a fallback flash player for older
browsers that don't support it natively. Always encode with the
[faststart](https://trac.ffmpeg.org/wiki/Encode/H.264#faststartforwebvideo)
flag.
### Subtitles ###
Unfortunately, soft-subtitles are not supported right now. This is something
that may be supported in the future, but currently if you need subtitles, they
will have to be hardsubbed onto the video itself.

View file

@ -1,57 +0,0 @@
Socket.IO Client Configuration
==============================
As of 2015-10-25, the legacy `/sioconfig` JavaScript for retrieving connection
information is being deprecated in favor of a new API. The purpose of this
change is to allow partitioning channels across multiple servers in order to
better handle increasing traffic.
To get the socket.io configuration for the server hosting a particular channel,
make a `GET` request to `/socketconfig/<channel name>.json`. The response will
be a JSON object containing a list of acceptable servers to connect to, or an
error message.
Examples:
```
GET /socketconfig/test.json
200 OK
{
"servers": [
{
"url": "https://localhost:8443",
"secure": true
},
{
"url": "http://localhost:1337",
"secure": false
},
{
"url": "https://local6:8443",
"secure": true,
"ipv6": true
},
{
"url": "http://local6:1337",
"secure": false,
"ipv6": true
}
]
}
GET /socketconfig/$invalid$.json
404 Not Found
{
"error": "Channel \"$invalid$\" does not exist."
}
```
Each entry in the `servers` array has `"secure":true` if the connection is
secured with TLS, otherwise it it is false. An entry with `"ipv6":true`
indicates that the server is listening on the IPv6 protocol.
You can pick any URL to connect socket.io to in order to join the specified
channel. I recommend picking one with `"secure":true`, only choosing an
insecure connection if implementing a TLS connection is infeasible.

View file

@ -1,55 +0,0 @@
# User Preferences #
From any CyTube channel, you can click the Options link at the top of the page to open a dialog where you can change your personal preferences. This page explains each of the available options.
## General ##
General interface preferences.
Setting | Description
--------|------------
Theme | Choose from different colorschemes for the website.
Layout | Choose from different layouts for elements on the page. Fluid layouts will expand to fill the entire window, while compact layouts will remain the same size. "Synchtube" layout is the same as the default layout, but mirrored.
Ignore Channel CSS | Don't load custom stylesheets for each channel. Requires a refresh to take effect.
Ignore Channel JavaScript | Don't load custom scripts for each channel. The Script Access tab allows you to manage your preferences on a per-channel basis, but if this setting is checked, scripts will be globally disallowed and you will not be prompted to accept them when joining a channel.
## Playback ##
Preferences for video playback and the playlist.
Setting | Description
--------|------------
Synchronize video playback | By default, CyTube attempts to synchronize the video so that everyone is watching at the same time. Some users with poor internet connections may wish to disable this in order to prevent excessive buffering due to constantly seeking forward.
Synch threshold | The number of seconds your video is allowed to be ahead/behind before it is forcibly seeked to the correct position. Should be set to at least 2 seconds to avoid buffering problems and choppy playback.
Remove the video player | Automatically remove the video player on page load. Equivalent to manually clicking Layout->Remove Video every time you load a channel.
Hide playlist buttons by default | Hides the control buttons from each video in the playlist, so that only the title is displayed. The control buttons can be shown by right clicking the video item in the playlist.
Old style playlist buttons | Legacy feature introduced in CyTube 2.0 for those who preferred the old 1.0-style video control buttons.
Quality Preference | Sets the preferred quality for player types that support quality selection (currently, this is YouTube, Vimeo, Dailymotion, Google Drive, and Google+). If your preferred quality is not available, the next lowest quality will be used.
## Chat ##
Preferences for the integrated chatroom.
Setting | Description
--------|------------
Show timestamps in chat | When enabled, a timestamp is prepended to each chat message. For example, `[09:45:10] message here`.
Sort userlist by rank | Controls whether the username list is sorted alphabetically and by rank, or just alphabetically.
Sort AFKers to bottom | When enabled, usernames of AFK users will be sorted to the bottom of the username list.
Blink page title on new messages | Controls the conditions under which the tab title blinks between the channel title and `*Chat*` when a new message arrives.
Notification sound on new messages | Controls the conditions under which a notification sound is played when a new message arrives.
Add a send button to chat | Adds a clickable button to send chat messages. Only really useful for virtual keyboards that lack a dedicated Enter key.
Disable chat emotes | Disables the automatic conversion of channel-defined emote codes to inline images.
## Script Access ##
Manage your preferences for allowing or denying custom scripts for channels you've visited. A channel will only appear here if you checked "Remember my preference" when allowing or denying a channel script. You can toggle the preference between "Allow" and "Deny", or click "Clear Preference" to remove the saved preference, so that you will be asked every time you join the channel.
## Moderator ##
Settings that only apply to channel moderators.
Setting | Description
--------|------------
Show name color | Colors your username in chat (the same color as in the username list). This setting is also controlled by the small button labeled "M" in the upper right corner of chat.
Show join messages | Display a message every time a user logs in to the chat.
Show shadowmuted messages | Show chat messages from shadowmuted users. These messages will appear ~~struck through~~, and only moderators with this setting enabled will see them.

View file

@ -1,11 +0,0 @@
# Issue a bot token in the channel settings modal (Bots tab), then paste it here.
BOT_TOKEN=cbt_your_token_here
# The channel this token was issued for.
CHANNEL=yourchannel
# Base URL of the CyTube server (no trailing slash).
SERVER_URL=http://localhost:1337
# REST API base (usually SERVER_URL + /api/v1).
API_BASE=http://localhost:8080/api/v1

View file

@ -1,594 +0,0 @@
#!/usr/bin/env node
/**
* CyTube Sync Demo Bot
*
* Shows the two halves of the bot API:
* WebSocket (socket.io-client) real-time events: chat, user list, playlist
* REST API (fetch) queries and commands: playlist, emotes, settings, moderation
*
* Setup:
* cp .env.example .env # fill in BOT_TOKEN and CHANNEL
* npm install
* node bot.js
*
* TUI keybindings:
* Enter send message or run command
* PgUp/PgDn scroll chat
* Ctrl-C quit
*
* Commands (prefix with /):
* /help list commands
* /playlist show current playlist via REST
* /emotes list emotes via REST
* /settings show channel settings via REST
* /users dump user list from in-memory state
* /add <type> <id> add media e.g. /add yt dQw4w9WgXcQ
* /skip skip to next playlist item
* /clear clear the playlist
* /kick <name> [reason] kick a user
* /me <text> send an action (/me) message
*/
'use strict';
require('dotenv').config();
const io = require('socket.io-client');
const fetch = require('node-fetch');
const blessed = require('blessed');
// ── Config ────────────────────────────────────────────────────────────────────
const {
BOT_TOKEN,
CHANNEL,
SERVER_URL = 'http://localhost:8080',
API_BASE = 'http://localhost:8080/api/v1',
} = process.env;
if (!BOT_TOKEN || !CHANNEL) {
console.error('BOT_TOKEN and CHANNEL must be set. Copy .env.example to .env and fill it in.');
process.exit(1);
}
if (!BOT_TOKEN.startsWith('cbt_')) {
console.error('BOT_TOKEN does not look right — it should start with cbt_');
process.exit(1);
}
// ── REST helpers ──────────────────────────────────────────────────────────────
async function apiRequest(method, path, body) {
const url = `${API_BASE}/channels/${CHANNEL}${path}`;
const opts = {
method,
headers: {
'Authorization': `Bearer ${BOT_TOKEN}`,
'Content-Type': 'application/json',
},
};
if (body !== undefined) opts.body = JSON.stringify(body);
const res = await fetch(url, opts);
const json = await res.json().catch(() => null);
if (!res.ok) {
throw new Error((json && json.error) || `HTTP ${res.status}`);
}
return json;
}
const api = {
get: (path) => apiRequest('GET', path),
post: (path, body) => apiRequest('POST', path, body),
put: (path, body) => apiRequest('PUT', path, body),
delete: (path) => apiRequest('DELETE', path),
};
// ── Utilities ─────────────────────────────────────────────────────────────────
function stripHtml(html) {
return html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'");
}
// Escape blessed tag syntax so server content can't inject markup.
function escBless(str) {
return String(str).replace(/\{/g, '\\{');
}
function hhmm(secs) {
return `${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, '0')}`;
}
function timestamp() {
return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// ── In-memory state ───────────────────────────────────────────────────────────
const state = {
users: [], // userlist entries from server
nowPlaying: null, // current changeMedia payload
connected: false,
inChannel: false,
};
// ── TUI ───────────────────────────────────────────────────────────────────────
const screen = blessed.screen({
smartCSR: true,
title: `CyTube Bot :: #${CHANNEL}`,
fullUnicode: true,
forceUnicode: true,
});
// Top bar — connection status + now playing
const statusBar = blessed.box({
top: 0,
left: 0,
width: '100%',
height: 1,
tags: true,
style: { bg: 'blue', fg: 'white', bold: true },
content: ` CyTube Bot #${CHANNEL} Connecting...`,
});
// Main chat log (left, scrollable)
const chatLog = blessed.log({
top: 1,
left: 0,
width: '70%',
height: '100%-4',
border: { type: 'line' },
label: ' Chat ',
scrollable: true,
alwaysScroll: true,
scrollbar: { ch: ' ', style: { bg: 'cyan' } },
mouse: true,
tags: true,
wrap: true,
style: { border: { fg: 'cyan' }, label: { fg: 'cyan', bold: true } },
});
// User list sidebar (right)
const userList = blessed.list({
top: 1,
right: 0,
width: '30%',
height: '100%-4',
border: { type: 'line' },
label: ' Users ',
scrollable: true,
mouse: true,
tags: true,
style: {
border: { fg: 'cyan' },
label: { fg: 'cyan', bold: true },
item: { fg: 'white' },
selected: { fg: 'white' },
},
});
// Input box (bottom)
const inputBox = blessed.textbox({
bottom: 0,
left: 0,
width: '100%',
height: 3,
border: { type: 'line' },
label: ' Message — /help for commands — Ctrl-C to quit ',
inputOnFocus: true,
style: { border: { fg: 'green' }, label: { fg: 'green' } },
});
screen.append(statusBar);
screen.append(chatLog);
screen.append(userList);
screen.append(inputBox);
screen.key(['C-c'], () => process.exit(0));
// ── TUI helpers ───────────────────────────────────────────────────────────────
function setStatus(msg) {
statusBar.setContent(` CyTube Bot #${CHANNEL} ${msg}`);
screen.render();
}
function chat(line) {
chatLog.log(line);
screen.render();
}
function info(line) {
chat(`{cyan-fg}${line}{/cyan-fg}`);
}
function warn(line) {
chat(`{yellow-fg}${line}{/yellow-fg}`);
}
function fail(line) {
chat(`{red-fg}✗ ${line}{/red-fg}`);
}
function rebuildUserList() {
const items = state.users.map(u => {
const isBot = u.meta && u.meta.is_bot;
const afk = u.meta && u.meta.afk;
let rankStr;
if (u.rank >= 5) rankStr = '{red-fg}[creator]{/red-fg}';
else if (u.rank >= 4) rankStr = '{yellow-fg}[owner]{/yellow-fg}';
else if (u.rank >= 3) rankStr = '{magenta-fg}[admin]{/magenta-fg}';
else if (u.rank >= 2) rankStr = '{green-fg}[mod]{/green-fg}';
else rankStr = '';
const botTag = isBot ? ' {blue-fg}[bot]{/blue-fg}' : '';
const afkTag = afk ? ' {grey-fg}[afk]{/grey-fg}' : '';
return `${escBless(u.name)} ${rankStr}${botTag}${afkTag}`;
});
userList.setLabel(` Users (${items.length}) `);
userList.setItems(items);
screen.render();
}
// ── Socket.IO ─────────────────────────────────────────────────────────────────
const socket = io(SERVER_URL, {
// This is how the bot authenticates — token goes in socket.handshake.auth.token
auth: { token: BOT_TOKEN },
reconnection: true,
reconnectionDelay: 3000,
reconnectionAttempts: Infinity,
});
socket.on('connect', () => {
state.connected = true;
setStatus('Authenticating...');
});
socket.on('disconnect', (reason) => {
state.connected = false;
state.inChannel = false;
state.users = [];
rebuildUserList();
warn(`Disconnected: ${reason}`);
setStatus(`Disconnected — reconnecting...`);
});
socket.on('connect_error', (err) => {
fail(`Connection error: ${err.message}`);
});
// Server confirms authentication and sends the bot's display name + rank.
// We wait for this before joining the channel to avoid any ordering issues.
socket.on('login', (data) => {
if (data.success) {
info(`Authenticated as: ${escBless(data.name)}`);
socket.emit('joinChannel', { name: CHANNEL });
} else {
fail(`Authentication failed: ${escBless(data.error || 'unknown')}`);
}
});
socket.on('errorMsg', (data) => {
fail(escBless(data.msg || 'Server error'));
});
socket.on('kick', (data) => {
fail(`Kicked: ${escBless(data.reason || '')}`);
setStatus('Kicked from channel');
});
// ── Channel events ────────────────────────────────────────────────────────────
// Channel options (title, password, etc.)
socket.on('channelOpts', (opts) => {
const title = opts.pagetitle || CHANNEL;
const playing = state.nowPlaying ? `${escBless(state.nowPlaying.title)}` : '';
setStatus(`{bold}${escBless(title)}{/bold}${playing}`);
});
// ── User list events ──────────────────────────────────────────────────────────
// Full user list, sent on join and refresh
socket.on('userlist', (users) => {
state.users = users;
state.inChannel = true;
rebuildUserList();
info(`Joined #${CHANNEL}${users.length} user(s) present`);
});
// New user joined
socket.on('addUser', (user) => {
state.users = state.users.filter(u => u.name !== user.name);
state.users.push(user);
rebuildUserList();
chat(`{green-fg}→ ${escBless(user.name)} joined{/green-fg}`);
});
// User left
socket.on('userLeave', (data) => {
state.users = state.users.filter(u => u.name !== data.name);
rebuildUserList();
chat(`{red-fg}← ${escBless(data.name)} left{/red-fg}`);
});
// Rank changed for a user
socket.on('setUserRank', (data) => {
const user = state.users.find(u => u.name === data.name);
if (user) user.rank = data.rank;
rebuildUserList();
});
// AFK / mute state changed
socket.on('setUserMeta', (data) => {
const user = state.users.find(u => u.name === data.name);
if (user) Object.assign(user.meta, data.meta);
rebuildUserList();
});
// ── Chat events ───────────────────────────────────────────────────────────────
socket.on('chatMsg', (data) => {
const time = timestamp();
const name = escBless(data.username || '?');
const msg = escBless(stripHtml(data.msg || ''));
const isAction = data.meta && data.meta.addClass === 'action';
// is_bot is set by the server in the message meta; fall back to checking
// the local user list in case the message arrives before the userlist does.
const senderInList = state.users.find(u => u.name === data.username);
const isBot = (data.meta && data.meta.is_bot) ||
(senderInList && senderInList.meta && senderInList.meta.is_bot);
const botTag = isBot ? ' {blue-fg}[bot]{/blue-fg}' : '';
if (isAction) {
chat(`{grey-fg}[${time}]{/grey-fg}${botTag} {italic}* ${name} ${msg}{/italic}`);
} else {
chat(`{grey-fg}[${time}]{/grey-fg} {bold}${name}{/bold}${botTag}: ${msg}`);
}
});
// Private messages
socket.on('pm', (data) => {
const name = escBless(data.username || '?');
const msg = escBless(stripHtml(data.msg || ''));
chat(`{magenta-fg}[PM ← ${name}]{/magenta-fg} ${msg}`);
});
// Chat cleared by a moderator
socket.on('clearchat', () => {
chatLog.setContent('');
info('Chat was cleared by a moderator.');
screen.render();
});
// ── Playlist events ───────────────────────────────────────────────────────────
// Full playlist on join
socket.on('playlist', (items) => {
if (items.length > 0) {
info(`Playlist loaded: ${items.length} item(s)`);
}
});
// New item added to playlist by someone
socket.on('queue', (data) => {
const item = data.item;
if (item && item.media) {
info(`Queued: [${item.media.type}] ${escBless(item.media.title)}`);
}
});
// Currently playing changed
socket.on('changeMedia', (media) => {
state.nowPlaying = media;
const dur = media.seconds ? ` (${hhmm(media.seconds)})` : '';
const title = escBless(media.title || media.id);
setStatus(`${title}${dur}`);
info(`Now playing: {bold}${title}{/bold}${dur}`);
});
// ── Emote events ──────────────────────────────────────────────────────────────
socket.on('updateEmote', (emote) => {
info(`Emote updated: :${escBless(emote.name)}:`);
});
socket.on('removeEmote', (data) => {
info(`Emote removed: :${escBless(data.name)}:`);
});
// ── Commands ──────────────────────────────────────────────────────────────────
const COMMANDS = {
help() {
info('─── Commands ───────────────────────────────────────────────────');
info(' /playlist fetch and show the playlist');
info(' /emotes list emote names');
info(' /settings show channel settings');
info(' /users dump in-memory user list');
info(' /add <type> <id> add media e.g. /add yt dQw4w9WgXcQ');
info(' /skip skip to next playlist item');
info(' /clear clear the playlist');
info(' /kick <name> [reason] kick a user from the channel');
info(' /me <text> send an action message');
info(' <anything else> send as a chat message');
info('───────────────────────────────────────────────────────────────');
},
async playlist() {
try {
const data = await api.get('/playlist');
info(`─── Playlist (${data.items.length} item${data.items.length !== 1 ? 's' : ''}) ──`);
if (data.items.length === 0) {
info(' (empty)');
} else {
data.items.forEach((item, i) => {
const dur = item.seconds ? hhmm(item.seconds) : '?:??';
const marker = i === data.currentIndex ? '{yellow-fg}▶{/yellow-fg}' : ' ';
info(` ${marker} [${item.type}] ${escBless(item.title)} (${dur}) uid:${item.uid}`);
});
}
if (data.locked) warn(' Playlist is locked');
} catch (e) {
fail(`playlist: ${e.message}`);
}
},
async emotes() {
try {
const emotes = await api.get('/emotes');
info(`─── Emotes (${emotes.length}) ──`);
if (emotes.length === 0) {
info(' (none)');
} else {
// Print names in rows of 8
for (let i = 0; i < emotes.length; i += 8) {
info(' ' + emotes.slice(i, i + 8).map(e => `:${escBless(e.name)}:`).join(' '));
}
}
} catch (e) {
fail(`emotes: ${e.message}`);
}
},
async settings() {
try {
const s = await api.get('/settings');
info('─── Channel Settings ──');
for (const [k, v] of Object.entries(s)) {
if (v !== null && v !== '' && v !== false) {
info(` ${k}: ${escBless(String(v))}`);
}
}
} catch (e) {
fail(`settings: ${e.message}`);
}
},
users() {
info(`─── Users (${state.users.length}) ──`);
state.users.forEach(u => {
const rank = u.rank >= 5 ? 'creator' : u.rank >= 4 ? 'owner' : u.rank >= 3 ? 'admin' : u.rank >= 2 ? 'mod' : 'user';
const isBot = u.meta && u.meta.is_bot ? ' [bot]' : '';
info(` ${escBless(u.name)} (${rank} rank:${u.rank})${isBot}`);
});
},
async add(args) {
const parts = args.trim().split(/\s+/);
if (parts.length < 2) {
fail('Usage: /add <type> <id> e.g. /add yt dQw4w9WgXcQ');
return;
}
const [type, id] = parts;
try {
await api.post('/playlist', { type, id, pos: 'end' });
info(`Added [${type}] ${escBless(id)} to playlist`);
} catch (e) {
fail(`add: ${e.message}`);
}
},
async skip() {
try {
const data = await api.get('/playlist');
if (data.items.length === 0) { warn('Playlist is empty'); return; }
const idx = data.currentIndex;
if (idx < 0 || idx >= data.items.length - 1) {
warn('No next item in playlist');
return;
}
const next = data.items[idx + 1];
await api.put('/playlist/playing', { uid: next.uid });
info(`Skipped to: ${escBless(next.title)}`);
} catch (e) {
fail(`skip: ${e.message}`);
}
},
async clear() {
try {
await api.post('/playlist/clear');
info('Playlist cleared');
} catch (e) {
fail(`clear: ${e.message}`);
}
},
async kick(args) {
const parts = args.trim().split(/\s+/);
const name = parts[0];
const reason = parts.slice(1).join(' ') || 'Kicked by bot';
if (!name) { fail('Usage: /kick <name> [reason]'); return; }
try {
await api.post(`/users/${encodeURIComponent(name)}/kick`, { reason });
info(`Kicked ${escBless(name)}`);
} catch (e) {
fail(`kick: ${e.message}`);
}
},
me(args) {
const text = args.trim();
if (!text) { fail('Usage: /me <text>'); return; }
socket.emit('chatMsg', { msg: `/me ${text}` });
},
};
async function handleInput(line) {
line = line.trim();
if (!line) return;
if (line.startsWith('/')) {
const space = line.indexOf(' ');
const name = (space === -1 ? line.slice(1) : line.slice(1, space)).toLowerCase();
const args = space === -1 ? '' : line.slice(space + 1);
if (COMMANDS[name]) {
try {
await COMMANDS[name](args);
} catch (e) {
fail(`Command error: ${e.message}`);
}
} else {
fail(`Unknown command: /${name} (type /help for a list)`);
}
} else {
// Regular chat message — sent over the WebSocket, not REST.
// The server will echo it back as a chatMsg event.
socket.emit('chatMsg', { msg: line });
}
}
// ── Input box wiring ──────────────────────────────────────────────────────────
inputBox.on('submit', async (value) => {
inputBox.clearValue();
inputBox.focus();
screen.render();
if (value && value.trim()) {
await handleInput(value);
}
});
// Pressing Enter submits, but blessed's textbox needs this nudge
inputBox.key('enter', () => inputBox.submit());
// ── Boot ──────────────────────────────────────────────────────────────────────
info(`Connecting to ${SERVER_URL} as bot in #${CHANNEL}...`);
info('Type /help for available commands.');
inputBox.focus();
screen.render();

View file

@ -1,283 +0,0 @@
{
"name": "cytube-demo-bot",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "cytube-demo-bot",
"version": "1.0.0",
"dependencies": {
"blessed": "^0.1.81",
"dotenv": "^16.0.0",
"node-fetch": "^2.7.0",
"socket.io-client": "^4.7.0"
}
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="
},
"node_modules/blessed": {
"version": "0.1.81",
"resolved": "https://registry.npmjs.org/blessed/-/blessed-0.1.81.tgz",
"integrity": "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ==",
"bin": {
"blessed": "bin/tput.js"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/engine.io-client": {
"version": "6.6.4",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.4.tgz",
"integrity": "sha512-+kjUJnZGwzewFDw951CDWcwj35vMNf2fcj7xQWOctq1F2i1jkDdVvdFG9kM/BEChymCH36KgjnW0NsL58JYRxw==",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.18.3",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/socket.io-client": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/ws": {
"version": "8.18.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"engines": {
"node": ">=0.4.0"
}
}
},
"dependencies": {
"@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="
},
"blessed": {
"version": "0.1.81",
"resolved": "https://registry.npmjs.org/blessed/-/blessed-0.1.81.tgz",
"integrity": "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ=="
},
"debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"requires": {
"ms": "^2.1.3"
}
},
"dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="
},
"engine.io-client": {
"version": "6.6.4",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.4.tgz",
"integrity": "sha512-+kjUJnZGwzewFDw951CDWcwj35vMNf2fcj7xQWOctq1F2i1jkDdVvdFG9kM/BEChymCH36KgjnW0NsL58JYRxw==",
"requires": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.18.3",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q=="
},
"ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"requires": {
"whatwg-url": "^5.0.0"
}
},
"socket.io-client": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
"requires": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
}
},
"socket.io-parser": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
"requires": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
}
},
"tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"requires": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"ws": {
"version": "8.18.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"requires": {}
},
"xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ=="
}
}
}

View file

@ -1,15 +0,0 @@
{
"name": "cytube-demo-bot",
"version": "1.0.0",
"description": "Demo bot for the CyTube Sync bot API — TUI chat client + REST queries",
"main": "bot.js",
"scripts": {
"start": "node bot.js"
},
"dependencies": {
"blessed": "^0.1.81",
"dotenv": "^16.0.0",
"node-fetch": "^2.7.0",
"socket.io-client": "^4.7.0"
}
}

View file

@ -1,32 +0,0 @@
# Python Show Bot Example
Uses `veretube-bot==0.1.4` with `AsyncBot` and the built-in Shows API helpers.
## Setup
```bash
cd examples/python-show-bot
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
Set environment variables:
- `BOT_TOKEN` (required)
- `CHANNEL` (required)
- `SOCKET_URL` (default: `http://localhost:1337`)
- `API_BASE` (default: `http://localhost:8080/api/v1`)
- `SHOW_TIMEZONE` (default: `UTC`, must be valid IANA timezone)
Run:
```bash
python bot.py
```
## Chat Commands
- `!shows` - list shows
- `!mkshow` - create a demo show
- `!runshow <id>` - run a show immediately

View file

@ -1,116 +0,0 @@
"""
Veretube Python Show Bot example (veretube-bot 0.1.4)
Commands in chat:
!shows -> list existing shows
!mkshow -> create an example show scheduled ~2 minutes from now
!show <id> -> inspect a show from API
!runshow <id> -> trigger immediate run of a show
"""
from datetime import datetime, timedelta, timezone
import asyncio
import os
from veretube_bot import AsyncBot, BotAPIError
BOT_TOKEN = os.getenv("BOT_TOKEN", "TOKEN_HERE")
CHANNEL = os.getenv("CHANNEL", "CHANNEL_NAME_HERE")
SOCKET_URL = os.getenv("SOCKET_URL", "http://localhost:1337")
API_BASE = os.getenv("API_BASE", "http://localhost:8080/api/v1")
SHOW_TIMEZONE = os.getenv("SHOW_TIMEZONE", "UTC")
bot = AsyncBot(
token=BOT_TOKEN,
channel=CHANNEL,
socket_url=SOCKET_URL,
api_url=API_BASE,
)
def create_example_show_payload() -> dict:
# Schedule a couple minutes in the future to make testing easy.
scheduled_for = datetime.now(timezone.utc) + timedelta(minutes=2)
return {
"name": f"Python Demo Show {scheduled_for.strftime('%H:%M:%S')}",
"scheduled_for": scheduled_for.isoformat(),
"timezone": SHOW_TIMEZONE,
"recurrence": "none",
"fill_mode": "append",
"conflict_mode": "force",
"start_playback": False,
"status": "scheduled",
"playlist": [
{"type": "yt", "id": "dQw4w9WgXcQ", "pos": "end"},
{"type": "yt", "id": "9bZkp7q19f0", "pos": "end"},
],
}
@bot.on("chatMsg")
async def on_chat(data):
msg = (data.get("msg") or "").strip()
if msg == "!shows":
try:
shows = await bot.list_shows()
except BotAPIError as err:
await bot.send_message(f"shows error: {err}")
return
if not shows:
await bot.send_message("No shows configured")
return
summary = ", ".join([f"#{s['id']} {s['name']} ({s['status']})" for s in shows[:4]])
await bot.send_message(f"Shows: {summary}")
elif msg == "!mkshow":
try:
show = await bot.create_show(create_example_show_payload())
persisted = await bot.get_show(show["id"])
await bot.send_message(
f"Created show #{persisted['id']} status={persisted.get('status')} "
f"scheduled_for={persisted.get('scheduled_for')} timezone={persisted.get('timezone')}"
)
except BotAPIError as err:
await bot.send_message(f"create show error: {err}")
elif msg.startswith("!runshow "):
parts = msg.split()
if len(parts) != 2 or not parts[1].isdigit():
await bot.send_message("Usage: !runshow <show_id>")
return
show_id = int(parts[1])
try:
result = await bot.show_action(show_id, "run")
await bot.send_message(f"Show #{result['id']} run action complete, status={result['status']}")
except BotAPIError as err:
await bot.send_message(f"run show error: {err}")
elif msg.startswith("!show "):
parts = msg.split()
if len(parts) != 2 or not parts[1].isdigit():
await bot.send_message("Usage: !show <show_id>")
return
show_id = int(parts[1])
try:
show = await bot.get_show(show_id)
await bot.send_message(
f"Show #{show['id']}: status={show.get('status')} "
f"scheduled_for={show.get('scheduled_for')} timezone={show.get('timezone')}"
)
except BotAPIError as err:
await bot.send_message(f"show lookup error: {err}")
@bot.on("changeMedia")
async def on_media(data):
title = data.get("title", "(unknown)")
await bot.send_message(f"Now playing: {title}")
if __name__ == "__main__":
asyncio.run(bot.run())

View file

@ -1,23 +0,0 @@
aiohappyeyeballs==2.6.2
aiohttp==3.13.5
aiosignal==1.4.0
async-timeout==5.0.1
attrs==26.1.0
bidict==0.23.1
certifi==2026.5.20
charset-normalizer==3.4.7
frozenlist==1.8.0
h11==0.16.0
idna==3.15
multidict==6.7.1
propcache==0.5.2
python-engineio==4.13.1
python-socketio==5.16.1
requests==2.33.1
simple-websocket==1.1.0
typing_extensions==4.15.0
urllib3==2.7.0
veretube-bot==0.1.4
websocket-client==1.9.0
wsproto==1.3.2
yarl==1.24.2

View file

@ -1,26 +0,0 @@
from veretube_bot import Bot, Rank
bot = Bot(
token="TOKEN_HERE",
channel="CHANNEL_NAME_HERE",
socket_url="http://localhost:1337",
api_url="http://localhost:8080/api/v1"
)
@bot.on("chatMsg")
def on_chat(data):
if data["msg"] == "!playlist":
playlist = bot.api.get_playlist()
bot.send_message(f"{len(playlist['items'])} items in queue")
elif data["msg"].startswith("!kick "):
name = data["msg"].split(" ", 1)[1]
bot.kick(name, "Kicked by command")
elif data["msg"] == "!emotes":
emotes = bot.get_emotes()
print(emotes)
@bot.on("changeMedia")
def on_media(data):
bot.send_message(f"Now playing: {data['title']}")
bot.run()

View file

@ -1,13 +0,0 @@
bidict==0.23.1
certifi==2026.4.22
charset-normalizer==3.4.7
h11==0.16.0
idna==3.13
python-engineio==4.13.1
python-socketio==5.16.1
requests==2.33.1
simple-websocket==1.1.0
urllib3==2.6.3
veretube-bot==0.1.0
websocket-client==1.9.0
wsproto==1.3.2

37
filter.js Normal file
View file

@ -0,0 +1,37 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Filter = function(name, regex, flags, replace) {
this.name = name;
this.source = regex;
this.flags = flags;
this.regex = new RegExp(this.source, this.flags);
this.replace = replace;
this.active = true;
this.filterlinks = false;
}
Filter.prototype.pack = function() {
return {
name: this.name,
source: this.source,
flags: this.flags,
replace: this.replace,
active: this.active,
filterlinks: this.filterlinks
}
}
Filter.prototype.filter = function(text) {
return text.replace(this.regex, this.replace);
}
exports.Filter = Filter;

View file

@ -1,243 +0,0 @@
// ==UserScript==
// @name Google Drive Video Player for {SITENAME}
// @namespace gdcytube
// @description Play Google Drive videos on {SITENAME}
// {INCLUDE_BLOCK}
// @grant unsafeWindow
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @connect docs.google.com
// @run-at document-end
// @version 1.7.0
// ==/UserScript==
try {
function debug(message) {
try {
unsafeWindow.console.log('[Drive]', message);
} catch (error) {
unsafeWindow.console.error(error);
}
}
function httpRequest(opts) {
if (typeof GM_xmlhttpRequest === 'undefined') {
// Assume GM4.0
debug('Using GM4.0 GM.xmlHttpRequest');
GM.xmlHttpRequest(opts);
} else {
debug('Using old-style GM_xmlhttpRequest');
GM_xmlhttpRequest(opts);
}
}
var ITAG_QMAP = {
37: 1080,
46: 1080,
22: 720,
45: 720,
59: 480,
44: 480,
35: 480,
18: 360,
43: 360,
34: 360
};
var ITAG_CMAP = {
43: 'video/webm',
44: 'video/webm',
45: 'video/webm',
46: 'video/webm',
18: 'video/mp4',
22: 'video/mp4',
37: 'video/mp4',
59: 'video/mp4',
35: 'video/flv',
34: 'video/flv'
};
function getVideoInfo(id, cb) {
var url = 'https://docs.google.com/get_video_info?authuser='
+ '&docid=' + id
+ '&sle=true'
+ '&hl=en';
debug('Fetching ' + url);
httpRequest({
method: 'GET',
url: url,
onload: function (res) {
try {
debug('Got response ' + res.responseText);
if (res.status !== 200) {
debug('Response status not 200: ' + res.status);
return cb(
'Google Drive request failed: HTTP ' + res.status
);
}
var data = {};
var error;
// Google Santa sometimes eats login cookies and gets mad if there aren't any.
if(/accounts\.google\.com\/ServiceLogin/.test(res.responseText)){
error = 'Google Docs request failed: ' +
'This video requires you be logged into a Google account. ' +
'Open your Gmail in another tab and then refresh video.';
return cb(error);
}
res.responseText.split('&').forEach(function (kv) {
var pair = kv.split('=');
data[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
});
if (data.status === 'fail') {
error = 'Google Drive request failed: ' +
unescape(data.reason).replace(/\+/g, ' ');
return cb(error);
}
if (!data.fmt_stream_map) {
error = (
'Google has removed the video streams associated' +
' with this item. It can no longer be played.'
);
return cb(error);
}
data.links = {};
data.fmt_stream_map.split(',').forEach(function (item) {
var pair = item.split('|');
data.links[pair[0]] = pair[1];
});
data.videoMap = mapLinks(data.links);
cb(null, data);
} catch (error) {
unsafeWindow.console.error(error);
}
},
onerror: function () {
var error = 'Google Drive request failed: ' +
'metadata lookup HTTP request failed';
error.reason = 'HTTP_ONERROR';
return cb(error);
}
});
}
function mapLinks(links) {
var videos = {
1080: [],
720: [],
480: [],
360: []
};
Object.keys(links).forEach(function (itag) {
itag = parseInt(itag, 10);
if (!ITAG_QMAP.hasOwnProperty(itag)) {
return;
}
videos[ITAG_QMAP[itag]].push({
itag: itag,
contentType: ITAG_CMAP[itag],
link: links[itag]
});
});
return videos;
}
/*
* Greasemonkey 2.0 has this wonderful sandbox that attempts
* to prevent script developers from shooting themselves in
* the foot by removing the trigger from the gun, i.e. it's
* impossible to cross the boundary between the browser JS VM
* and the privileged sandbox that can run GM_xmlhttpRequest().
*
* So in this case, we have to resort to polling a special
* variable to see if getGoogleDriveMetadata needs to be called
* and deliver the result into another special variable that is
* being polled on the browser side.
*/
/*
* Browser side function -- sets gdUserscript.pollID to the
* ID of the Drive video to be queried and polls
* gdUserscript.pollResult for the result.
*/
function getGoogleDriveMetadata_GM(id, callback) {
debug('Setting GD poll ID to ' + id);
unsafeWindow.gdUserscript.pollID = id;
var tries = 0;
var i = setInterval(function () {
if (unsafeWindow.gdUserscript.pollResult) {
debug('Got result');
clearInterval(i);
var result = unsafeWindow.gdUserscript.pollResult;
unsafeWindow.gdUserscript.pollResult = null;
callback(result.error, result.result);
} else if (++tries > 100) {
// Took longer than 10 seconds, give up
clearInterval(i);
}
}, 100);
}
/*
* Sandbox side function -- polls gdUserscript.pollID for
* the ID of a Drive video to be queried, looks up the
* metadata, and stores it in gdUserscript.pollResult
*/
function setupGDPoll() {
unsafeWindow.gdUserscript = cloneInto({}, unsafeWindow);
var pollInterval = setInterval(function () {
if (unsafeWindow.gdUserscript.pollID) {
var id = unsafeWindow.gdUserscript.pollID;
unsafeWindow.gdUserscript.pollID = null;
debug('Polled and got ' + id);
getVideoInfo(id, function (error, data) {
unsafeWindow.gdUserscript.pollResult = cloneInto({
error: error,
result: data
}, unsafeWindow);
});
}
}, 1000);
}
var TM_COMPATIBLES = [
'Tampermonkey',
'Violentmonkey' // https://github.com/calzoneman/sync/issues/713
];
function isTampermonkeyCompatible() {
try {
return TM_COMPATIBLES.indexOf(GM_info.scriptHandler) >= 0;
} catch (error) {
return false;
}
}
if (isTampermonkeyCompatible()) {
unsafeWindow.getGoogleDriveMetadata = getVideoInfo;
} else {
debug('Using non-TM polling workaround');
unsafeWindow.getGoogleDriveMetadata = exportFunction(
getGoogleDriveMetadata_GM, unsafeWindow);
setupGDPoll();
}
unsafeWindow.console.log('Initialized userscript Google Drive player');
unsafeWindow.hasDriveUserscript = true;
// Checked against GS_VERSION from data.js
unsafeWindow.driveUserscriptVersion = '1.7';
} catch (error) {
unsafeWindow.console.error(error);
}

View file

@ -1,37 +0,0 @@
var fs = require('fs');
var path = require('path');
var sitename = process.argv[2];
var includes = process.argv.slice(3).map(function (include) {
return '// @include ' + include;
}).join('\n');
var lines = String(fs.readFileSync(
path.resolve(__dirname, 'cytube-google-drive.user.js'))).split('\n');
var userscriptOutput = '';
var metaOutput = '';
lines.forEach(function (line) {
if (line.match(/\{INCLUDE_BLOCK\}/)) {
userscriptOutput += includes + '\n';
} else if (line.match(/\{SITENAME\}/)) {
line = line.replace(/\{SITENAME\}/, sitename) + '\n';
userscriptOutput += line;
metaOutput += line;
} else {
if (line.match(/==\/?UserScript|@name|@version/)) {
metaOutput += line + '\n';
}
userscriptOutput += line + '\n';
}
});
fs.writeFileSync(
path.join(__dirname, '..', 'www', 'js', 'cytube-google-drive.user.js'),
userscriptOutput
);
fs.writeFileSync(
path.join(__dirname, '..', 'www', 'js', 'cytube-google-drive.meta.js'),
metaOutput
);

497
get-info.js Normal file
View file

@ -0,0 +1,497 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var http = require("http");
var https = require("https");
var Logger = require("./logger.js");
var Media = require("./media.js").Media;
var CustomEmbedFilter = require("./customembed").filter;
module.exports = function (Server) {
function urlRetrieve(transport, options, callback) {
var req = transport.request(options, function (res) {
var buffer = "";
res.setEncoding("utf-8");
res.on("data", function (chunk) {
buffer += chunk;
});
res.on("end", function () {
callback(res.statusCode, buffer);
});
});
req.end();
}
var Getters = {
/* youtube.com */
yt: function (id, callback) {
if(Server.cfg["enable-ytv3"] && Server.cfg["ytv3apikey"]) {
Getters["ytv3"](id, callback);
return;
}
var options = {
host: "gdata.youtube.com",
port: 443,
path: "/feeds/api/videos/" + id + "?v=2&alt=json",
method: "GET",
dataType: "jsonp",
timeout: 1000
};
if(Server.cfg["ytv2devkey"]) {
options.headers = {
"X-Gdata-Key": "key=" + Server.cfg["ytv2devkey"]
};
}
urlRetrieve(https, options, function (status, data) {
if(status === 404) {
callback("Video not found", null);
return;
} else if(status === 403) {
callback("Private video", null);
return;
} else if(status !== 200) {
callback(true, null);
return;
}
try {
data = JSON.parse(data);
var seconds = data.entry.media$group.yt$duration.seconds;
var title = data.entry.title.$t;
var media = new Media(id, title, seconds, "yt");
callback(false, media);
} catch(e) {
// Gdata version 2 has the rather silly habit of
// returning error codes in XML when I explicitly asked
// for JSON
var m = buffer.match(/<internalReason>([^<]+)<\/internalReason>/);
if(m === null)
m = buffer.match(/<code>([^<]+)<\/code>/);
var err = true;
if(m) {
if(m[1] === "too_many_recent_calls") {
err = "YouTube is throttling the server right "+
"now for making too many requests. "+
"Please try again in a moment.";
} else {
err = m[1];
}
}
callback(err, null);
}
});
},
/* youtube.com API v3 (requires API key) */
ytv3: function (id, callback) {
var params = [
"part=" + encodeURIComponent("id,snippet,contentDetails"),
"id=" + id,
"key=" + Server.cfg["ytapikey"]
].join("&");
var options = {
host: "www.googleapis.com",
port: 443,
path: "/youtube/v3/videos?" + params,
method: "GET",
dataType: "jsonp",
timeout: 1000
};
urlRetrieve(https, options, function (status, data) {
if(status !== 200) {
callback(true, null);
return;
}
try {
data = JSON.parse(data);
// I am a bit disappointed that the API v3 just doesn't
// return anything in any error case
if(data.pageInfo.totalResults !== 1) {
callback(true, null);
return;
}
var vid = data.items[0];
var title = vid.snippet.title;
// No, it's not possible to get a number representing
// the video length. Instead, I get a time of the format
// PT#M#S which represents
// "Period of Time" # Minutes, # Seconds
var m = vid.contentDetails.duration.match(/PT(\d+)M(\d+)S/);
var seconds = parseInt(m[1]) * 60 + parseInt(m[2]);
var media = new Media(id, title, seconds, "yt");
callback(false, media);
} catch(e) {
callback(true, media);
}
});
},
/* youtube.com playlists */
yp: function (id, callback, url) {
var path = "/feeds/api/playlists/" + id + "?v=2&alt=json";
// YouTube only returns 25 at a time, so I have to keep asking
// for more with the URL they give me
if(url !== undefined) {
path = "/" + url.split("gdata.youtube.com")[1];
}
var options = {
host: "gdata.youtube.com",
port: 443,
path: path,
method: "GET",
dataType: "jsonp",
timeout: 1000
};
if(Server.cfg["ytv2devkey"]) {
options.headers = {
"X-Gdata-Key": "key=" + Server.cfg["ytv2devkey"]
};
}
urlRetrieve(https, options, function (status, data) {
if(status === 404) {
callback("Playlist not found", null);
return;
} else if(status === 403) {
callback("Playlist is private", null);
return;
} else if(status !== 200) {
callback(true, null);
}
try {
data = JSON.parse(data);
var vids = [];
for(var i in data.feed.entry) {
try {
var item = data.feed.entry[i];
var id = item.media$group.yt$videoid.$t;
var title = item.title.$t;
var seconds = item.media$group.yt$duration.seconds;
var media = new Media(id, title, seconds, "yt");
vids.push(media);
} catch(e) {
}
}
callback(false, vids);
var links = data.feed.link;
for(var i in links) {
if(links[i].rel === "next")
Getters["yp"](id, callback, links[i].href);
}
} catch(e) {
callback(true, null);
}
});
},
/* youtube.com search */
ytSearch: function (terms, callback) {
for(var i in terms)
terms[i] = encodeURIComponent(terms[i]);
var query = terms.join("+");
var options = {
host: "gdata.youtube.com",
port: 443,
path: "/feeds/api/videos/?q=" + query + "&v=2&alt=json",
method: "GET",
dataType: "jsonp",
timeout: 1000
};
if(Server.cfg["ytv2devkey"]) {
options.headers = {
"X-Gdata-Key": "key=" + Server.cfg["ytv2devkey"]
};
}
urlRetrieve(https, options, function (status, data) {
if(status !== 200) {
callback(true, null);
return;
}
try {
data = JSON.parse(data);
var vids = [];
for(var i in data.feed.entry) {
try {
var item = data.feed.entry[i];
var id = item.media$group.yt$videoid.$t;
var title = item.title.$t;
var seconds = item.media$group.yt$duration.seconds;
var media = new Media(id, title, seconds, "yt");
media.thumb = item.media$group.media$thumbnail[0];
vids.push(media);
} catch(e) {
}
}
callback(false, vids);
} catch(e) {
callback(true, null);
}
});
},
/* vimeo.com */
vi: function (id, callback) {
var options = {
host: "vimeo.com",
port: 443,
path: "/api/v2/video/" + id + ".json",
method: "GET",
dataType: "jsonp",
timeout: 1000
};
urlRetrieve(https, options, function (status, data) {
if(status === 404) {
callback("Video not found", null);
return;
} else if(status === 403) {
callback("Private video", null);
return;
} else if(status !== 200) {
callback(true, null);
return;
}
try {
data = JSON.parse(data);
data = data[0];
var seconds = data.duration;
var title = data.title;
var media = new Media(id, title, seconds, "vi");
callback(false, media);
} catch(e) {
var err = true;
if(buffer.match(/not found/))
err = "Video not found";
callback(err, null);
}
});
},
/* dailymotion.com */
dm: function (id, callback) {
// Dailymotion's API is an example of an API done right
// - Supports SSL
// - I can ask for exactly which fields I want
// - URL is simple
// - Field names are sensible
// Other media providers take notes, please
var options = {
host: "api.dailymotion.com",
port: 443,
path: "/video/" + id + "?fields=duration,title",
method: "GET",
dataType: "jsonp",
timeout: 1000
};
urlRetrieve(https, options, function (status, data) {
if(status !== 200) {
callback(true, null);
return;
}
try {
data = JSON.parse(data);
var title = data.title;
var seconds = data.duration;
if(title === "Deleted video" && seconds === 10) {
callback("Video not found", null);
return;
}
var media = new Media(id, title, seconds, "dm");
callback(false, media);
} catch(e) {
callback(err, null);
}
});
},
/* soundcloud.com */
sc: function (id, callback) {
// Soundcloud's API is badly designed and badly documented
// In order to lookup track data from a URL, I have to first
// make a call to /resolve to get the track id, then make a second
// call to /tracks/{track.id} to actally get useful data
// This is a waste of bandwidth and a pain in the ass
const SC_CLIENT = "2e0c82ab5a020f3a7509318146128abd";
var options = {
host: "api.soundcloud.com",
port: 443,
path: "/resolve.json?url=" + id + "&client_id=" + SC_CLIENT,
method: "GET",
dataType: "jsonp",
timeout: 1000
};
urlRetrieve(https, options, function (status, data) {
if(status === 404) {
callback("Sound not found", null);
return;
} else if(status !== 302) {
callback(true, null);
return;
}
var track = null;
try {
data = JSON.parse(data);
track = data.location;
} catch(e) {
callback(true, null);
return;
}
var options2 = {
host: "api.soundcloud.com",
port: 443,
path: track,
method: "GET",
dataType: "jsonp",
timeout: 1000
};
// I want to get off async's wild ride
urlRetrieve(https, options2, function (status, data) {
if(status !== 200) {
callback(true, null);
return;
}
try {
data = JSON.parse(data);
// Duration is in ms, but I want s
var seconds = data.duration / 1000;
var title = data.title;
var media = new Media(id, title, seconds, "sc");
callback(false, media);
} catch(e) {
callback(true, null);
}
});
});
},
/* livestream.com */
li: function (id, callback) {
var title = "Livestream.com - " + id;
var media = new Media(id, title, "--:--", "li");
callback(false, media);
},
/* twitch.tv */
tw: function (id, callback) {
var title = "Twitch.tv - " + id;
var media = new Media(id, title, "--:--", "tw");
callback(false, media);
},
/* justin.tv */
jt: function (id, callback) {
var title = "Justin.tv - " + id;
var media = new Media(id, title, "--:--", "jt");
callback(false, media);
},
/* ustream.tv */
us: function (id, callback) {
var options = {
host: "www.ustream.tv",
port: 80,
path: "/" + id,
method: "GET",
timeout: 1000
};
urlRetrieve(http, options, function (status, data) {
if(status !== 200) {
callback(true, null);
return;
}
// Regexing the ID out of the HTML because
// Ustream's API is so horribly documented
// I literally could not figure out how to retrieve
// this information.
//
// [](/eatadick)
var m = data.match(/cid":([0-9]+)/);
if(m) {
var title = "Ustream.tv - " + id;
var media = new Media(m[1], title, "--:--", "us");
callback(false, media);
} else {
callback(true, null);
}
});
},
/* JWPlayer */
jw: function (id, callback) {
var title = "JWPlayer - " + id;
var media = new Media(id, title, "--:--", "jw");
callback(false, media);
},
/* rtmp stream */
rt: function (id, callback) {
var title = "Livestream";
var media = new Media(id, title, "--:--", "rt");
callback(false, media);
},
/* imgur.com albums */
im: function (id, callback) {
var title = "Imgur Album - " + id;
var media = new Media(id, title, "--:--", "im");
callback(false, media);
},
/* custom embed */
cu: function (id, callback) {
id = CustomEmbedFilter(id);
var media = new Media(id, "Custom Media", "--:--", "cu");
callback(false, media);
}
};
return {
Getters: Getters,
getMedia: function (id, type, callback) {
if(type in this.Getters) {
this.Getters[type](id, callback);
}
}
};
}

View file

@ -1,98 +0,0 @@
#!/usr/bin/env node
const ver = process.version.match(/v(\d+)\.\d+\.\d+/);
if (parseInt(ver[1], 10) < 12) {
console.error(
`node.js ${process.version} is not supported. ` +
'CyTube requires node v12 or later.'
)
process.exit(1);
}
checkPlayerExists();
const args = parseArgs();
if (args.has('--daemonize')) {
fork();
} else {
try {
require('./lib/main');
} catch (err) {
console.error('FATAL: Failed to require() lib/main.js');
handleStartupError(err);
}
}
function fork() {
try {
console.log('Warning: --daemonize support is experimental. Use with caution.');
const spawn = require('child_process').spawn;
const path = require('path');
const main = path.resolve(__dirname, 'lib', 'main.js');
const child = spawn(process.argv[0], [main], {
detached: true,
stdio: 'ignore' // TODO: support setting stdout/stderr logfile
});
child.unref();
console.log('Forked with PID ' + child.pid);
} catch (error) {
console.error('FATAL: Failed to fork lib/main.js');
handleStartupError(error);
}
}
function handleStartupError(err) {
if (/module version mismatch/i.test(err.message)) {
console.error('Module version mismatch, try running `npm rebuild` or ' +
'removing the node_modules folder and re-running ' +
'`npm install`');
} else {
console.error('Possible causes:\n' +
' * You haven\'t run `npm run build-server` to regenerate ' +
'the runtime\n' +
' * You\'ve upgraded node/npm and haven\'t rebuilt dependencies ' +
'(try `npm rebuild` or `rm -rf node_modules && npm install`)\n' +
' * A dependency failed to install correctly (check the output ' +
'of `npm install` next time)');
}
console.error(err.stack);
process.exit(1);
}
function parseArgs() {
const args = new Map();
for (var i = 2; i < process.argv.length; i++) {
if (/^--/.test(process.argv[i])) {
var val;
if (i+1 < process.argv.length) val = process.argv[i+1];
else val = null;
args.set(process.argv[i], val);
}
}
return args;
}
function checkPlayerExists() {
const fs = require('fs');
const path = require('path');
const playerDotJs = path.join(__dirname, 'www', 'js', 'player.js');
if (!fs.existsSync(playerDotJs)) {
console.error(
'Missing video player: www/js/player.js. This should have been ' +
'automatically generated by the postinstall step of ' +
'`npm install`, but you can manually regenerate it by running ' +
'`npm run build-player`'
);
process.exit(1);
}
}

View file

@ -1,603 +0,0 @@
const assert = require('assert');
const KickbanModule = require('../../lib/channel/kickban');
const database = require('../../lib/database');
const Promise = require('bluebird');
const testDB = require('../testutil/db').testDB;
database.init(testDB);
describe('KickbanModule', () => {
const channelName = `test_${Math.random().toString(31).substring(2)}`;
let mockChannel;
let mockUser;
let kickban;
beforeEach(() => {
mockChannel = {
name: channelName,
refCounter: {
ref() { },
unref() { }
},
logger: {
log() { }
},
modules: {
permissions: {
canBan() {
return true;
}
}
},
users: []
};
mockUser = {
getName() {
return 'The_Admin';
},
getLowerName() {
return 'the_admin';
},
socket: {
emit(frame) {
if (frame === 'errorMsg') {
throw new Error(arguments[1].msg);
}
}
},
account: {
effectiveRank: 3
}
};
kickban = new KickbanModule(mockChannel);
});
afterEach(async () => {
await database.getDB().runTransaction(async tx => {
await tx.table('channel_bans')
.where({ channel: channelName })
.del();
await tx.table('channel_ranks')
.where({ channel: channelName })
.del();
});
});
describe('#handleCmdBan', () => {
it('inserts a valid ban', done => {
let kicked = false;
mockChannel.refCounter.unref = () => {
assert(kicked, 'Expected user to be kicked');
database.getDB().runTransaction(async tx => {
const ban = await tx.table('channel_bans')
.where({
channel: channelName,
name: 'test_user'
})
.first();
assert.strictEqual(ban.ip, '*');
assert.strictEqual(ban.reason, 'because reasons');
assert.strictEqual(ban.bannedby, mockUser.getName());
done();
});
};
mockChannel.users = [{
getLowerName() {
return 'test_user';
},
kick(reason) {
assert.strictEqual(reason, "You're banned!");
kicked = true;
}
}];
kickban.handleCmdBan(
mockUser,
'/ban test_user because reasons',
{}
);
});
it('rejects if the username is invalid', done => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'Invalid username'
);
done();
}
};
kickban.handleCmdBan(
mockUser,
'/ban test_user<>%$# because reasons',
{}
);
});
it('rejects if the user does not have ban permission', done => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'You do not have ban permissions on this channel'
);
done();
}
};
mockChannel.modules.permissions.canBan = () => false;
kickban.handleCmdBan(
mockUser,
'/ban test_user because reasons',
{}
);
});
it('rejects if the user tries to ban themselves', done => {
let costanza = false;
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'You cannot ban yourself'
);
if (!costanza) {
throw new Error('Expected costanza for banning self');
}
done();
} else if (frame === 'costanza') {
assert.strictEqual(
obj.msg,
"You can't ban yourself"
);
costanza = true;
}
};
kickban.handleCmdBan(
mockUser,
'/ban the_Admin because reasons',
{}
);
});
it('rejects if the user is ranked below the ban recipient', done => {
database.getDB().runTransaction(tx => {
return tx.table('channel_ranks')
.insert({
channel: channelName,
name: 'test_user',
rank: 5
});
}).then(() => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
"You don't have permission to ban test_user"
);
done();
}
};
kickban.handleCmdBan(
mockUser,
'/ban test_user because reasons',
{}
);
});
});
it('rejects if the the ban recipient is already banned', done => {
database.getDB().runTransaction(tx => {
return tx.table('channel_bans')
.insert({
channel: channelName,
name: 'test_user',
ip: '*',
bannedby: 'somebody',
reason: 'I dunno'
});
}).then(() => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'test_user is already banned'
);
done();
}
};
kickban.handleCmdBan(
mockUser,
'/ban test_user because reasons',
{}
);
});
});
});
describe('#handleCmdIPBan', () => {
beforeEach(async () => {
await database.getDB().runTransaction(async tx => {
await tx.table('aliases')
.insert([{
name: 'test_user',
ip: '1.2.3.4',
time: Date.now()
}]);
});
});
afterEach(async () => {
await database.getDB().runTransaction(async tx => {
await tx.table('aliases')
.where({ name: 'test_user' })
.orWhere({ ip: '1.2.3.4' })
.del();
});
});
it('inserts a valid ban', done => {
let firstUserKicked = false;
let secondUserKicked = false;
mockChannel.refCounter.unref = () => {
assert(firstUserKicked, 'Expected banned user to be kicked');
assert(
secondUserKicked,
'Expected user with banned IP to be kicked'
);
database.getDB().runTransaction(async tx => {
const nameBan = await tx.table('channel_bans')
.where({
channel: channelName,
name: 'test_user',
ip: '*'
})
.first();
assert.strictEqual(nameBan.reason, 'because reasons');
assert.strictEqual(nameBan.bannedby, mockUser.getName());
const ipBan = await tx.table('channel_bans')
.where({
channel: channelName,
ip: '1.2.3.4'
})
.first();
assert.strictEqual(ipBan.name, 'test_user');
assert.strictEqual(ipBan.reason, 'because reasons');
assert.strictEqual(ipBan.bannedby, mockUser.getName());
done();
});
};
mockChannel.users = [{
getLowerName() {
return 'test_user';
},
realip: '1.2.3.4',
kick(reason) {
assert.strictEqual(reason, "You're banned!");
firstUserKicked = true;
}
}, {
getLowerName() {
return 'second_user_same_ip';
},
realip: '1.2.3.4',
kick(reason) {
assert.strictEqual(reason, "You're banned!");
secondUserKicked = true;
}
}];
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user because reasons',
{}
);
});
it('inserts a valid range ban', done => {
mockChannel.refCounter.unref = () => {
database.getDB().runTransaction(async tx => {
const ipBan = await tx.table('channel_bans')
.where({
channel: channelName,
ip: '1.2.3'
})
.first();
assert.strictEqual(ipBan.name, 'test_user');
assert.strictEqual(ipBan.reason, 'because reasons');
assert.strictEqual(ipBan.bannedby, mockUser.getName());
done();
});
};
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user range because reasons',
{}
);
});
it('inserts a valid wide-range ban', done => {
mockChannel.refCounter.unref = () => {
database.getDB().runTransaction(async tx => {
const ipBan = await tx.table('channel_bans')
.where({
channel: channelName,
ip: '1.2'
})
.first();
assert.strictEqual(ipBan.name, 'test_user');
assert.strictEqual(ipBan.reason, 'because reasons');
assert.strictEqual(ipBan.bannedby, mockUser.getName());
done();
});
};
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user wrange because reasons',
{}
);
});
it('inserts a valid IPv6 ban', done => {
const longIP = require('../../lib/utilities').expandIPv6('::abcd');
mockChannel.refCounter.unref = () => {
database.getDB().runTransaction(async tx => {
const ipBan = await tx.table('channel_bans')
.where({
channel: channelName,
ip: longIP
})
.first();
assert.strictEqual(ipBan.name, 'test_user');
assert.strictEqual(ipBan.reason, 'because reasons');
assert.strictEqual(ipBan.bannedby, mockUser.getName());
done();
});
};
database.getDB().runTransaction(async tx => {
await tx.table('aliases')
.insert({
name: 'test_user',
ip: longIP,
time: Date.now()
});
}).then(() => {
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user because reasons',
{}
);
});
});
it('rejects if the user does not have ban permission', done => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'You do not have ban permissions on this channel'
);
done();
}
};
mockChannel.modules.permissions.canBan = () => false;
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user because reasons',
{}
);
});
it('rejects if the user tries to ban themselves', done => {
let costanza = false;
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'You cannot ban yourself'
);
if (!costanza) {
throw new Error('Expected costanza for banning self');
}
done();
} else if (frame === 'costanza') {
assert.strictEqual(
obj.msg,
"You can't ban yourself"
);
costanza = true;
}
};
kickban.handleCmdIPBan(
mockUser,
'/ipban the_Admin because reasons',
{}
);
});
it('rejects if the user is ranked below the ban recipient', done => {
database.getDB().runTransaction(tx => {
return tx.table('channel_ranks')
.insert({
channel: channelName,
name: 'test_user',
rank: 5
});
}).then(() => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
"You don't have permission to ban IP " +
"09l.TFb.5To.HBB"
);
done();
}
};
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user because reasons',
{}
);
});
});
it('rejects if the user is ranked below an alias of the ban recipient', done => {
database.getDB().runTransaction(async tx => {
await tx.table('channel_ranks')
.insert({
channel: channelName,
name: 'another_user',
rank: 5
});
await tx.table('aliases')
.insert({
name: 'another_user',
ip: '1.2.3.3', // different IP, same /24 range
time: Date.now()
});
}).then(() => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
"You don't have permission to ban IP " +
"09l.TFb.5To.*"
);
done();
}
};
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user range because reasons',
{}
);
});
});
it('rejects if the the ban recipient IP is already banned', done => {
database.getDB().runTransaction(tx => {
return tx.table('channel_bans')
.insert({
channel: channelName,
name: 'another_user',
ip: '1.2.3.4',
bannedby: 'somebody',
reason: 'I dunno'
});
}).then(() => {
mockUser.socket.emit = (frame, obj) => {
if (frame === 'errorMsg') {
assert.strictEqual(
obj.msg,
'09l.TFb.5To.HBB is already banned'
);
done();
}
};
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user because reasons',
{}
);
});
});
it('still adds the IP ban even if the name is already banned', done => {
mockChannel.refCounter.unref = () => {
database.getDB().runTransaction(async tx => {
const ipBan = await tx.table('channel_bans')
.where({
channel: channelName,
ip: '1.2.3.4'
})
.first();
assert.strictEqual(ipBan.name, 'test_user');
assert.strictEqual(ipBan.reason, 'because reasons');
assert.strictEqual(ipBan.bannedby, mockUser.getName());
done();
});
};
database.getDB().runTransaction(tx => {
return tx.table('channel_bans')
.insert({
channel: channelName,
name: 'test_user',
ip: '*',
bannedby: 'somebody',
reason: 'I dunno'
});
}).then(() => {
kickban.handleCmdIPBan(
mockUser,
'/ipban test_user because reasons',
{}
);
});
});
});
});

View file

@ -1,109 +0,0 @@
const assert = require('assert');
const { BannedChannelsController } = require('../../lib/controller/banned-channels');
const dbChannels = require('../../lib/database/channels');
const testDB = require('../testutil/db').testDB;
const { EventEmitter } = require('events');
require('../../lib/database').init(testDB);
const testBan = {
name: 'ban_test_1',
externalReason: 'because I said so',
internalReason: 'illegal content',
bannedBy: 'admin'
};
async function cleanupTestBan() {
return dbChannels.removeBannedChannel(testBan.name);
}
describe('BannedChannelsController', () => {
let controller;
let messages;
beforeEach(async () => {
await cleanupTestBan();
messages = new EventEmitter();
controller = new BannedChannelsController(
dbChannels,
messages
);
});
afterEach(async () => {
await cleanupTestBan();
});
it('bans a channel', async () => {
assert.strictEqual(await controller.getBannedChannel(testBan.name), null);
let received = null;
messages.once('ChannelBanned', cb => {
received = cb;
});
await controller.banChannel(testBan);
let info = await controller.getBannedChannel(testBan.name);
for (let field of Object.keys(testBan)) {
// Consider renaming parameter to avoid this branch
if (field === 'name') {
assert.strictEqual(info.channelName, testBan.name);
} else {
assert.strictEqual(info[field], testBan[field]);
}
}
assert.notEqual(received, null);
assert.strictEqual(received.channel, testBan.name);
assert.strictEqual(received.externalReason, testBan.externalReason);
});
it('updates an existing ban', async () => {
let received = [];
messages.on('ChannelBanned', cb => {
received.push(cb);
});
await controller.banChannel(testBan);
let testBan2 = { ...testBan, externalReason: 'because of reasons' };
await controller.banChannel(testBan2);
let info = await controller.getBannedChannel(testBan2.name);
for (let field of Object.keys(testBan2)) {
// Consider renaming parameter to avoid this branch
if (field === 'name') {
assert.strictEqual(info.channelName, testBan2.name);
} else {
assert.strictEqual(info[field], testBan2[field]);
}
}
assert.deepStrictEqual(received, [
{
channel: testBan.name,
externalReason: testBan.externalReason
},
{
channel: testBan2.name,
externalReason: testBan2.externalReason
},
]);
});
it('unbans a channel', async () => {
let received = null;
messages.once('ChannelUnbanned', cb => {
received = cb;
});
await controller.banChannel(testBan);
await controller.unbanChannel(testBan.name, testBan.bannedBy);
let info = await controller.getBannedChannel(testBan.name);
assert.strictEqual(info, null);
assert.notEqual(received, null);
assert.strictEqual(received.channel, testBan.name);
});
});

View file

@ -1,88 +0,0 @@
const assert = require('assert');
const { testDB } = require('../testutil/db');
const accounts = require('../../lib/database/accounts');
require('../../lib/database').init(testDB);
describe('AccountsDatabase', () => {
describe('#verifyLogin', () => {
let ip = '169.254.111.111';
let user;
let password;
beforeEach(async () => {
return testDB.knex.table('users')
.where({ ip })
.delete();
});
beforeEach(done => {
user = `u${Math.random().toString(31).substring(2)}`;
password = 'int!gration_Test';
accounts.register(
user,
password,
'',
ip,
(error, res) => {
if (error) {
throw error;
}
console.log(`Created test user ${user}`);
done();
}
)
});
it('verifies a correct login', done => {
accounts.verifyLogin(
user,
password,
(error, res) => {
if (error) {
throw error;
}
assert.strictEqual(res.name, user);
done();
}
);
});
it('verifies a correct login with an older hash', done => {
testDB.knex.table('users')
.where({ name: user })
.update({
// 'test' hashed with old version of bcrypt module
password: '$2b$10$2oCG7O9FFqie7T8O33yQDugFPS0NqkgbQjtThTs7Jr8E1QOzdRruK'
})
.then(() => {
accounts.verifyLogin(
user,
'test',
(error, res) => {
if (error) {
throw error;
}
assert.strictEqual(res.name, user);
done();
}
);
});
});
it('rejects an incorrect login', done => {
accounts.verifyLogin(
user,
'not the right password',
(error, res) => {
assert.strictEqual(error, 'Invalid username/password combination');
done();
}
);
});
});
});

View file

@ -1,76 +0,0 @@
const assert = require('assert');
const AliasesDB = require('../../lib/db/aliases').AliasesDB;
const testDB = require('../testutil/db').testDB;
const aliasesDB = new AliasesDB(testDB);
const testIPs = ['111.111.111.111', '111.111.111.222'];
const testNames = ['itest1', 'itest2'];
function cleanup() {
return testDB.knex.table('aliases')
.where('ip', 'in', testIPs)
.del()
.then(() => {
return testDB.knex.table('aliases')
.where('name', 'in', testNames)
.del();
});
}
function addSomeAliases() {
return cleanup().then(() => {
return testDB.knex.table('aliases')
.insert([
{ ip: testIPs[0], name: testNames[0], time: Date.now() },
{ ip: testIPs[0], name: testNames[1], time: Date.now() },
{ ip: testIPs[1], name: testNames[1], time: Date.now() }
]);
});
}
describe('AliasesDB', () => {
describe('#addAlias', () => {
beforeEach(cleanup);
afterEach(cleanup);
it('adds a new alias', () => {
return aliasesDB.addAlias(testIPs[0], testNames[0])
.then(() => {
return testDB.knex.table('aliases')
.where({ ip: testIPs[0], name: testNames[0] })
.select()
.then(rows => {
assert.strictEqual(rows.length, 1, 'expected 1 row');
});
});
});
});
describe('#getAliasesByIP', () => {
beforeEach(addSomeAliases);
afterEach(cleanup);
it('retrieves aliases by IP', () => {
return aliasesDB.getAliasesByIP(testIPs[0])
.then(names => assert.deepStrictEqual(
names.sort(), testNames.sort()));
});
it('retrieves aliases by partial IP', () => {
return aliasesDB.getAliasesByIP(testIPs[0].substring(4))
.then(names => assert.deepStrictEqual(
names.sort(), testNames.sort()));
});
});
describe('#getIPsByName', () => {
beforeEach(addSomeAliases);
afterEach(cleanup);
it('retrieves IPs by name', () => {
return aliasesDB.getIPsByName(testNames[1])
.then(ips => assert.deepStrictEqual(
ips.sort(), testIPs.sort()));
});
});
});

View file

@ -1,92 +0,0 @@
const assert = require('assert');
const GlobalBanDB = require('../../lib/db/globalban').GlobalBanDB;
const testDB = require('../testutil/db').testDB;
const { o } = require('../testutil/o');
const globalBanDB = new GlobalBanDB(testDB);
const testBan = { ip: '8.8.8.8', reason: 'test' };
function cleanupTestBan() {
return testDB.knex.table('global_bans')
.where({ ip: testBan.ip })
.del();
}
function setupTestBan() {
return testDB.knex.table('global_bans')
.insert(testBan)
.catch(error => {
if (error.code === 'ER_DUP_ENTRY') {
return testDB.knex.table('global_bans')
.where({ ip: testBan.ip })
.update({ reason: testBan.reason });
}
throw error;
});
}
describe('GlobalBanDB', () => {
describe('#listGlobalBans', () => {
beforeEach(setupTestBan);
afterEach(cleanupTestBan);
it('lists existing IP bans', () => {
return globalBanDB.listGlobalBans().then(bans => {
assert.deepStrictEqual([{
ip: '8.8.8.8',
reason: 'test'
}], bans.map(o));
});
});
});
describe('#addGlobalIPBan', () => {
beforeEach(cleanupTestBan);
afterEach(cleanupTestBan);
it('adds a new ban', () => {
return globalBanDB.addGlobalIPBan('8.8.8.8', 'test').then(() => {
return testDB.knex.table('global_bans')
.where({ ip: '8.8.8.8' })
.select()
.then(rows => {
assert.strictEqual(rows.length, 1, 'Expected 1 row');
assert.strictEqual(rows[0].ip, '8.8.8.8');
assert.strictEqual(rows[0].reason, 'test');
});
});
});
it('updates the reason on an existing ban', () => {
return globalBanDB.addGlobalIPBan('8.8.8.8', 'test').then(() => {
return globalBanDB.addGlobalIPBan('8.8.8.8', 'different').then(() => {
return testDB.knex.table('global_bans')
.where({ ip: '8.8.8.8' })
.select()
.then(rows => {
assert.strictEqual(rows.length, 1, 'Expected 1 row');
assert.strictEqual(rows[0].ip, '8.8.8.8');
assert.strictEqual(rows[0].reason, 'different');
});
});
});
});
});
describe('#removeGlobalIPBan', () => {
beforeEach(setupTestBan);
afterEach(cleanupTestBan);
it('removes a ban', () => {
return globalBanDB.removeGlobalIPBan('8.8.8.8').then(() => {
return testDB.knex.table('global_bans')
.where({ ip: '8.8.8.8' })
.select()
.then(rows => {
assert.strictEqual(rows.length, 0, 'Expected 0 rows');
});
});
});
});
});

View file

@ -1,144 +0,0 @@
const assert = require('assert');
const PasswordResetDB = require('../../lib/db/password-reset').PasswordResetDB;
const testDB = require('../testutil/db').testDB;
const { o } = require('../testutil/o');
const passwordResetDB = new PasswordResetDB(testDB);
function cleanup() {
return testDB.knex.table('password_reset').del();
}
describe('PasswordResetDB', () => {
describe('#insert', () => {
beforeEach(cleanup);
const params = {
ip: '1.2.3.4',
name: 'testing',
email: 'test@example.com',
hash: 'abcdef',
expire: 5678
};
it('adds a new password reset', () => {
return passwordResetDB.insert(params).then(() => {
return testDB.knex.table('password_reset')
.where({ name: 'testing' })
.select();
}).then(rows => {
assert.strictEqual(rows.length, 1);
assert.deepStrictEqual(o(rows[0]), params);
});
});
it('overwrites an existing reset for the same name', () => {
return passwordResetDB.insert(params).then(() => {
params.ip = '5.6.7.8';
params.email = 'somethingelse@example.com';
params.hash = 'qwertyuiop';
params.expire = 9999;
return passwordResetDB.insert(params);
}).then(() => {
return testDB.knex.table('password_reset')
.where({ name: 'testing' })
.select();
}).then(rows => {
assert.strictEqual(rows.length, 1);
assert.deepStrictEqual(o(rows[0]), params);
});
});
});
describe('#get', () => {
const reset = {
ip: '1.2.3.4',
name: 'testing',
email: 'test@example.com',
hash: 'abcdef',
expire: 5678
};
beforeEach(() => cleanup().then(() => {
return testDB.knex.table('password_reset').insert(reset);
}));
it('gets a password reset by hash', () => {
return passwordResetDB.get(reset.hash).then(result => {
assert.deepStrictEqual(o(result), reset);
});
});
it('throws when no reset exists for the input', () => {
return passwordResetDB.get('lalala').then(() => {
assert.fail('Expected not found error');
}).catch(error => {
assert.strictEqual(
error.message,
'No password reset found for hash lalala'
);
});
});
});
describe('#delete', () => {
const reset = {
ip: '1.2.3.4',
name: 'testing',
email: 'test@example.com',
hash: 'abcdef',
expire: 5678
};
beforeEach(() => cleanup().then(() => {
return testDB.knex.table('password_reset').insert(reset);
}));
it('deletes a password reset by hash', () => {
return passwordResetDB.delete(reset.hash).then(() => {
return testDB.knex.table('password_reset')
.where({ name: 'testing' })
.select();
}).then(rows => {
assert.strictEqual(rows.length, 0);
});
});
});
describe('#cleanup', () => {
const now = Date.now();
const reset1 = {
ip: '1.2.3.4',
name: 'testing',
email: 'test@example.com',
hash: 'abcdef',
expire: now - 25 * 60 * 60 * 1000
};
const reset2 = {
ip: '5.6.7.8',
name: 'testing2',
email: 'test@example.com',
hash: 'abcdef',
expire: now
};
beforeEach(() => cleanup().then(() => {
return testDB.knex.table('password_reset')
.insert([reset1, reset2]);
}));
it('cleans up old password resets', () => {
return passwordResetDB.cleanup().then(() => {
return testDB.knex.table('password_reset')
.whereIn('name', ['testing1', 'testing2'])
.select();
}).then(rows => {
assert.strictEqual(rows.length, 1);
assert.deepStrictEqual(o(rows[0]), reset2);
});
});
});
});

View file

@ -1,136 +0,0 @@
const assert = require('assert');
const KickbanModule = require('../../lib/channel/kickban');
const database = require('../../lib/database');
const dbChannels = require('../../lib/database/channels');
const Promise = require('bluebird');
const ChannelModule = require('../../lib/channel/module');
const Flags = require('../../lib/flags');
const testDB = require('../testutil/db').testDB;
function randomString(length) {
const chars = 'abcdefgihkmnpqrstuvwxyz0123456789';
let str = '';
for (let i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
database.init(testDB);
describe('onPreUserJoin Ban Check', () => {
const channelName = `test_${randomString(20)}`;
const bannedIP = '1.1.1.1';
const bannedName = 'troll';
const mockChannel = {
name: channelName,
modules: {},
is(flag) {
return flag === Flags.C_REGISTERED;
}
};
const module = new KickbanModule(mockChannel);
before(done => {
dbChannels.ban(channelName, bannedIP, bannedName, '', '', () => {
dbChannels.ban(channelName, bannedIP, '', '', '', () => {
dbChannels.ban(channelName, '*', bannedName, '', '', () => {
done();
});
});
});
});
after(done => {
dbChannels.deleteBans(channelName, null, () => {
done();
});
});
it('handles a banned IP with a different name', done => {
const user = {
getName() {
return 'anotherTroll';
},
realip: bannedIP,
kick() {
}
};
module.onUserPreJoin(user, null, (error, res) => {
assert.equal(error, null, `Unexpected error: ${error}`);
assert.equal(res, ChannelModule.DENY, 'Expected user to be banned');
done();
});
});
it('handles a banned name with a different IP', done => {
const user = {
getName() {
return 'troll';
},
realip: '5.5.5.5',
kick() {
}
};
module.onUserPreJoin(user, null, (error, res) => {
assert.equal(error, null, `Unexpected error: ${error}`);
assert.equal(res, ChannelModule.DENY, 'Expected user to be banned');
done();
});
});
it('handles a banned IP with a blank name', done => {
const user = {
getName() {
return '';
},
realip: bannedIP,
kick() {
}
};
module.onUserPreJoin(user, null, (error, res) => {
assert.equal(error, null, `Unexpected error: ${error}`);
assert.equal(res, ChannelModule.DENY, 'Expected user to be banned');
done();
});
});
it('handles a non-banned IP with a blank name', done => {
const user = {
getName() {
return '';
},
realip: '5.5.5.5'
};
module.onUserPreJoin(user, null, (error, res) => {
assert.equal(error, null, `Unexpected error: ${error}`);
assert.equal(res, ChannelModule.PASSTHROUGH, 'Expected user not to be banned');
done();
});
});
it('handles a non-banned IP with a non-banned name', done => {
const user = {
getName() {
return 'some_user';
},
realip: '5.5.5.5'
};
module.onUserPreJoin(user, null, (error, res) => {
assert.equal(error, null, `Unexpected error: ${error}`);
assert.equal(res, ChannelModule.PASSTHROUGH, 'Expected user not to be banned');
done();
});
});
});

View file

@ -1,14 +0,0 @@
const loadFromToml = require('../../lib/configuration/configloader').loadFromToml;
const path = require('path');
class IntegrationTestConfig {
constructor(config) {
this.config = config;
}
get knexConfig() {
return this.config.database;
}
}
exports.testConfig = loadFromToml(IntegrationTestConfig, path.resolve(__dirname, '..', '..', 'conf', 'integration-test.toml'));

View file

@ -1,4 +0,0 @@
const testConfig = require('./config').testConfig;
const Database = require('../../lib/database').Database;
exports.testDB = new Database(testConfig.knexConfig);

View file

@ -1,4 +0,0 @@
exports.o = function o(obj) {
// Workaround for knex returning RowDataPacket and failing assertions
return Object.assign({}, obj);
}

63
logger.js Normal file
View file

@ -0,0 +1,63 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var fs = require("fs");
function getTimeString() {
var d = new Date();
return d.toDateString() + " " + d.toTimeString().split(" ")[0];
}
var Logger = function(filename) {
this.filename = filename;
this.writer = fs.createWriteStream(filename, {
flags: "a",
encoding: "utf-8"
});
}
Logger.prototype.log = function () {
var msg = "";
for(var i in arguments)
msg += arguments[i];
if(this.dead) {
return;
}
var str = "[" + getTimeString() + "] " + msg + "\n";
try {
this.writer.write(str);
} catch(e) {
errlog.log("WARNING: Attempted logwrite failed: " + this.filename);
errlog.log("Message was: " + msg);
errlog.log(e);
}
}
Logger.prototype.close = function () {
try {
this.writer.end();
} catch(e) {
errlog.log("Log close failed: " + this.filename);
}
}
var errlog = new Logger("error.log");
var syslog = new Logger("sys.log");
errlog.actualLog = errlog.log;
errlog.log = function(what) { console.log(what); this.actualLog(what); }
syslog.actualLog = syslog.log;
syslog.log = function(what) { console.log(what); this.actualLog(what); }
exports.Logger = Logger;
exports.errlog = errlog;
exports.syslog = syslog;

95
media.js Normal file
View file

@ -0,0 +1,95 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Helper function for formatting a time value in seconds
// to the format hh:mm:ss
function formatTime(sec) {
if(sec == "--:--")
return sec;
sec = Math.floor(sec);
var hours="", minutes="", seconds="";
if(sec > 3600) {
hours = ""+Math.floor(sec / 3600);
if(hours.length < 2)
hours = "0"+hours;
sec = sec % 3600;
}
minutes = ""+Math.floor(sec / 60);
while(minutes.length < 2) {
minutes = "0"+minutes;
}
seconds = ""+(sec % 60);
while(seconds.length < 2) {
seconds = "0"+seconds;
}
var time = "";
if(hours != "")
time = hours + ":";
time += minutes + ":" + seconds;
return time;
}
exports.formatTime = formatTime;
// Represents a media entry
var Media = function(id, title, seconds, type) {
this.id = id;
this.title = title;
this.seconds = seconds == "--:--" ? "--:--" : parseInt(seconds);
this.duration = formatTime(this.seconds);
if(seconds == "--:--") {
this.seconds = 0;
}
this.type = type;
}
Media.prototype.dup = function() {
var m = new Media(this.id, this.title, this.seconds, this.type);
return m;
}
// Returns an object containing the data in this Media but not the
// prototype
Media.prototype.pack = function() {
return {
id: this.id,
title: this.title,
seconds: this.seconds,
duration: this.duration,
type: this.type,
};
}
// Same as pack() but includes the currentTime variable set by the channel
// when the media is being synchronized
Media.prototype.fullupdate = function() {
return {
id: this.id,
title: this.title,
seconds: this.seconds,
duration: this.duration,
type: this.type,
currentTime: this.currentTime,
paused: this.paused,
};
}
Media.prototype.timeupdate = function() {
//return this.fullupdate();
return {
currentTime: this.currentTime,
paused: this.paused
};
}
exports.Media = Media;

195
notwebsocket.js Normal file
View file

@ -0,0 +1,195 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Logger = require("./logger");
const chars = "abcdefghijklmnopqsrtuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789";
var NotWebsocket = function() {
this.hash = "";
for(var i = 0; i < 30; i++) {
this.hash += chars[parseInt(Math.random() * (chars.length - 1))];
}
this.pktqueue = [];
this.handlers = {};
this.room = "";
this.lastpoll = Date.now();
this.noflood = {};
}
NotWebsocket.prototype.checkFlood = function(id, rate) {
if(id in this.noflood) {
this.noflood[id].push(Date.now());
}
else {
this.noflood[id] = [Date.now()];
}
if(this.noflood[id].length > 10) {
this.noflood[id].shift();
var hz = 10000 / (this.noflood[id][9] - this.noflood[id][0]);
if(hz > rate) {
throw "Rate is too high: " + id;
}
}
}
NotWebsocket.prototype.emit = function(msg, data) {
var pkt = [msg, data];
this.pktqueue.push(pkt);
}
NotWebsocket.prototype.poll = function() {
this.checkFlood("poll", 100);
this.lastpoll = Date.now();
var q = [];
for(var i = 0; i < this.pktqueue.length; i++) {
q.push(this.pktqueue[i]);
}
this.pktqueue.length = 0;
return q;
}
NotWebsocket.prototype.on = function(msg, callback) {
if(!(msg in this.handlers))
this.handlers[msg] = [];
this.handlers[msg].push(callback);
}
NotWebsocket.prototype.recv = function(urlstr) {
this.checkFlood("recv", 100);
var msg, data;
try {
var js = JSON.parse(urlstr);
msg = js[0];
data = js[1];
}
catch(e) {
Logger.errlog.log("Failed to parse NWS string");
Logger.errlog.log(urlstr);
}
if(!msg)
return;
if(!(msg in this.handlers))
return;
for(var i = 0; i < this.handlers[msg].length; i++) {
this.handlers[msg][i](data);
}
}
NotWebsocket.prototype.join = function(rm) {
if(!(rm in rooms)) {
rooms[rm] = [];
}
rooms[rm].push(this);
}
NotWebsocket.prototype.leave = function(rm) {
if(rm in rooms) {
var idx = rooms[rm].indexOf(this);
if(idx >= 0) {
rooms[rm].splice(idx, 1);
}
}
}
NotWebsocket.prototype.disconnect = function() {
for(var rm in rooms) {
this.leave(rm);
}
this.recv(JSON.stringify(["disconnect", undefined]));
this.emit("disconnect");
clients[this.hash] = null;
delete clients[this.hash];
}
function sendJSON(res, obj) {
var response = JSON.stringify(obj, null, 4);
if(res.callback) {
response = res.callback + "(" + response + ")";
}
var len = unescape(encodeURIComponent(response)).length;
res.setHeader("Content-Type", "application/json");
res.setHeader("Content-Length", len);
res.end(response);
}
var clients = {};
var rooms = {};
function newConnection(req, res) {
var nws = new NotWebsocket();
clients[nws.hash] = nws;
res.callback = req.query.callback;
sendJSON(res, nws.hash);
return nws;
}
exports.newConnection = newConnection;
function msgReceived(req, res) {
res.callback = req.query.callback;
var h = req.params.hash;
if(h in clients && clients[h] != null) {
var str = req.params.str;
res.callback = req.query.callback;
try {
if(str == "poll") {
sendJSON(res, clients[h].poll());
}
else {
clients[h].recv(decodeURIComponent(str));
sendJSON(res, "");
}
}
catch(e) {
res.send(429); // 429 Too Many Requests
}
}
else {
res.send(404);
}
}
exports.msgReceived = msgReceived;
function inRoom(rm) {
var cl = [];
if(rm in rooms) {
for(var i = 0; i < rooms[rm].length; i++) {
cl.push(rooms[rm][i]);
}
}
cl.emit = function(msg, data) {
for(var i = 0; i < this.length; i++) {
this[i].emit(msg, data);
}
};
return cl;
}
exports.inRoom = inRoom;
function checkDeadSockets() {
for(var h in clients) {
if(Date.now() - clients[h].lastpoll >= 2000) {
clients[h].disconnect();
}
}
}
setInterval(checkDeadSockets, 2000);

7481
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,82 +1,18 @@
{
"author": "Calvin Montgomery",
"name": "CyTube",
"description": "Online media synchronizer and chat",
"version": "3.86.1",
"repository": {
"url": "http://github.com/calzoneman/sync"
},
"license": "MIT",
"dependencies": {
"@calzoneman/jsli": "^2.0.1",
"@cytube/mediaquery": "github:CyTube/mediaquery#52a635d45f38785bdb26e842c9f2bb505bc37a1c",
"bcrypt": "^5.0.1",
"bluebird": "^3.7.2",
"body-parser": "^1.20.1",
"cheerio": "^1.0.0-rc.10",
"clone": "^2.1.2",
"compression": "^1.7.4",
"cookie-parser": "^1.4.5",
"create-error": "^0.3.1",
"csrf": "^3.1.0",
"cytubefilters": "github:calzoneman/cytubefilters#c67b2dab2dc5cc5ed11018819f71273d0f8a1bf5",
"express": "^4.18.2",
"express-minify": "^1.0.0",
"json-typecheck": "^0.1.3",
"knex": "^2.4.0",
"lodash": "^4.17.21",
"morgan": "^1.10.0",
"mysql": "^2.18.1",
"nodemailer": "^6.6.1",
"prom-client": "^13.1.0",
"proxy-addr": "^2.0.6",
"pug": "^3.0.2",
"redis": "^3.1.1",
"sanitize-html": "^2.7.0",
"serve-static": "^1.15.0",
"socket.io": "^4.5.4",
"source-map-support": "^0.5.19",
"toml": "^3.0.0",
"uuid": "^8.3.2",
"yamljs": "^0.2.8"
},
"scripts": {
"build-player": "./bin/build-player.js",
"build-server": "babel -D --source-maps --out-dir lib/ src/",
"flow": "flow",
"lint": "eslint src",
"pretest": "npm run lint",
"postinstall": "./postinstall.sh",
"server-dev": "babel -D --watch --source-maps --verbose --out-dir lib/ src/",
"generate-userscript": "$npm_node_execpath gdrive-userscript/generate-userscript $@ > www/js/cytube-google-drive.user.js",
"test": "mocha --recursive --exit test",
"integration-test": "mocha --recursive --exit integration_test"
},
"devDependencies": {
"@babel/cli": "^7.15.7",
"@babel/core": "^7.15.8",
"@babel/eslint-parser": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"babel-plugin-add-module-exports": "^1.0.4",
"coffeescript": "^1.9.2",
"eslint": "^7.32.0",
"eslint-plugin-no-jquery": "^2.7.0",
"mocha": "^9.2.2",
"sinon": "^10.0.0"
},
"babel": {
"presets": [
[
"@babel/env",
{
"targets": {
"node": "12"
}
}
]
],
"plugins": [
"add-module-exports"
]
}
"author": "Calvin Montgomery",
"name": "CyTube",
"description": "Online media synchronizer and chat",
"version": "2.3.1",
"repository": {
"url": "http://github.com/calzoneman/sync"
},
"dependencies": {
"socket.io": ">=0.9",
"express": ">=3.2",
"mysql-libmysqlclient": "*",
"node_hash": "*",
"bcrypt": "*",
"nodemailer": "*",
"validator": "*"
}
}

View file

@ -1,36 +0,0 @@
window.Player = class Player
constructor: (data) ->
if not (this instanceof Player)
return new Player(data)
@setMediaProperties(data)
@paused = false
load: (data) ->
@setMediaProperties(data)
setMediaProperties: (data) ->
@mediaId = data.id
@mediaType = data.type
@mediaLength = data.seconds
play: ->
@paused = false
pause: ->
@paused = true
seekTo: (time) ->
setVolume: (volume) ->
getTime: (cb) ->
cb(0)
isPaused: (cb) ->
cb(@paused)
getVolume: (cb) ->
cb(VOLUME)
destroy: ->

View file

@ -1,39 +0,0 @@
CUSTOM_EMBED_WARNING = 'This channel is embedding custom content from %link%.
Since this content is not trusted, you must click "Embed" below to allow
the content to be embedded.<hr>'
window.CustomEmbedPlayer = class CustomEmbedPlayer extends EmbedPlayer
constructor: (data) ->
if not (this instanceof CustomEmbedPlayer)
return new CustomEmbedPlayer(data)
@load(data)
load: (data) ->
if not data.meta.embed?
console.error('CustomEmbedPlayer::load(): missing meta.embed')
return
embedSrc = data.meta.embed.src
link = document.createElement('a')
link.href = embedSrc
link.target = '_blank'
link.rel = 'noopener noreferer'
strong = document.createElement('strong')
strong.textContent = embedSrc
link.appendChild(strong)
# TODO: Ideally makeAlert() would allow optionally providing a DOM
# element instead of requiring HTML text
alert = makeAlert('Untrusted Content', CUSTOM_EMBED_WARNING.replace('%link%', link.outerHTML),
'alert-warning')
.removeClass('col-md-12')
$('<button/>').addClass('btn btn-default')
.text('Embed')
.on('click', =>
super(data)
)
.appendTo(alert.find('.alert'))
removeOld(alert)

View file

@ -1,135 +0,0 @@
window.DailymotionPlayer = class DailymotionPlayer extends Player
constructor: (data) ->
if not (this instanceof DailymotionPlayer)
return new DailymotionPlayer(data)
@setMediaProperties(data)
@initialVolumeSet = false
@playbackReadyCb = null
waitUntilDefined(window, 'DM', =>
removeOld()
params =
autoplay: 1
logo: 0
quality = @mapQuality(USEROPTS.default_quality)
if quality != 'auto'
params.quality = quality
@element = DM.$('ytapiplayer')
if not @element or @element.nodeType != Node.ELEMENT_NODE
throw new Error("Invalid player element in DailymotionPlayer(), requires an existing HTML element: " + @element)
if DM.Player._INSTANCES[@element.id] != undefined
@element = DM.Player.destroy(@element.id)
@dm = DM.Player.create(@element,
video: data.id
width: parseInt(VWIDTH, 10)
height: parseInt(VHEIGHT, 10)
params: params
)
@dm.addEventListener('apiready', =>
@dmReady = true
@dm.addEventListener('ended', ->
if CLIENT.leader
socket.emit('playNext')
)
@dm.addEventListener('pause', =>
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@dm.addEventListener('playing', =>
@paused = false
if CLIENT.leader
sendVideoUpdate()
if not @initialVolumeSet
@setVolume(VOLUME)
@initialVolumeSet = true
)
# Once the video stops, the internal state of the player
# becomes unusable and attempting to load() will corrupt it and
# crash the player with an error. As a shortmedium term
# workaround, mark the player as "not ready" until the next
# playback_ready event
@dm.addEventListener('video_end', =>
@dmReady = false
)
@dm.addEventListener('playback_ready', =>
@dmReady = true
if @playbackReadyCb
@playbackReadyCb()
@playbackReadyCb = null
)
)
)
load: (data) ->
@setMediaProperties(data)
if @dm and @dmReady
@dm.load(data.id)
@dm.seek(data.currentTime)
else if @dm
# TODO: Player::load() needs to be made asynchronous in the future
console.log('Warning: load() called before DM is ready, queueing callback')
@playbackReadyCb = () =>
@dm.load(data.id)
@dm.seek(data.currentTime)
else
console.error('WTF? DailymotionPlayer::load() called but @dm is undefined')
pause: ->
if @dm and @dmReady
@paused = true
@dm.pause()
play: ->
if @dm and @dmReady
@paused = false
@dm.play()
seekTo: (time) ->
if @dm and @dmReady
@dm.seek(time)
setVolume: (volume) ->
if @dm and @dmReady
@dm.setVolume(volume)
getTime: (cb) ->
if @dm and @dmReady
cb(@dm.currentTime)
else
cb(0)
getVolume: (cb) ->
if @dm and @dmReady
if @dm.muted
cb(0)
else
volume = @dm.volume
# There was once a bug in Dailymotion where it sometimes gave back
# volumes in the wrong range. Not sure if this is still a necessary
# check.
if volume > 1
volume /= 100
cb(volume)
else
cb(VOLUME)
mapQuality: (quality) ->
switch String(quality)
when '240', '480', '720', '1080' then String(quality)
when '360' then '380'
when 'best' then '1080'
else 'auto'
destroy: ->
if @dm
@dm.destroy('ytapiplayer')

View file

@ -1,49 +0,0 @@
DEFAULT_ERROR = 'You are currently connected via HTTPS but the embedded content
uses non-secure plain HTTP. Your browser therefore blocks it from
loading due to mixed content policy. To fix this, embed the video using a
secure link if available (https://...), or find another source for the content.'
genParam = (name, value) ->
$('<param/>').attr(
name: name
value: value
)
window.EmbedPlayer = class EmbedPlayer extends Player
constructor: (data) ->
if not (this instanceof EmbedPlayer)
return new EmbedPlayer(data)
@load(data)
load: (data) ->
@setMediaProperties(data)
embed = data.meta.embed
if not embed?
console.error('EmbedPlayer::load(): missing meta.embed')
return
@player = @loadIframe(embed)
removeOld(@player)
loadIframe: (embed) ->
if embed.src.indexOf('http:') == 0 and location.protocol == 'https:'
if @__proto__.mixedContentError?
error = @__proto__.mixedContentError
else
error = DEFAULT_ERROR
alert = makeAlert('Mixed Content Error', error, 'alert-danger')
.removeClass('col-md-12')
alert.find('.close').remove()
return alert
else
iframe = $('<iframe/>').attr(
src: embed.src
frameborder: '0'
allow: 'autoplay'
allowfullscreen: '1'
)
return iframe

View file

@ -1,86 +0,0 @@
window.GoogleDrivePlayer = class GoogleDrivePlayer extends VideoJSPlayer
constructor: (data) ->
if not (this instanceof GoogleDrivePlayer)
return new GoogleDrivePlayer(data)
super(data)
load: (data) ->
if not window.hasDriveUserscript
window.promptToInstallDriveUserscript()
else if window.hasDriveUserscript
window.maybePromptToUpgradeUserscript()
if typeof window.getGoogleDriveMetadata is 'function'
setTimeout(=>
backoffRetry((cb) ->
window.getGoogleDriveMetadata(data.id, cb)
, (error, metadata) =>
if error
console.error(error)
alertBox = window.document.createElement('div')
alertBox.className = 'alert alert-danger'
alertBox.textContent = error
document.getElementById('ytapiplayer').appendChild(alertBox)
else
data.meta.direct = metadata.videoMap
super(data)
, {
maxTries: 3
delay: 1000
factor: 1.2
jitter: 500
})
, Math.random() * 1000)
window.promptToInstallDriveUserscript = ->
if document.getElementById('prompt-install-drive-userscript')
return
alertBox = document.createElement('div')
alertBox.id = 'prompt-install-drive-userscript'
alertBox.className = 'alert alert-info'
alertBox.innerHTML = """
Due to continual breaking changes making it increasingly difficult to
maintain Google Drive support, Google Drive now requires installing
a userscript in order to play the video."""
alertBox.appendChild(document.createElement('br'))
infoLink = document.createElement('a')
infoLink.className = 'btn btn-info'
infoLink.href = '/google_drive_userscript'
infoLink.textContent = 'Click here for details'
infoLink.target = '_blank'
alertBox.appendChild(infoLink)
closeButton = document.createElement('button')
closeButton.className = 'close pull-right'
closeButton.innerHTML = '&times;'
closeButton.onclick = ->
alertBox.parentNode.removeChild(alertBox)
alertBox.insertBefore(closeButton, alertBox.firstChild)
removeOld($('<div/>').append(alertBox))
window.tellUserNotToContactMeAboutThingsThatAreNotSupported = ->
if document.getElementById('prompt-no-gdrive-support')
return
alertBox = document.createElement('div')
alertBox.id = 'prompt-no-gdrive-support'
alertBox.className = 'alert alert-danger'
alertBox.innerHTML = """
CyTube has detected an error in Google Drive playback. Please note that the
staff in CyTube support channels DO NOT PROVIDE SUPPORT FOR GOOGLE DRIVE. It
is left in the code as-is for existing users, but we will not assist in
troubleshooting any errors that occur.<br>"""
alertBox.appendChild(document.createElement('br'))
infoLink = document.createElement('a')
infoLink.className = 'btn btn-danger'
infoLink.href = 'https://github.com/calzoneman/sync/wiki/Frequently-Asked-Questions#why-dont-you-support-google-drive-anymore'
infoLink.textContent = 'Click here for details'
infoLink.target = '_blank'
alertBox.appendChild(infoLink)
closeButton = document.createElement('button')
closeButton.className = 'close pull-right'
closeButton.innerHTML = '&times;'
closeButton.onclick = ->
alertBox.parentNode.removeChild(alertBox)
alertBox.insertBefore(closeButton, alertBox.firstChild)
removeOld($('<div/>').append(alertBox))

View file

@ -1,23 +0,0 @@
window.HLSPlayer = class HLSPlayer extends VideoJSPlayer
constructor: (data) ->
if not (this instanceof HLSPlayer)
return new HLSPlayer(data)
@setupMeta(data)
super(data)
load: (data) ->
@setupMeta(data)
super(data)
setupMeta: (data) ->
data.meta.direct =
# Quality is required for data.meta.direct processing but doesn't
# matter here because it's dictated by the stream. Arbitrarily
# choose 480.
480: [
{
link: data.id
contentType: 'application/x-mpegURL'
}
]

View file

@ -1,33 +0,0 @@
window.IframeChild = class IframeChild extends PlayerJSPlayer
constructor: (data) ->
if not (this instanceof IframeChild)
return new IframeChild(data)
super(data)
load: (data) ->
@setMediaProperties(data)
@ready = false
waitUntilDefined(window, 'playerjs', =>
iframe = $('<iframe/>')
.attr(
src: '/iframe'
allow: 'autoplay; fullscreen'
)
removeOld(iframe)
@setupFrame(iframe[0], data)
@setupPlayer(iframe[0])
)
setupFrame: (iframe, data) ->
iframe.addEventListener('load', =>
# TODO: ideally, communication with the child frame should use postMessage()
iframe.contentWindow.VOLUME = VOLUME
iframe.contentWindow.loadMediaPlayer(Object.assign({}, data, { type: 'cm' } ))
iframe.contentWindow.document.querySelector('#ytapiplayer').classList.add('vjs-16-9')
adapter = iframe.contentWindow.playerjs.VideoJSAdapter(iframe.contentWindow.PLAYER.player)
adapter.ready()
typeof data?.meta?.thumbnail == 'string' and iframe.contentWindow.PLAYER.player.poster(data.meta.thumbnail)
)

View file

@ -1,17 +0,0 @@
window.LivestreamPlayer = class LivestreamPlayer extends EmbedPlayer
constructor: (data) ->
if not (this instanceof LivestreamPlayer)
return new LivestreamPlayer(data)
@load(data)
load: (data) ->
[ account, event ] = data.id.split(';')
data.meta.embed =
src: "https://livestream.com/accounts/#{account}/events/#{event}/player?\
enableInfoAndActivity=false&\
defaultDrawer=&\
autoPlay=true&\
mute=false"
tag: 'iframe'
super(data)

View file

@ -1,66 +0,0 @@
window.NicoPlayer = class NicoPlayer extends Player
constructor: (data) ->
if not (this instanceof NicoPlayer)
return new NicoPlayer(data)
@load(data)
load: (data) ->
@setMediaProperties(data)
waitUntilDefined(window, 'NicovideoEmbed', =>
@nico = new NicovideoEmbed({ playerId: 'ytapiplayer', videoId: data.id })
removeOld($(@nico.iframe))
@nico.on('ended', =>
if CLIENT.leader
socket.emit('playNext')
)
@nico.on('pause', =>
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@nico.on('play', =>
@paused = false
if CLIENT.leader
sendVideoUpdate()
)
@nico.on('ready', =>
@play()
@setVolume(VOLUME)
)
)
play: ->
@paused = false
if @nico
@nico.play()
pause: ->
@paused = true
if @nico
@nico.pause()
seekTo: (time) ->
if @nico
@nico.seek(time * 1000)
setVolume: (volume) ->
if @nico
@nico.volumeChange(volume)
getTime: (cb) ->
if @nico
cb(parseFloat(@nico.state.currentTime / 1000))
else
cb(0)
getVolume: (cb) ->
if @nico
cb(parseFloat(@nico.state.volume))
else
cb(VOLUME)

View file

@ -1,21 +0,0 @@
window.OdyseePlayer = class OdyseePlayer extends PlayerJSPlayer
constructor: (data) ->
if not (this instanceof OdyseePlayer)
return new OdyseePlayer(data)
super(data)
load: (data) ->
@ready = false
@setMediaProperties(data)
waitUntilDefined(window, 'playerjs', =>
iframe = $('<iframe/>')
.attr(
src: data.meta.embed.src
allow: 'autoplay; fullscreen'
)
removeOld(iframe)
@setupPlayer(iframe[0], data)
)

View file

@ -1,122 +0,0 @@
PEERTUBE_EMBED_WARNING = 'This channel is embedding PeerTube content from %link%.
PeerTube instances may use P2P technology that will expose your IP address to third parties, including but not
limited to other users in this channel. It is also conceivable that if the content in question is in violation of
copyright laws your IP address could be potentially be observed by legal authorities monitoring the tracker of
this PeerTube instance. The operators of %site% are not responsible for the data sent by the embedded player to
third parties on your behalf.<br><br> If you understand the risks, wish to assume all liability, and continue to
the content, click "Embed" below to allow the content to be embedded.<hr>'
PEERTUBE_RISK = false
window.PeerPlayer = class PeerPlayer extends Player
constructor: (data) ->
if not (this instanceof PeerPlayer)
return new PeerPlayer(data)
@warn(data)
warn: (data) ->
if USEROPTS.peertube_risk or PEERTUBE_RISK
return @load(data)
site = new URL(document.URL).hostname
embedSrc = data.meta.embed.domain
link = "<a href=\"http://#{embedSrc}\" target=\"_blank\" rel=\"noopener noreferer\"><strong>#{embedSrc}</strong></a>"
alert = makeAlert('Privacy Advisory', PEERTUBE_EMBED_WARNING.replace('%link%', link).replace('%site%', site),
'alert-warning')
.removeClass('col-md-12')
$('<button/>').addClass('btn btn-default')
.text('Embed')
.on('click', =>
@load(data)
)
.appendTo(alert.find('.alert'))
$('<button/>').addClass('btn btn-default pull-right')
.text('Embed and dont ask again for this session')
.on('click', =>
PEERTUBE_RISK = true
@load(data)
)
.appendTo(alert.find('.alert'))
removeOld(alert)
load: (data) ->
@setMediaProperties(data)
waitUntilDefined(window, 'PeerTubePlayer', =>
video = $('<iframe/>')
removeOld(video)
video.attr(
src: "https://#{data.meta.embed.domain}/videos/embed/#{data.meta.embed.uuid}?api=1"
allow: 'autoplay; fullscreen'
)
@peertube = new PeerTubePlayer(video[0])
@peertube.addEventListener('playbackStatusChange', (status) =>
@paused = status == 'paused'
if CLIENT.leader
sendVideoUpdate()
)
@peertube.addEventListener('playbackStatusUpdate', (status) =>
@peertube.currentTime = status.position
if status.playbackState == "ended" and CLIENT.leader
socket.emit('playNext')
)
@peertube.addEventListener('volumeChange', (volume) =>
VOLUME = volume
setOpt("volume", VOLUME)
)
@play()
@setVolume(VOLUME)
)
play: ->
@paused = false
if @peertube and @peertube.ready
@peertube.play().catch((error) ->
console.error('PeerTube::play():', error)
)
pause: ->
@paused = true
if @peertube and @peertube.ready
@peertube.pause().catch((error) ->
console.error('PeerTube::pause():', error)
)
seekTo: (time) ->
if @peertube and @peertube.ready
@peertube.seek(time)
getVolume: (cb) ->
if @peertube and @peertube.ready
@peertube.getVolume().then((volume) ->
cb(parseFloat(volume))
).catch((error) ->
console.error('PeerTube::getVolume():', error)
)
else
cb(VOLUME)
setVolume: (volume) ->
if @peertube and @peertube.ready
@peertube.setVolume(volume).catch((error) ->
console.error('PeerTube::setVolume():', error)
)
getTime: (cb) ->
if @peertube and @peertube.ready
cb(@peertube.currentTime)
else
cb(0)
setQuality: (quality) ->
# USEROPTS.default_quality
# @peertube.getResolutions()
# @peertube.setResolution(resolutionId : number)

View file

@ -1,85 +0,0 @@
window.PlayerJSPlayer = class PlayerJSPlayer extends Player
constructor: (data) ->
if not (this instanceof PlayerJSPlayer)
return new PlayerJSPlayer(data)
@load(data)
load: (data) ->
@setMediaProperties(data)
@ready = false
if not data.meta.playerjs
throw new Error('Invalid input: missing meta.playerjs')
waitUntilDefined(window, 'playerjs', =>
iframe = $('<iframe/>')
.attr(
src: data.meta.playerjs.src
allow: 'autoplay; fullscreen'
)
removeOld(iframe)
@setupPlayer(iframe[0])
)
setupPlayer: (iframe) ->
@player = new playerjs.Player(iframe)
@player.on('ready', =>
@player.on('error', (error) =>
console.error('PlayerJS error', error.stack)
)
@player.on('ended', ->
if CLIENT.leader
socket.emit('playNext')
)
@player.on('play', ->
@paused = false
if CLIENT.leader
sendVideoUpdate()
)
@player.on('pause', ->
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@player.setVolume(VOLUME * 100)
if not @paused
@player.play()
@ready = true
)
play: ->
@paused = false
if @player and @ready
@player.play()
pause: ->
@paused = true
if @player and @ready
@player.pause()
seekTo: (time) ->
if @player and @ready
@player.setCurrentTime(time)
setVolume: (volume) ->
if @player and @ready
@player.setVolume(volume * 100)
getTime: (cb) ->
if @player and @ready
@player.getCurrentTime(cb)
else
cb(0)
getVolume: (cb) ->
if @player and @ready
@player.getVolume((volume) ->
cb(volume / 100)
)
else
cb(VOLUME)

View file

@ -1,31 +0,0 @@
codecToMimeType = (codec) ->
switch codec
when 'mov/h264', 'mov/av1' then 'video/mp4'
when 'flv/h264' then 'video/flv'
when 'matroska/vp8', 'matroska/vp9', 'matroska/av1' then 'video/webm'
when 'ogg/theora' then 'video/ogg'
when 'mp3' then 'audio/mp3'
when 'vorbis' then 'audio/ogg'
when 'aac' then 'audio/aac'
when 'opus' then 'audio/opus'
else 'video/flv'
window.FilePlayer = class FilePlayer extends VideoJSPlayer
constructor: (data) ->
if not (this instanceof FilePlayer)
return new FilePlayer(data)
data.meta.direct =
480: [{
contentType: codecToMimeType(data.meta.codec)
link: data.id
}]
super(data)
load: (data) ->
data.meta.direct =
480: [{
contentType: codecToMimeType(data.meta.codec)
link: data.id
}]
super(data)

View file

@ -1,23 +0,0 @@
window.RTMPPlayer = class RTMPPlayer extends VideoJSPlayer
constructor: (data) ->
if not (this instanceof RTMPPlayer)
return new RTMPPlayer(data)
@setupMeta(data)
super(data)
load: (data) ->
@setupMeta(data)
super(data)
setupMeta: (data) ->
data.meta.direct =
# Quality is required for data.meta.direct processing but doesn't
# matter here because it's dictated by the stream. Arbitrarily
# choose 480.
480: [
{
link: data.id
contentType: 'rtmp/flv'
}
]

View file

@ -1,108 +0,0 @@
window.SoundCloudPlayer = class SoundCloudPlayer extends Player
constructor: (data) ->
if not (this instanceof SoundCloudPlayer)
return new SoundCloudPlayer(data)
@setMediaProperties(data)
waitUntilDefined(window, 'SC', =>
removeOld()
# For tracks that are private, but embeddable, the API returns a
# special URL to load into the player.
# TODO: rename scuri?
if data.meta.scuri
soundUrl = data.meta.scuri
else
soundUrl = data.id
widget = $('<iframe/>').appendTo($('#ytapiplayer'))
widget.attr(
id: 'scplayer'
src: "https://w.soundcloud.com/player/?url=#{soundUrl}"
)
# Soundcloud embed widget doesn't have a volume control.
sliderHolder = $('<div/>').attr('id', 'soundcloud-volume-holder')
.insertAfter(widget)
$('<span/>').attr('id', 'soundcloud-volume-label')
.addClass('label label-default')
.text('Volume')
.appendTo(sliderHolder)
volumeSlider = $('<div/>').attr('id', 'soundcloud-volume')
.appendTo(sliderHolder)
.slider(
range: 'min'
value: VOLUME * 100
stop: (event, ui) =>
@setVolume(ui.value / 100)
)
@soundcloud = SC.Widget(widget[0])
@soundcloud.bind(SC.Widget.Events.READY, =>
@soundcloud.ready = true
@setVolume(VOLUME)
@play()
@soundcloud.bind(SC.Widget.Events.PAUSE, =>
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@soundcloud.bind(SC.Widget.Events.PLAY, =>
@paused = false
if CLIENT.leader
sendVideoUpdate()
)
@soundcloud.bind(SC.Widget.Events.FINISH, =>
if CLIENT.leader
socket.emit('playNext')
)
)
)
load: (data) ->
@setMediaProperties(data)
if @soundcloud and @soundcloud.ready
if data.meta.scuri
soundUrl = data.meta.scuri
else
soundUrl = data.id
@soundcloud.load(soundUrl, auto_play: true)
@soundcloud.bind(SC.Widget.Events.READY, =>
@setVolume(VOLUME)
)
else
console.error('SoundCloudPlayer::load() called but soundcloud is not ready')
play: ->
@paused = false
if @soundcloud and @soundcloud.ready
@soundcloud.play()
pause: ->
@paused = true
if @soundcloud and @soundcloud.ready
@soundcloud.pause()
seekTo: (time) ->
if @soundcloud and @soundcloud.ready
# SoundCloud measures time in milliseconds while CyTube uses seconds.
@soundcloud.seekTo(time * 1000)
setVolume: (volume) ->
if @soundcloud and @soundcloud.ready
@soundcloud.setVolume(volume * 100)
getTime: (cb) ->
if @soundcloud and @soundcloud.ready
# Returned time is in milliseconds; CyTube expects seconds
@soundcloud.getPosition((time) -> cb(time / 1000))
else
cb(0)
getVolume: (cb) ->
if @soundcloud and @soundcloud.ready
@soundcloud.getVolume((vol) -> cb(vol / 100))
else
cb(VOLUME)

View file

@ -1,35 +0,0 @@
window.StreamablePlayer = class StreamablePlayer extends PlayerJSPlayer
constructor: (data) ->
if not (this instanceof StreamablePlayer)
return new StreamablePlayer(data)
super(data)
load: (data) ->
@ready = false
@finishing = false
@setMediaProperties(data)
waitUntilDefined(window, 'playerjs', =>
iframe = $('<iframe/>')
.attr(
src: "https://streamable.com/e/#{data.id}"
allow: 'autoplay; fullscreen'
)
removeOld(iframe)
@setupPlayer(iframe[0])
@player.on('ready', =>
# Streamable does not implement ended event since it loops
# gotta use a timeupdate hack
@player.on('timeupdate', (time) =>
if time.duration - time.seconds < 1 and not @finishing
setTimeout(=>
if CLIENT.leader
socket.emit('playNext')
@pause()
, (time.duration - time.seconds) * 1000)
@finishing = true
)
)
)

View file

@ -1,128 +0,0 @@
window.TWITCH_PARAMS_ERROR = 'The Twitch embed player now uses parameters which only
work if the following requirements are met: (1) The embedding website uses
HTTPS; (2) The embedding website uses the default port (443) and is accessed
via https://example.com instead of https://example.com:port. I have no
control over this -- see <a href="https://discuss.dev.twitch.tv/t/twitch-embedded-player-migration-timeline-update/25588" rel="noopener noreferrer" target="_blank">this Twitch post</a>
for details'
window.TwitchPlayer = class TwitchPlayer extends Player
constructor: (data) ->
if not (this instanceof TwitchPlayer)
return new TwitchPlayer(data)
@setMediaProperties(data)
waitUntilDefined(window, 'Twitch', =>
waitUntilDefined(Twitch, 'Player', =>
@init(data)
)
)
init: (data) ->
removeOld()
if location.hostname != location.host or location.protocol != 'https:'
alert = makeAlert(
'Twitch API Parameters',
window.TWITCH_PARAMS_ERROR,
'alert-danger'
).removeClass('col-md-12')
removeOld(alert)
@twitch = null
return
options =
parent: [location.hostname]
width: $('#ytapiplayer').width()
height: $('#ytapiplayer').height()
if data.type is 'tv'
# VOD
options.video = data.id
else
# Livestream
options.channel = data.id
@twitch = new Twitch.Player('ytapiplayer', options)
@twitch.addEventListener(Twitch.Player.READY, =>
@setVolume(VOLUME)
@twitch.setQuality(@mapQuality(USEROPTS.default_quality))
@twitch.addEventListener(Twitch.Player.PLAY, =>
@paused = false
if CLIENT.leader
sendVideoUpdate()
)
@twitch.addEventListener(Twitch.Player.PAUSE, =>
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@twitch.addEventListener(Twitch.Player.ENDED, =>
if CLIENT.leader
socket.emit('playNext')
)
)
load: (data) ->
@setMediaProperties(data)
try
if data.type is 'tv'
# VOD
@twitch.setVideo(data.id)
else
# Livestream
@twitch.setChannel(data.id)
catch error
console.error(error)
pause: ->
try
@twitch.pause()
@paused = true
catch error
console.error(error)
play: ->
try
@twitch.play()
@paused = false
catch error
console.error(error)
seekTo: (time) ->
try
@twitch.seek(time)
catch error
console.error(error)
getTime: (cb) ->
try
cb(@twitch.getCurrentTime())
catch error
console.error(error)
setVolume: (volume) ->
try
@twitch.setVolume(volume)
if volume > 0
@twitch.setMuted(false)
catch error
console.error(error)
getVolume: (cb) ->
try
if @twitch.isPaused()
cb(0)
else
cb(@twitch.getVolume())
catch error
console.error(error)
mapQuality: (quality) ->
switch String(quality)
when '1080' then 'chunked'
when '720' then 'high'
when '480' then 'medium'
when '360' then 'low'
when '240' then 'mobile'
when 'best' then 'chunked'
else ''

View file

@ -1,21 +0,0 @@
window.TwitchClipPlayer = class TwitchClipPlayer extends EmbedPlayer
constructor: (data) ->
if not (this instanceof TwitchClipPlayer)
return new TwitchClipPlayer(data)
@load(data)
load: (data) ->
if location.hostname != location.host or location.protocol != 'https:'
alert = makeAlert(
'Twitch API Parameters',
window.TWITCH_PARAMS_ERROR,
'alert-danger'
).removeClass('col-md-12')
removeOld(alert)
return
data.meta.embed =
tag: 'iframe'
src: "https://clips.twitch.tv/embed?clip=#{data.id}&parent=#{location.host}"
super(data)

View file

@ -1,118 +0,0 @@
TYPE_MAP =
yt: YouTubePlayer
vi: VimeoPlayer
dm: DailymotionPlayer
gd: GoogleDrivePlayer
fi: FilePlayer
sc: SoundCloudPlayer
li: LivestreamPlayer
tw: TwitchPlayer
tv: TwitchPlayer
cu: CustomEmbedPlayer
rt: RTMPPlayer
hl: HLSPlayer
sb: StreamablePlayer
tc: TwitchClipPlayer
cm: VideoJSPlayer
pt: PeerPlayer
bc: IframeChild
bn: IframeChild
od: OdyseePlayer
wp: WhepPlayer
nv: NicoPlayer
window.loadMediaPlayer = (data) ->
try
if window.PLAYER
window.PLAYER.destroy()
catch error
console.error error
if data.meta.direct and data.type is 'vi'
try
window.PLAYER = new VideoJSPlayer(data)
catch e
console.error e
else if data.type of TYPE_MAP
try
window.PLAYER = TYPE_MAP[data.type](data)
catch e
console.error e
window.handleMediaUpdate = (data) ->
PLAYER = window.PLAYER
# Do not update if the current time is past the end of the video, unless
# the video has length 0 (which is a special case for livestreams)
if typeof PLAYER.mediaLength is 'number' and
PLAYER.mediaLength > 0 and
data.currentTime > PLAYER.mediaLength
return
# Negative currentTime indicates a lead-in for clients to load the video,
# but not play it yet (helps with initial buffering)
waiting = data.currentTime < 0
# Load a new video in the same player if the ID changed
if data.id and data.id != PLAYER.mediaId
if data.currentTime < 0
data.currentTime = 0
PLAYER.load(data)
PLAYER.play()
if waiting
PLAYER.seekTo(0)
# YouTube player has a race condition that crashes the player if
# play(), seek(0), and pause() are called quickly without waiting
# for events to fire. Setting a flag variable that is checked in the
# event handler mitigates this.
if PLAYER instanceof YouTubePlayer
PLAYER.pauseSeekRaceCondition = true
else
PLAYER.pause()
return
else if PLAYER instanceof YouTubePlayer
PLAYER.pauseSeekRaceCondition = false
if CLIENT.leader or not USEROPTS.synch
return
if data.paused and not PLAYER.paused
PLAYER.seekTo(data.currentTime)
PLAYER.pause()
else if PLAYER.paused and not data.paused
PLAYER.play()
PLAYER.getTime((seconds) ->
time = data.currentTime
diff = (time - seconds) or time
accuracy = USEROPTS.sync_accuracy
# Dailymotion can't seek very accurately in Flash due to keyframe
# placement. Accuracy should not be set lower than 5 or the video
# may be very choppy.
if PLAYER instanceof DailymotionPlayer
accuracy = Math.max(accuracy, 5)
if diff > accuracy
# The player is behind the correct time
PLAYER.seekTo(time)
else if diff < -accuracy
# The player is ahead of the correct time
# Don't seek all the way back, to account for possible buffering.
# However, do seek all the way back for Dailymotion due to the
# keyframe issue mentioned above.
if not (PLAYER instanceof DailymotionPlayer)
time += 1
PLAYER.seekTo(time)
)
window.removeOld = (replace) ->
$('#soundcloud-volume-holder').remove()
replace ?= $('<div/>').addClass('embed-responsive-item')
old = $('#ytapiplayer')
old.attr('id', 'ytapiplayer-old')
replace.attr('id', 'ytapiplayer')
replace.insertBefore(old)
old.remove()
return replace

View file

@ -1,239 +0,0 @@
sortSources = (sources) ->
if not sources
console.error('sortSources() called with null source list')
return []
qualities = ['2160', '1440', '1080', '720', '540', '480', '360', '240']
pref = String(USEROPTS.default_quality)
if USEROPTS.default_quality == 'best'
pref = '2160'
idx = qualities.indexOf(pref)
if idx < 0
idx = 5 # 480p
qualityOrder = qualities.slice(idx).concat(qualities.slice(0, idx).reverse())
qualityOrder.unshift('auto')
sourceOrder = []
flvOrder = []
for quality in qualityOrder
if quality of sources
flv = []
nonflv = []
sources[quality].forEach((source) ->
source.quality = quality
if source.contentType == 'video/flv'
flv.push(source)
else
nonflv.push(source)
)
sourceOrder = sourceOrder.concat(nonflv)
flvOrder = flvOrder.concat(flv)
return sourceOrder.concat(flvOrder).map((source) ->
type: source.contentType
src: source.link
res: source.quality
label: getSourceLabel(source)
)
getSourceLabel = (source) ->
if source.res is 'auto'
return 'auto'
else
return "#{source.quality}p #{source.contentType.split('/')[1]}"
hasAnyTextTracks = (data) ->
ntracks = data?.meta?.textTracks?.length ? 0
return ntracks > 0
hasAnyAudioTracks = (data) ->
ntracks = data?.meta?.audioTracks?.length ? 0
return ntracks > 0
window.VideoJSPlayer = class VideoJSPlayer extends Player
constructor: (data) ->
if not (this instanceof VideoJSPlayer)
return new VideoJSPlayer(data)
@load(data)
loadPlayer: (data) ->
waitUntilDefined(window, 'videojs', =>
attrs =
width: '100%'
height: '100%'
if @mediaType == 'cm' and hasAnyTextTracks(data)
attrs.crossorigin = 'anonymous'
video = $('<video/>')
.addClass('video-js vjs-default-skin embed-responsive-item')
.attr(attrs)
removeOld(video)
@sources = sortSources(data.meta.direct)
if @sources.length == 0
console.error('VideoJSPlayer::constructor(): data.meta.direct
has no sources!')
@mediaType = null
return
@sourceIdx = 0
# TODO: Refactor VideoJSPlayer to use a preLoad()/load()/postLoad() pattern
# VideoJSPlayer should provide the core functionality and logic for specific
# dependent player types (gdrive) should be an extension
if data.meta.gdrive_subtitles
data.meta.gdrive_subtitles.available.forEach((subt) ->
label = subt.lang_original
if subt.name
label += " (#{subt.name})"
$('<track/>').attr(
src: "/gdvtt/#{data.id}/#{subt.lang}/#{subt.name}.vtt?\
vid=#{data.meta.gdrive_subtitles.vid}"
kind: 'subtitles'
srclang: subt.lang
label: label
).appendTo(video)
)
if data.meta.textTracks
data.meta.textTracks.forEach((track) ->
label = track.name
attrs =
src: track.url
kind: 'subtitles'
type: track.type
label: label
if track.default? and track.default
attrs.default = ''
$('<track/>').attr(attrs).appendTo(video)
)
pluginData =
videoJsResolutionSwitcher:
default: @sources[0].res
if hasAnyAudioTracks(data)
pluginData.audioSwitch =
audioTracks: data.meta.audioTracks,
volume: VOLUME
@player = videojs(video[0],
# https://github.com/Dash-Industry-Forum/dash.js/issues/2184
autoplay: @sources[0].type != 'application/dash+xml',
controls: true,
plugins: pluginData
)
@player.ready(=>
# Have to use updateSrc instead of <source> tags
# see: https://github.com/videojs/video.js/issues/3428
@player.poster(data.meta.thumbnail)
@player.updateSrc(@sources)
@player.on('error', =>
err = @player.error()
if err and err.code == 4
console.error('Caught error, trying next source')
# Does this really need to be done manually?
@sourceIdx++
if @sourceIdx < @sources.length
@player.src(@sources[@sourceIdx])
else
console.error('Out of sources, video will not play')
if @mediaType is 'gd'
if not window.hasDriveUserscript
window.promptToInstallDriveUserscript()
else
window.tellUserNotToContactMeAboutThingsThatAreNotSupported()
)
@setVolume(VOLUME)
@player.on('ended', ->
if CLIENT.leader
socket.emit('playNext')
)
@player.on('pause', =>
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@player.on('play', =>
@paused = false
if CLIENT.leader
sendVideoUpdate()
)
# Workaround for IE-- even after seeking completes, the loading
# spinner remains.
@player.on('seeked', =>
$('.vjs-waiting').removeClass('vjs-waiting')
)
# Workaround for Chrome-- it seems that the click bindings for
# the subtitle menu aren't quite set up until after the ready
# event finishes, so set a timeout for 1ms to force this code
# not to run until the ready() function returns.
setTimeout(->
$('#ytapiplayer .vjs-subtitles-button .vjs-menu-item').each((i, elem) ->
textNode = elem.childNodes[0]
if textNode.textContent == localStorage.lastSubtitle
elem.click()
elem.onclick = ->
if elem.attributes['aria-checked'].value == 'true'
localStorage.lastSubtitle = textNode.textContent
)
, 1)
)
)
load: (data) ->
@setMediaProperties(data)
# Note: VideoJS does have facilities for loading new videos into the
# existing player object, however it appears to be pretty glitchy when
# a video can't be played (either previous or next video). It's safer
# to just reset the entire thing.
@destroy()
@loadPlayer(data)
play: ->
@paused = false
if @player and @player.readyState() > 0
@player.play()
pause: ->
@paused = true
if @player and @player.readyState() > 0
@player.pause()
seekTo: (time) ->
if @player and @player.readyState() > 0
@player.currentTime(time)
setVolume: (volume) ->
if @player
@player.volume(volume)
getTime: (cb) ->
if @player and @player.readyState() > 0
cb(@player.currentTime())
else
cb(0)
getVolume: (cb) ->
if @player and @player.readyState() > 0
if @player.muted()
cb(0)
else
cb(@player.volume())
else
cb(VOLUME)
destroy: ->
removeOld()
if @player
@player.dispose()

View file

@ -1,86 +0,0 @@
window.VimeoPlayer = class VimeoPlayer extends Player
constructor: (data) ->
if not (this instanceof VimeoPlayer)
return new VimeoPlayer(data)
@load(data)
load: (data) ->
@setMediaProperties(data)
waitUntilDefined(window, 'Vimeo', =>
video = $('<iframe/>')
removeOld(video)
video.attr(
src: "https://player.vimeo.com/video/#{data.id}"
allow: 'autoplay; fullscreen'
)
@vimeo = new Vimeo.Player(video[0])
@vimeo.on('ended', =>
if CLIENT.leader
socket.emit('playNext')
)
@vimeo.on('pause', =>
@paused = true
if CLIENT.leader
sendVideoUpdate()
)
@vimeo.on('play', =>
@paused = false
if CLIENT.leader
sendVideoUpdate()
)
@play()
@setVolume(VOLUME)
)
play: ->
@paused = false
if @vimeo
@vimeo.play().catch((error) ->
console.error('vimeo::play():', error)
)
pause: ->
@paused = true
if @vimeo
@vimeo.pause().catch((error) ->
console.error('vimeo::pause():', error)
)
seekTo: (time) ->
if @vimeo
@vimeo.setCurrentTime(time).catch((error) ->
console.error('vimeo::setCurrentTime():', error)
)
setVolume: (volume) ->
if @vimeo
@vimeo.setVolume(volume).catch((error) ->
console.error('vimeo::setVolume():', error)
)
getTime: (cb) ->
if @vimeo
@vimeo.getCurrentTime().then((time) ->
cb(parseFloat(time))
).catch((error) ->
console.error('vimeo::getCurrentTime():', error)
)
else
cb(0)
getVolume: (cb) ->
if @vimeo
@vimeo.getVolume().then((volume) ->
cb(parseFloat(volume))
).catch((error) ->
console.error('vimeo::getVolume():', error)
)
else
cb(VOLUME)

View file

@ -1,87 +0,0 @@
window.WhepPlayer = class WhepPlayer extends Player
constructor: (data) ->
return new WhepPlayer(data) unless this instanceof WhepPlayer
super(data)
@load(data)
load: (data) ->
@ready = false
@paused = true
@setMediaProperties(data)
unless data.meta?.whepURL
u = new URL(data.id)
streemId = u.pathname.split('/').filter(Boolean)[0]
data.meta ?= {}
# Adjust these to whatever your backend expects
data.meta.whepURL = "#{u.origin}/api/whep"
data.meta.streamKey = streemId
{ whepURL, streamKey } = data.meta
# Create video element
videoEl = document.createElement 'video'
videoEl.autoplay = true
videoEl.muted = true
videoEl.controls = true
# Use the standard container swapper
holder = removeOld() # jQuery object
holder.empty().append(videoEl)
@videoEl = videoEl
# ---- WebRTC setup ----
pc = new RTCPeerConnection()
pc.addTransceiver 'audio', direction: 'recvonly'
pc.addTransceiver 'video', direction: 'recvonly'
pc.ontrack = (e) => @videoEl.srcObject = e.streams[0]
pc.onconnectionstatechange = =>
if pc.connectionState is 'connected'
@ready = true
@fire? 'ready'
pc.createOffer()
.then (offer) =>
pc.setLocalDescription offer
fetch whepURL,
method: 'POST'
headers:
Authorization: "Bearer #{streamKey}"
'Content-Type': 'application/sdp'
body: offer.sdp
.then (r) -> r.text()
.then (answer) ->
pc.setRemoteDescription type: 'answer', sdp: answer
.catch (err) ->
console.error 'WHEP negotiation failed:', err
@pc = pc
play: ->
@paused = false
@videoEl?.play?()
pause: ->
@paused = true
@videoEl?.pause?()
seekTo: (t) ->
@videoEl?.currentTime = t if @ready
setVolume: (v) ->
@videoEl?.volume = v if @ready
getTime: (cb) ->
if @ready and @videoEl?
cb @videoEl.currentTime
else
cb 0
getVolume: (cb) ->
if @ready and @videoEl?
cb @videoEl.volume
else
cb VOLUME

View file

@ -1,96 +0,0 @@
window.YouTubePlayer = class YouTubePlayer extends Player
constructor: (data) ->
if not (this instanceof YouTubePlayer)
return new YouTubePlayer(data)
@setMediaProperties(data)
@pauseSeekRaceCondition = false
waitUntilDefined(window, 'YT', =>
# Even after window.YT is defined, YT.Player may not be, which causes a
# 'YT.Player is not a constructor' error occasionally
waitUntilDefined(YT, 'Player', =>
removeOld()
@yt = new YT.Player('ytapiplayer',
videoId: data.id
playerVars:
autohide: 1
autoplay: 1
controls: 1
iv_load_policy: 3 # iv_load_policy 3 indicates no annotations
rel: 0
events:
onReady: @onReady.bind(this)
onStateChange: @onStateChange.bind(this)
)
)
)
load: (data) ->
@setMediaProperties(data)
if @yt and @yt.ready
@yt.loadVideoById(data.id, data.currentTime)
else
console.error('WTF? YouTubePlayer::load() called but yt is not ready')
onReady: ->
@yt.ready = true
@setVolume(VOLUME)
onStateChange: (ev) ->
# If you pause the video before the first PLAYING
# event is emitted, weird things happen (or at least that was true
# whenever this comment was authored in 2015).
if ev.data == YT.PlayerState.PLAYING and @pauseSeekRaceCondition
@pause()
@pauseSeekRaceCondition = false
if (ev.data == YT.PlayerState.PAUSED and not @paused) or
(ev.data == YT.PlayerState.PLAYING and @paused)
@paused = (ev.data == YT.PlayerState.PAUSED)
if CLIENT.leader
sendVideoUpdate()
if ev.data == YT.PlayerState.ENDED and CLIENT.leader
socket.emit('playNext')
play: ->
@paused = false
if @yt and @yt.ready
@yt.playVideo()
pause: ->
@paused = true
if @yt and @yt.ready
@yt.pauseVideo()
seekTo: (time) ->
if @yt and @yt.ready
@yt.seekTo(time, true)
setVolume: (volume) ->
if @yt and @yt.ready
if volume > 0
# If the player is muted, even if the volume is set,
# the player remains muted
@yt.unMute()
@yt.setVolume(volume * 100)
setQuality: (quality) ->
# https://github.com/calzoneman/sync/issues/726
getTime: (cb) ->
if @yt and @yt.ready
cb(@yt.getCurrentTime())
else
cb(0)
getVolume: (cb) ->
if @yt and @yt.ready
if @yt.isMuted()
cb(0)
else
cb(@yt.getVolume() / 100)
else
cb(VOLUME)

520
playlist.js Normal file
View file

@ -0,0 +1,520 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
ULList = require("./ullist").ULList;
var Media = require("./media").Media;
var AllPlaylists = {};
function PlaylistItem(media, uid) {
this.media = media;
this.uid = uid;
this.temp = false;
this.queueby = "";
this.prev = null;
this.next = null;
}
PlaylistItem.prototype.pack = function() {
return {
media: this.media.pack(),
uid: this.uid,
temp: this.temp,
queueby: this.queueby
};
}
function Playlist(chan) {
var name = chan.canonical_name;
if(name in AllPlaylists && AllPlaylists[name]) {
var pl = AllPlaylists[name];
if(!pl.dead)
pl.die();
}
this.items = new ULList();
this.current = null;
this.next_uid = 0;
this._leadInterval = false;
this._lastUpdate = 0;
this._counter = 0;
this.leading = true;
this.callbacks = {
"changeMedia": [],
"mediaUpdate": [],
"remove": [],
};
this.lock = false;
this.action_queue = [];
this._qaInterval = false;
AllPlaylists[name] = this;
this.channel = chan;
this.server = chan.server;
var pl = this;
this.on("mediaUpdate", function(m) {
chan.sendAll("mediaUpdate", m.timeupdate());
});
this.on("changeMedia", function(m) {
chan.onVideoChange();
chan.sendAll("setCurrent", pl.current.uid);
chan.sendAll("changeMedia", m.fullupdate());
});
this.on("remove", function(item) {
chan.broadcastPlaylistMeta();
chan.sendAll("delete", {
uid: item.uid
});
});
}
Playlist.prototype.queueAction = function(data) {
this.action_queue.push(data);
if(this._qaInterval)
return;
var pl = this;
this._qaInterval = setInterval(function() {
var data = pl.action_queue.shift();
if(data.waiting) {
if(!("expire" in data))
data.expire = Date.now() + 10000;
if(Date.now() < data.expire)
pl.action_queue.unshift(data);
}
else
data.fn();
if(pl.action_queue.length == 0) {
clearInterval(pl._qaInterval);
pl._qaInterval = false;
}
}, 100);
}
Playlist.prototype.dump = function() {
var arr = this.items.toArray();
var pos = 0;
for(var i in arr) {
if(this.current && arr[i].uid == this.current.uid) {
pos = i;
break;
}
}
var time = 0;
if(this.current)
time = this.current.media.currentTime;
return {
pl: arr,
pos: pos,
time: time
};
}
Playlist.prototype.die = function () {
this.clear();
if(this._leadInterval) {
clearInterval(this._leadInterval);
this._leadInterval = false;
}
if(this._qaInterval) {
clearInterval(this._qaInterval);
this._qaInterval = false;
}
//for(var key in this)
// delete this[key];
this.dead = true;
}
Playlist.prototype.load = function(data, callback) {
this.clear();
for(var i in data.pl) {
var e = data.pl[i].media;
var m = new Media(e.id, e.title, e.seconds, e.type);
var it = this.makeItem(m);
it.temp = data.pl[i].temp;
it.queueby = data.pl[i].queueby;
this.items.append(it);
if(i == parseInt(data.pos)) {
this.current = it;
}
}
if(callback)
callback();
}
Playlist.prototype.on = function(ev, fn) {
if(typeof fn === "undefined") {
var pl = this;
return function() {
for(var i = 0; i < pl.callbacks[ev].length; i++) {
pl.callbacks[ev][i].apply(this, arguments);
}
}
}
else if(typeof fn === "function") {
this.callbacks[ev].push(fn);
}
}
Playlist.prototype.makeItem = function(media) {
return new PlaylistItem(media, this.next_uid++);
}
Playlist.prototype.add = function(item, pos) {
var success;
if(pos == "append")
success = this.items.append(item);
else if(pos == "prepend")
success = this.items.prepend(item);
else
success = this.items.insertAfter(item, pos);
if(success && this.items.length == 1) {
this.current = item;
this.startPlayback();
}
return success;
}
Playlist.prototype.addCachedMedia = function(data, callback) {
var pos = "append";
if(data.pos == "next") {
if(!this.current)
pos = "prepend";
else
pos = this.current.uid;
}
var it = this.makeItem(data.media);
it.temp = data.temp;
it.queueby = data.queueby;
var pl = this;
var action = {
fn: function() {
if(pl.add(it, pos))
callback(false, it);
},
waiting: false
};
this.queueAction(action);
}
Playlist.prototype.addMedia = function(data, callback) {
if(data.type == "yp") {
this.addYouTubePlaylist(data, callback);
return;
}
var pos = "append";
if(data.pos == "next") {
if(!this.current)
pos = "prepend";
else
pos = this.current.uid;
}
var it = this.makeItem(null);
var pl = this;
var action = {
fn: function() {
if(pl.add(it, pos)) {
callback(false, it);
}
},
waiting: true
};
this.queueAction(action);
// Pre-cached data
if(typeof data.title === "string" &&
typeof data.seconds === "number") {
if(data.maxlength && data.seconds > data.maxlength) {
action.expire = 0;
callback("Media is too long!", null);
return;
}
it.media = new Media(data.id, data.title, data.seconds, data.type);
action.waiting = false;
return;
}
this.server.infogetter.getMedia(data.id, data.type, function(err, media) {
if(err) {
action.expire = 0;
callback(err, null);
return;
}
if(data.maxlength && media.seconds > data.maxlength) {
action.expire = 0;
callback("Media is too long!", null);
return;
}
it.media = media;
it.temp = data.temp;
it.queueby = data.queueby;
action.waiting = false;
});
}
Playlist.prototype.addMediaList = function(data, callback) {
var start = false;
if(data.pos == "next") {
data.list = data.list.reverse();
start = data.list[data.list.length - 1];
}
if(this.items.length != 0)
start = false;
var pl = this;
for(var i = 0; i < data.list.length; i++) {
var x = data.list[i];
x.pos = data.pos;
if(start && x == start) {
pl.addMedia(x, function (err, item) {
if(err) {
callback(err, item);
}
else {
callback(err, item);
pl.current = item;
pl.startPlayback();
}
});
}
else {
pl.addMedia(x, callback);
}
}
}
Playlist.prototype.addYouTubePlaylist = function(data, callback) {
var pos = "append";
if(data.pos == "next") {
if(!this.current)
pos = "prepend";
else
pos = this.current.uid;
}
var pl = this;
this.server.infogetter.getMedia(data.id, data.type, function(err, vids) {
if(err) {
callback(err, null);
return;
}
if(data.pos === "next")
vids.reverse();
vids.forEach(function(media) {
if(data.maxlength && media.seconds > data.maxlength) {
callback("Media is too long!", null);
return;
}
var it = pl.makeItem(media);
it.temp = data.temp;
it.queueby = data.queueby;
pl.queueAction({
fn: function() {
if(pl.add(it, pos))
callback(false, it);
},
});
});
});
}
Playlist.prototype.remove = function(uid, callback) {
var pl = this;
this.queueAction({
fn: function() {
var item = pl.items.find(uid);
if(pl.items.remove(uid)) {
if(callback)
callback();
if(item == pl.current)
pl._next();
}
},
waiting: false
});
}
Playlist.prototype.move = function(from, after, callback) {
var pl = this;
this.queueAction({
fn: function() {
pl._move(from, after, callback);
},
waiting: false
});
}
Playlist.prototype._move = function(from, after, callback) {
var it = this.items.find(from);
if(!this.items.remove(from))
return;
if(after === "prepend") {
if(!this.items.prepend(it))
return;
}
else if(after === "append") {
if(!this.items.append(it))
return;
}
else if(!this.items.insertAfter(it, after))
return;
callback();
}
Playlist.prototype.next = function() {
if(!this.current)
return;
var it = this.current;
if(it.temp) {
var pl = this;
this.remove(it.uid, function() {
pl.on("remove")(it);
});
}
else {
this._next();
}
return this.current;
}
Playlist.prototype._next = function() {
if(!this.current)
return;
this.current = this.current.next;
if(this.current === null && this.items.first !== null)
this.current = this.items.first;
if(this.current) {
this.startPlayback();
}
}
Playlist.prototype.jump = function(uid) {
if(!this.current)
return false;
var jmp = this.items.find(uid);
if(!jmp)
return false;
var it = this.current;
this.current = jmp;
if(this.current) {
this.startPlayback();
}
if(it.temp) {
var pl = this;
this.remove(it.uid, function () {
pl.on("remove")(it);
});
}
return this.current;
}
Playlist.prototype.clear = function() {
this.items.clear();
this.next_uid = 0;
this.current = null;
clearInterval(this._leadInterval);
}
Playlist.prototype.lead = function(lead) {
this.leading = lead;
var pl = this;
if(!this.leading && this._leadInterval) {
clearInterval(this._leadInterval);
this._leadInterval = false;
}
else if(this.leading && !this._leadInterval) {
this._leadInterval = setInterval(function() {
pl._leadLoop();
}, 1000);
}
}
Playlist.prototype.startPlayback = function(time) {
if(!this.current || !this.current.media)
return false;
this.current.media.paused = false;
this.current.media.currentTime = time || -1;
var pl = this;
if(this._leadInterval) {
clearInterval(this._leadInterval);
this._leadInterval = false;
}
this.on("changeMedia")(this.current.media);
if(this.leading && !isLive(this.current.media.type)) {
this._lastUpdate = Date.now();
this._leadInterval = setInterval(function() {
pl._leadLoop();
}, 1000);
}
}
function isLive(type) {
return type == "li" // Livestream.com
|| type == "tw" // Twitch.tv
|| type == "jt" // Justin.tv
|| type == "rt" // RTMP
|| type == "jw" // JWPlayer
|| type == "us" // Ustream.tv
|| type == "im" // Imgur album
|| type == "cu";// Custom embed
}
const UPDATE_INTERVAL = 5;
Playlist.prototype._leadLoop = function() {
if(this.current == null)
return;
if(this.channel.name == "") {
this.die();
return;
}
this.current.media.currentTime += (Date.now() - this._lastUpdate) / 1000.0;
this._lastUpdate = Date.now();
this._counter++;
if(this.current.media.currentTime >= this.current.media.seconds + 2) {
this.next();
}
else if(this._counter % UPDATE_INTERVAL == 0) {
this.on("mediaUpdate")(this.current.media);
}
}
module.exports = Playlist;

46
poll.js Normal file
View file

@ -0,0 +1,46 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Poll = function(initiator, title, options) {
this.initiator = initiator;
this.title = title;
this.options = options;
this.counts = new Array(options.length);
for(var i = 0; i < this.counts.length; i++) {
this.counts[i] = 0;
}
this.votes = {};
}
Poll.prototype.vote = function(ip, option) {
if(!(ip in this.votes) || this.votes[ip] == null) {
this.votes[ip] = option;
this.counts[option]++;
}
}
Poll.prototype.unvote = function(ip) {
if(ip in this.votes && this.votes[ip] != null) {
this.counts[this.votes[ip]]--;
this.votes[ip] = null;
}
}
Poll.prototype.packUpdate = function() {
return {
title: this.title,
options: this.options,
counts: this.counts,
initiator: this.initiator
}
}
exports.Poll = Poll;

View file

@ -1,14 +0,0 @@
#!/bin/sh
set -e
if ! command -v npm >/dev/null; then
echo "Could not find npm in \$PATH"
exit 1
fi
echo "Building from src/ to lib/"
npm run build-server
echo "Building from player/ to www/js/player.js"
npm run build-player
echo "Done"

55
rank.js Normal file
View file

@ -0,0 +1,55 @@
/*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
exports.Anonymous = -1;
exports.Guest = 0;
exports.Member = 1;
exports.Moderator = 2;
exports.Owner = 3;
exports.Siteadmin = 255;
var permissions = {
acp : exports.Siteadmin,
announce : exports.Siteadmin,
registerChannel : exports.Owner,
acl : exports.Owner,
chatFilter : exports.Owner,
setcss : exports.Owner,
setjs : exports.Owner,
channelperms : exports.Owner,
queue : exports.Moderator,
assignLeader : exports.Moderator,
kick : exports.Moderator,
ipban : exports.Moderator,
ban : exports.Moderator,
promote : exports.Moderator,
qlock : exports.Moderator,
poll : exports.Moderator,
shout : exports.Moderator,
channelOpts : exports.Moderator,
jump : exports.Moderator,
updateMotd : exports.Moderator,
drink : exports.Moderator,
seeVoteskip : exports.Moderator,
uncache : exports.Moderator,
seenlogins : exports.Moderator,
settemp : exports.Moderator,
search : exports.Guest,
chat : exports.Guest,
};
// Check if someone has permission to do shit
exports.hasPermission = function(user, what) {
if(what in permissions) {
return user.rank >= permissions[what];
}
else return false;
}

2
run.sh
View file

@ -2,7 +2,7 @@
while :
do
node index.js
node server.js
sleep 2
done

View file

@ -1,122 +0,0 @@
#!/usr/bin/env node
/*
** CyTube Service Socket Commandline
*/
const readline = require('readline');
const spawn = require('child_process').spawn;
const util = require('util');
const net = require('net');
const fs = require('fs');
const COMPLETIONS = [
"/delete_old_tables",
"/gc",
"/globalban",
"/reload",
"/reloadcert",
"/reload-partitions",
"/switch",
"/unglobalban",
"/unloadchan"
];
var Config = require("./lib/config");
Config.load("config.yaml");
if(!Config.get("service-socket.enabled")){
console.error('The Service Socket is not enabled.');
process.exit(1);
}
const SOCKETFILE = Config.get("service-socket.socket");
// Wipe the TTY
process.stdout.write('\x1Bc');
var commandline, eventlog, syslog, errorlog;
var client = net.createConnection(SOCKETFILE).on('connect', () => {
commandline = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: tabcomplete
});
commandline.setPrompt("> ", 2);
commandline.on("line", function(line) {
if(line === 'exit'){ return cleanup(); }
if(line === 'quit'){ return cleanup(); }
if(line.match(/^\/globalban/) && line.split(/\s+/).length === 2){
console.log('You must provide a reason')
return commandline.prompt();
}
client.write(line);
commandline.prompt();
});
commandline.on('close', function() {
return cleanup();
});
commandline.on("SIGINT", function() {
commandline.clearLine();
commandline.question("Terminate connection? ", function(answer) {
return answer.match(/^y(es)?$/i) ? cleanup() : commandline.output.write("> ");
});
});
commandline.prompt();
console.log = function() { cmdouthndlr("log", arguments); }
console.warn = function() { cmdouthndlr("warn", arguments); }
console.error = function() { cmdouthndlr("error", arguments); }
// console.info is reserved in this script for the exit message
// this prevents an extraneous final prompt from readline on terminate
eventlog = spawn('tail', ['-f', 'events.log']);
eventlog.stdout.on('data', function (data) {
console.log(data.toString().replace(/^(.+)$/mg, 'events: $1'));
});
syslog = spawn('tail', ['-f', 'sys.log']);
syslog.stdout.on('data', function (data) {
console.log(data.toString().replace(/^(.+)$/mg, 'sys: $1'));
});
errorlog = spawn('tail', ['-f', 'error.log']);
errorlog.stdout.on('data', function (data) {
console.log(data.toString().replace(/^(.+)$/mg, 'error: $1'));
});
}).on('data', (msg) => {
msg = msg.toString();
if(msg === '__disconnect'){
console.log('Server shutting down.');
return cleanup();
}
// Generic message handler
console.log('server: ', data)
}).on('error', (data) => {
console.error('Unable to connect to Service Socket.', data);
process.exit(1);
});
function cmdouthndlr(type, args) {
var t = Math.ceil((commandline.line.length + 3) / process.stdout.columns);
var text = util.format.apply(console, args);
commandline.output.write("\n\x1B[" + t + "A\x1B[0J");
commandline.output.write(text + "\n");
commandline.output.write(Array(t).join("\n\x1B[E"));
commandline._refreshLine();
}
function cleanup(){
console.info('\n',"Terminating.",'\n');
eventlog.kill('SIGTERM');
syslog.kill('SIGTERM');
client.end();
process.exit(0);
}
function tabcomplete(line) {
return [COMPLETIONS.filter((cv)=>{ return cv.indexOf(line) == 0; }), line];
}

248
server.js Normal file
View file

@ -0,0 +1,248 @@
var path = require("path");
var fs = require("fs");
var express = require("express");
var Config = require("./config");
var Logger = require("./logger");
var Channel = require("./channel");
var User = require("./user");
const VERSION = "2.3.1";
function getIP(req) {
var raw = req.connection.remoteAddress;
var forward = req.header("x-forwarded-for");
if(Server.cfg["trust-x-forward"] && forward) {
var ip = forward.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
return raw;
}
function getSocketIP(socket) {
var raw = socket.handshake.address.address;
if(Server.cfg["trust-x-forward"]) {
if(typeof socket.handshake.headers["x-forwarded-for"] == "string") {
var ip = socket.handshake.headers["x-forwarded-for"]
.split(",")[0];
Logger.syslog.log("REVPROXY " + raw + " => " + ip);
return ip;
}
}
return raw;
}
var Server = {
channels: [],
channelLoaded: function (name) {
for(var i in this.channels) {
if(this.channels[i].canonical_name == name.toLowerCase())
return true;
}
return false;
},
getChannel: function (name) {
for(var i in this.channels) {
if(this.channels[i].canonical_name == name.toLowerCase())
return this.channels[i];
}
var c = new Channel(name, this);
this.channels.push(c);
return c;
},
unloadChannel: function(chan) {
if(chan.registered)
chan.saveDump();
chan.playlist.die();
chan.logger.close();
for(var i in this.channels) {
if(this.channels[i].canonical_name == chan.canonical_name) {
this.channels.splice(i, 1);
break;
}
}
chan.name = "";
},
stats: null,
app: null,
io: null,
httpserv: null,
ioserv: null,
db: null,
ips: {},
acp: null,
httpaccess: null,
logHTTP: function (req, status) {
if(status === undefined)
status = 200;
var ip = req.connection.remoteAddress;
var ip2 = false;
if(this.cfg["trust-x-forward"])
ip2 = req.header("x-forwarded-for") || req.header("cf-connecting-ip");
var ipstr = !ip2 ? ip : ip + " (X-Forwarded-For " + ip2 + ")";
var url = req.url;
// Remove query
if(url.indexOf("?") != -1)
url = url.substring(0, url.lastIndexOf("?"));
this.httpaccess.log([ipstr, req.method, url, status, req.headers["user-agent"]].join(" "));
},
init: function () {
this.httpaccess = new Logger.Logger("httpaccess.log");
this.app = express();
// channel path
this.app.get("/r/:channel(*)", function (req, res, next) {
var c = req.params.channel;
if(!c.match(/^[\w-_]+$/)) {
res.redirect("/" + c);
}
else {
this.logHTTP(req);
res.sendfile(__dirname + "/www/channel.html");
}
}.bind(this));
// api path
this.api = require("./api")(this);
this.app.get("/api/:apireq(*)", function (req, res, next) {
this.logHTTP(req);
this.api.handle(req.url.substring(5), req, res);
}.bind(this));
this.app.get("/", function (req, res, next) {
this.logHTTP(req);
res.sendfile(__dirname + "/www/index.html");
}.bind(this));
// default path
this.app.get("/:thing(*)", function (req, res, next) {
var opts = {
root: __dirname + "/www",
maxAge: this.cfg["asset-cache-ttl"]
}
res.sendfile(req.params.thing, opts, function (err) {
if(err) {
this.logHTTP(req, err.status);
// Damn path traversal attacks
if(req.params.thing.indexOf("%2e") != -1) {
res.send("Don't try that again, I'll ban you");
Logger.syslog.log("WARNING: Attempted path "+
"traversal from /" + getIP(req));
Logger.syslog.log("URL: " + req.url);
}
// Something actually went wrong
else {
// Status codes over 500 are server errors
if(err.status >= 500)
Logger.errlog.log(err);
res.send(err.status);
}
}
else {
this.logHTTP(req);
}
}.bind(this));
}.bind(this));
// fallback
this.app.use(function (err, req, res, next) {
this.logHTTP(req, err.status);
if(err.status == 404) {
res.send(404);
} else {
next(err);
}
}.bind(this));
// bind servers
this.httpserv = this.app.listen(Server.cfg["web-port"],
Server.cfg["express-host"]);
this.ioserv = express().listen(Server.cfg["io-port"],
Server.cfg["express-host"]);
// init socket.io
this.io = require("socket.io").listen(this.ioserv);
this.io.set("log level", 1);
this.io.sockets.on("connection", function (socket) {
var ip = getSocketIP(socket);
socket._ip = ip;
if(this.db.checkGlobalBan(ip)) {
Logger.syslog.log("Disconnecting " + ip + " - gbanned");
socket.emit("kick", {
reason: "You're globally banned."
});
socket.disconnect(true);
return;
}
socket.on("disconnect", function () {
this.ips[ip]--;
}.bind(this));
if(!(ip in this.ips))
this.ips[ip] = 0;
this.ips[ip]++;
if(this.ips[ip] > Server.cfg["ip-connection-limit"]) {
socket.emit("kick", {
reason: "Too many connections from your IP address"
});
socket.disconnect(true);
return;
}
// finally a valid user
Logger.syslog.log("Accepted socket from /" + socket._ip);
new User(socket, this);
}.bind(this));
// init database
this.db = require("./database");
this.db.setup(Server.cfg);
this.db.init();
// init ACP
this.acp = require("./acp")(this);
// init stats
this.stats = require("./stats")(this);
// init media retriever
this.infogetter = require("./get-info")(this);
},
shutdown: function () {
Logger.syslog.log("Unloading channels");
for(var i in this.channels) {
if(this.channels[i].registered) {
Logger.syslog.log("Saving /r/" + this.channels[i].name);
this.channels[i].saveDump();
}
}
Logger.syslog.log("Goodbye");
process.exit(0);
}
};
Logger.syslog.log("Starting CyTube v" + VERSION);
fs.exists("chanlogs", function (exists) {
exists || fs.mkdir("chanlogs");
});
fs.exists("chandump", function (exists) {
exists || fs.mkdir("chandump");
});
Config.load(Server, "cfg.json", function () {
Server.init();
if(!Server.cfg["debug"]) {
process.on("uncaughtException", function (err) {
Logger.errlog.log("[SEVERE] Uncaught Exception: " + err);
Logger.errlog.log(err.stack);
});
process.on("SIGINT", function () {
Server.shutdown();
});
}
});

View file

@ -1 +0,0 @@
{ "env": { "node": true } }

View file

@ -1,59 +0,0 @@
import db from './database';
import Promise from 'bluebird';
const dbGetGlobalRank = Promise.promisify(db.users.getGlobalRank);
const dbMultiGetGlobalRank = Promise.promisify(db.users.getGlobalRanks);
const dbGetChannelRank = Promise.promisify(db.channels.getRank);
const dbMultiGetChannelRank = Promise.promisify(db.channels.getRanks);
const dbGetAliases = Promise.promisify(db.getAliases);
const DEFAULT_PROFILE = Object.freeze({ image: '', text: '' });
class Account {
constructor(ip, user, aliases) {
this.ip = ip;
this.user = user;
this.aliases = aliases;
this.channelRank = -1;
this.guestName = null;
this.update();
}
update() {
if (this.user !== null) {
this.name = this.user.name;
this.globalRank = this.user.global_rank;
} else if (this.guestName !== null) {
this.name = this.guestName;
this.globalRank = 0;
} else {
this.name = '';
this.globalRank = -1;
}
this.lowername = this.name.toLowerCase();
this.effectiveRank = Math.max(this.channelRank, this.globalRank);
this.profile = (this.user === null) ? DEFAULT_PROFILE : this.user.profile;
}
}
module.exports.Account = Account;
module.exports.rankForName = async function rankForNameAsync(name, channel) {
const [globalRank, channelRank] = await Promise.all([
dbGetGlobalRank(name),
dbGetChannelRank(channel, name)
]);
return Math.max(globalRank, channelRank);
};
module.exports.rankForIP = async function rankForIP(ip, channel) {
const aliases = await dbGetAliases(ip);
const [globalRanks, channelRanks] = await Promise.all([
dbMultiGetGlobalRank(aliases),
dbMultiGetChannelRank(channel, aliases)
]);
return Math.max.apply(Math, globalRanks.concat(channelRanks));
};

View file

@ -1,285 +0,0 @@
var Logger = require("./logger");
var Server = require("./server");
var db = require("./database");
var util = require("./utilities");
import { v4 as uuidv4 } from 'uuid';
function eventUsername(user) {
return user.getName() + "@" + user.realip;
}
function handleAnnounce(user, data) {
var sv = Server.getServer();
sv.announce({
id: uuidv4(),
title: data.title,
text: data.content,
from: user.getName()
});
Logger.eventlog.log("[acp] " + eventUsername(user) + " opened announcement `" +
data.title + "`");
}
function handleAnnounceClear(user) {
Server.getServer().announce(null);
Logger.eventlog.log("[acp] " + eventUsername(user) + " cleared announcement");
}
function handleGlobalBan(user, data) {
const globalBanDB = db.getGlobalBanDB();
globalBanDB.addGlobalIPBan(data.ip, data.note).then(() => {
Logger.eventlog.log("[acp] " + eventUsername(user) + " global banned " + data.ip);
return globalBanDB.listGlobalBans().then(bans => {
// Why is it called reason in the DB and note in the socket frame?
// Who knows...
const mappedBans = bans.map(ban => {
return { ip: ban.ip, note: ban.reason };
});
user.socket.emit("acp-gbanlist", mappedBans);
});
}).catch(error => {
user.socket.emit("errMessage", {
msg: error.message
});
});
}
function handleGlobalBanDelete(user, data) {
const globalBanDB = db.getGlobalBanDB();
globalBanDB.removeGlobalIPBan(data.ip).then(() => {
Logger.eventlog.log("[acp] " + eventUsername(user) + " un-global banned " +
data.ip);
return globalBanDB.listGlobalBans().then(bans => {
// Why is it called reason in the DB and note in the socket frame?
// Who knows...
const mappedBans = bans.map(ban => {
return { ip: ban.ip, note: ban.reason };
});
user.socket.emit("acp-gbanlist", mappedBans);
});
}).catch(error => {
user.socket.emit("errMessage", {
msg: error.message
});
});
}
function handleListUsers(user, data) {
var value = data.value;
var field = data.field;
value = (typeof value !== 'string') ? '' : value;
field = (typeof field !== 'string') ? 'name' : field;
var fields = ["id", "name", "global_rank", "email", "ip", "time"];
if(!fields.includes(field)){
user.socket.emit("errMessage", {
msg: `The field "${field}" doesn't exist or isn't searchable.`
});
return;
}
db.users.search(field, value, fields, function (err, users) {
if (err) {
user.socket.emit("errMessage", {
msg: err
});
return;
}
user.socket.emit("acp-list-users", users);
});
}
function handleSetRank(user, data) {
var name = data.name;
var rank = data.rank;
if (typeof name !== "string" || typeof rank !== "number") {
return;
}
if (rank >= user.global_rank) {
user.socket.emit("errMessage", {
msg: "You are not permitted to promote others to equal or higher rank than " +
"yourself."
});
return;
}
db.users.getGlobalRank(name, function (err, oldrank) {
if (err) {
user.socket.emit("errMessage", {
msg: err
});
return;
}
if (oldrank >= user.global_rank) {
user.socket.emit("errMessage", {
msg: "You are not permitted to change the rank of users who rank " +
"higher than you."
});
return;
}
db.users.setGlobalRank(name, rank, function (err) {
if (err) {
user.socket.emit("errMessage", {
msg: err
});
} else {
Logger.eventlog.log("[acp] " + eventUsername(user) + " set " + name +
"'s global_rank to " + rank);
user.socket.emit("acp-set-rank", data);
}
});
});
}
function handleResetPassword(user, data, ack) {
var name = data.name;
var email = data.email;
if (typeof name !== "string" || typeof email !== "string") {
return;
}
db.users.getGlobalRank(name, function (err, rank) {
if (rank >= user.global_rank) {
user.socket.emit("errMessage", {
msg: "You don't have permission to reset the password for " + name
});
return;
}
var hash = util.sha1(util.randomSalt(64));
var expire = Date.now() + 86400000;
db.addPasswordReset({
ip: "",
name: name,
email: email,
hash: hash,
expire: expire
}, function (err) {
if (err) {
ack && ack({ error: err });
return;
}
Logger.eventlog.log("[acp] " + eventUsername(user) + " initialized a " +
"password recovery for " + name);
ack && ack({ hash });
});
});
}
function handleListChannels(user, data) {
var field = data.field;
var value = data.value;
if (typeof field !== "string" || typeof value !== "string") {
return;
}
var dbfunc;
if (field === "owner") {
dbfunc = db.channels.searchOwner;
} else {
dbfunc = db.channels.search;
}
dbfunc(value, function (err, rows) {
if (err) {
user.socket.emit("errMessage", {
msg: err
});
return;
}
user.socket.emit("acp-list-channels", rows);
});
}
function handleDeleteChannel(user, data) {
var name = data.name;
if (typeof data.name !== "string") {
return;
}
var sv = Server.getServer();
if (sv.isChannelLoaded(name)) {
sv.getChannel(name).users.forEach(function (u) {
u.kick("Channel shutting down");
});
}
db.channels.drop(name, function (err) {
Logger.eventlog.log("[acp] " + eventUsername(user) + " deleted channel " + name);
if (err) {
user.socket.emit("errMessage", {
msg: err
});
} else {
user.socket.emit("acp-delete-channel", {
name: name
});
}
});
}
function handleListActiveChannels(user) {
user.socket.emit("acp-list-activechannels", Server.getServer().packChannelList(false, true));
}
function handleForceUnload(user, data) {
var name = data.name;
if (typeof name !== "string") {
return;
}
var sv = Server.getServer();
if (!sv.isChannelLoaded(name)) {
return;
}
var chan = sv.getChannel(name);
var users = Array.prototype.slice.call(chan.users);
chan.emit("empty");
users.forEach(function (u) {
u.kick("Channel shutting down");
});
Logger.eventlog.log("[acp] " + eventUsername(user) + " forced unload of " + name);
}
function init(user) {
var s = user.socket;
s.on("acp-announce", handleAnnounce.bind(this, user));
s.on("acp-announce-clear", handleAnnounceClear.bind(this, user));
s.on("acp-gban", handleGlobalBan.bind(this, user));
s.on("acp-gban-delete", handleGlobalBanDelete.bind(this, user));
s.on("acp-list-users", handleListUsers.bind(this, user));
s.on("acp-set-rank", handleSetRank.bind(this, user));
s.on("acp-reset-password", handleResetPassword.bind(this, user));
s.on("acp-list-channels", handleListChannels.bind(this, user));
s.on("acp-delete-channel", handleDeleteChannel.bind(this, user));
s.on("acp-list-activechannels", handleListActiveChannels.bind(this, user));
s.on("acp-force-unload", handleForceUnload.bind(this, user));
const globalBanDB = db.getGlobalBanDB();
globalBanDB.listGlobalBans().then(bans => {
// Why is it called reason in the DB and note in the socket frame?
// Who knows...
const mappedBans = bans.map(ban => {
return { ip: ban.ip, note: ban.reason };
});
user.socket.emit("acp-gbanlist", mappedBans);
}).catch(error => {
user.socket.emit("errMessage", {
msg: error.message
});
});
Logger.eventlog.log("[acp] Initialized ACP for " + eventUsername(user));
}
module.exports.init = init;

View file

@ -1,54 +0,0 @@
var AsyncQueue = function () {
this._q = [];
this._lock = false;
this._tm = 0;
};
AsyncQueue.prototype.next = function () {
if (this._q.length > 0) {
if (!this.lock())
return;
var item = this._q.shift();
var fn = item[0];
this._tm = Date.now() + item[1];
fn(this);
}
};
AsyncQueue.prototype.lock = function () {
if (this._lock) {
if (this._tm > 0 && Date.now() > this._tm) {
this._tm = 0;
return true;
}
return false;
}
this._lock = true;
return true;
};
AsyncQueue.prototype.release = function () {
var self = this;
if (!self._lock)
return false;
self._lock = false;
setImmediate(function () {
self.next();
});
return true;
};
AsyncQueue.prototype.queue = function (fn) {
var self = this;
self._q.push([fn, 20000]);
self.next();
};
AsyncQueue.prototype.reset = function () {
this._q = [];
this._lock = false;
};
module.exports = AsyncQueue;

View file

@ -1,183 +0,0 @@
/*
bgtask.js
Registers background jobs to run periodically while the server is
running.
*/
var Config = require("./config");
var db = require("./database");
var Promise = require("bluebird");
const shows = require('./shows');
const calendarDB = require('./database/calendar-integrations');
const integrationsApi = require('./web/routes/api/integrations');
const LOGGER = require('@calzoneman/jsli')('bgtask');
var init = null;
/* Alias cleanup */
function initAliasCleanup() {
var CLEAN_INTERVAL = parseInt(Config.get("aliases.purge-interval"));
var CLEAN_EXPIRE = parseInt(Config.get("aliases.max-age"));
setInterval(function () {
db.cleanOldAliases(CLEAN_EXPIRE, function (err) {
LOGGER.info("Cleaned old aliases");
if (err)
LOGGER.error(err);
});
}, CLEAN_INTERVAL);
}
/* Password reset cleanup */
function initPasswordResetCleanup() {
var CLEAN_INTERVAL = 8*60*60*1000;
setInterval(function () {
db.cleanOldPasswordResets(function (err) {
if (err)
LOGGER.error(err);
});
}, CLEAN_INTERVAL);
}
function initChannelDumper(Server) {
const chanPath = Config.get('channel-path');
var CHANNEL_SAVE_INTERVAL = parseInt(Config.get("channel-save-interval"))
* 60000;
setInterval(function () {
if (Server.channels.length === 0) {
return;
}
var wait = CHANNEL_SAVE_INTERVAL / Server.channels.length;
LOGGER.info(`Saving channels with delay ${wait}`);
Promise.reduce(Server.channels, (_, chan) => {
return Promise.delay(wait).then(async () => {
if (!chan.dead && chan.users && chan.users.length > 0) {
try {
await chan.saveState();
LOGGER.info(`Saved /${chanPath}/${chan.name}`);
} catch (error) {
LOGGER.error(
'Failed to save /%s/%s: %s',
chanPath,
chan ? chan.name : '<undefined>',
error.stack
);
}
}
}).catch(error => {
LOGGER.error(`Failed to save channel: ${error.stack}`);
});
}, 0).catch(error => {
LOGGER.error(`Failed to save channels: ${error.stack}`);
});
}, CHANNEL_SAVE_INTERVAL);
}
function initAccountCleanup() {
setInterval(() => {
(async () => {
let rows = await db.users.findAccountsPendingDeletion();
for (let row of rows) {
try {
await db.users.purgeAccount(row.id);
LOGGER.info('Purged account from request %j', row);
} catch (error) {
LOGGER.error('Error purging account %j: %s', row, error.stack);
}
}
})().catch(error => {
LOGGER.error('Error purging deleted accounts: %s', error.stack);
});
}, 3600 * 1000);
}
function initShowScheduler() {
var SCHEDULE_INTERVAL = 15 * 1000;
var running = false;
setInterval(async () => {
if (running) {
return;
}
running = true;
try {
await shows.pollAndRunDueShows();
} catch (error) {
LOGGER.error('Show scheduler failure: %s', error.stack || error);
} finally {
running = false;
}
}, SCHEDULE_INTERVAL);
}
function initCalendarAutoSyncScheduler() {
const AUTO_SYNC_INTERVAL_MS = 60 * 1000;
const AUTO_SYNC_PERIOD_MINUTES = 30;
let running = false;
function inStaggerSlot(integrationId, now) {
const slot = Number(integrationId || 0) % AUTO_SYNC_PERIOD_MINUTES;
const minute = new Date(now).getUTCMinutes() % AUTO_SYNC_PERIOD_MINUTES;
return slot === minute;
}
setInterval(async () => {
if (running) {
return;
}
running = true;
try {
const now = Date.now();
const rows = await calendarDB.listConnectedByProvider('google');
for (const integration of rows) {
if (!inStaggerSlot(integration.id, now)) {
continue;
}
if (integration.last_sync_at && now - integration.last_sync_at < AUTO_SYNC_PERIOD_MINUTES * 60 * 1000) {
continue;
}
try {
await integrationsApi.syncIntegrationNow({
provider: 'google',
integration,
channelRow: { id: integration.channel_id },
enforceCooldown: false
});
} catch (err) {
LOGGER.warn(
'Auto calendar sync failed integration=%s channel=%s: %s',
integration.id,
integration.channel_id,
err && (err.stack || err.message) || err
);
}
}
} catch (err) {
LOGGER.error('Calendar auto-sync scheduler failure: %s', err.stack || err);
} finally {
running = false;
}
}, AUTO_SYNC_INTERVAL_MS);
}
module.exports = function (Server) {
if (init === Server) {
LOGGER.warn("Attempted to re-init background tasks");
return;
}
init = Server;
initAliasCleanup();
initChannelDumper(Server);
initPasswordResetCleanup();
initAccountCleanup();
initShowScheduler();
initCalendarAutoSyncScheduler();
};

Some files were not shown because too many files have changed in this diff Show more