Begin refactoring

This commit is contained in:
calzoneman 2013-04-02 14:39:56 -05:00
parent 52fe508628
commit 0afc184402
2 changed files with 325 additions and 53 deletions

160
channel-new.js Normal file
View File

@ -0,0 +1,160 @@
/*
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 Channel = function(name) {
Logger.syslog.log("Opening channel " + name);
this.name = name;
// Initialize defaults
this.registered = false;
this.users = [];
this.queue = [];
this.library = {};
this.position = -1;
this.media = null;
this.leader = null;
this.chatbuffer = [];
this.openqueue = false;
this.poll = false;
this.voteskip = false;
this.opts = {
qopen_allow_qnext: false,
qopen_allow_move: false,
qopen_allow_playnext: false,
qopen_allow_delete: false,
allow_voteskip: true,
pagetitle: this.name,
customcss: ""
};
this.filters = [
[/`([^`]+)`/g , "<code>$1</code>" , true],
[/\*([^\*]+)\*/g , "<strong>$1</strong>", true],
[/(^| )_([^_]+)_/g , "$1<em>$2</em>" , true],
[/\\\\([-a-zA-Z0-9]+)/g, "[](/$1)" , true]
];
this.motd = {
motd: "",
html: ""
};
this.ipbans = {};
this.logger = new Logger.Logger("chanlogs/" + this.name + ".log");
this.i = 0;
this.time = new Date().getTime();
Database.loadChannel(this);
if(this.registered) {
this.loadDump();
}
}
/* REGION Channel data */
Channel.prototype.loadDump = function() {
fs.readFile("chandump/" + this.name, function(err, data) {
if(err) {
return;
}
try {
this.logger.log("*** Loading channel dump from disk");
data = JSON.parse(data);
for(var i = 0; i < data.queue.length; i++) {
var e = data.queue[i];
this.queue.push(new Media(e.id, e.title, e.seconds, e.type));
}
this.sendAll("playlist", {
pl: this.queue
});
this.position = data.position - 1;
if(this.position < -1)
this.position = -1;
if(this.queue.length > 0)
this.playNext();
this.opts = data.opts;
if(data.filters) {
this.filters = new Array(data.filters.length);
for(var i = 0; i < data.filters.length; i++) {
this.filters[i] = [new RegExp(data.filters[i][0]),
data.filters[i][1],
data.filters[i][2]];
}
}
if(data.motd) {
this.motd = data.motd;
}
}
catch(e) {
Logger.errlog.log("Channel dump load failed: ");
Logger.errlog.log(e);
}
}.bind(this));
}
Channel.prototype.saveDump = function() {
}
Channel.prototype.tryRegister = function(user) {
if(this.registered) {
user.socket.emit("registerChannel", {
success: false,
error: "This channel is already registered"
});
}
else if(!user.loggedIn) {
user.socket.emit("registerChannel", {
success: false,
error: "You must log in to register a channel"
});
}
else if(!Rank.hasPermission(user, "registerChannel")) {
user.socket.emit("registerChannel", {
success: false,
error: "You don't have permission to register this channel"
});
}
else {
if(Database.registerChannel(this)) {
this.registered = true;
this.saveRank(user);
user.socket.emit("registerChannel", {
success: true,
});
this.logger.log("*** " + user.name + " registered the channel");
Logger.syslog.log("Channel " + this.name + " was registered by " + user.name);
}
else {
user.socket.emit("registerChannel", {
success: false,
error: "Unable to register channel, see an admin"
});
}
}
}
Channel.prototype.getRank = function(user) {
if(!this.registered) {
return Rank.Guest;
}
return Database.lookupChannelRank(this.name, user.name);
}
Channel.prototype.saveRank = function(user) {
return Database.saveChannelRank(this.name, user);
}
Channel.prototype.cacheMedia = function(media) {
this.library[media.id] = media;
if(this.registered) {
return Database.cacheMedia(this.name, media);
}
return false;
}

View File

@ -12,19 +12,29 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
var mysql = require("mysql-libmysqlclient"); var mysql = require("mysql-libmysqlclient");
var Config = require("./config.js"); var Config = require("./config.js");
var Logger = require("./logger.js"); var Logger = require("./logger.js");
var Rank = require("./rank.js");
var initialized = false; var initialized = false;
exports.getConnection = function() {
var db = mysql.createConnectionSync();
db.connectSync(Config.MYSQL_SERVER, Config.MYSQL_USER,
Config.MYSQL_PASSWORD, Config.MYSQL_DB);
if(!db.connectedSync()) {
Logger.errlog.log("database.getConnection: DB connection failed");
return false;
}
return db;
}
exports.init = function() { exports.init = function() {
if(initialized) if(initialized)
return; return;
var db = mysql.createConnectionSync(); var db = exports.getConnection();
db.connectSync(Config.MYSQL_SERVER, Config.MYSQL_USER, if(!db) {
Config.MYSQL_PASSWORD, Config.MYSQL_DB); Logger.errlog.log("database.init: DB conection failed");
if(!db.connectedSync()) { return;
Logger.errlog.log("database.init: DB connection failed");
return false;
} }
var query = "CREATE TABLE IF NOT EXISTS `channels` \ var query = "CREATE TABLE IF NOT EXISTS `channels` \
(`id` INT NOT NULL AUTO_INCREMENT, \ (`id` INT NOT NULL AUTO_INCREMENT, \
@ -55,64 +65,166 @@ exports.init = function() {
return true; return true;
} }
exports.listChannels = function() { exports.loadChannel = function(chan) {
if(!initialized) var db = exports.getConnection();
return false; if(!db) {
var db = mysql.createConnectionSync(); chan.logger.log("!!! Could not connect to database");
db.connectSync(Config.MYSQL_SERVER, Config.MYSQL_USER, return;
Config.MYSQL_PASSWORD, Config.MYSQL_DB); }
var query = "SELECT * FROM `channels`"; // Check if channel exists
var query = "SELECT * FROM channels WHERE name='{}'"
.replace("{}", chan.name);
var results = db.querySync(query); var results = db.querySync(query);
if(!results) { if(!results) {
Logger.errlog.log("database.listChannels: query failed"); Logger.errlog.log("Channel.loadMysql: Channel query failed");
return false; return;
} }
if(results) {
var rows = results.fetchAllSync(); var rows = results.fetchAllSync();
db.closeSync(); if(rows.length == 0) {
return rows; Logger.syslog.log("Channel " + chan.name + " is unregistered.");
return;
} }
}; chan.registered = true;
exports.listUsers = function() { // Load library
if(!initialized) var query = "SELECT * FROM chan_{}_library"
return false; .replace("{}", chan.name);
var db = mysql.createConnectionSync();
db.connectSync(Config.MYSQL_SERVER, Config.MYSQL_USER,
Config.MYSQL_PASSWORD, Config.MYSQL_DB);
var query = "SELECT * FROM `registrations`";
var results = db.querySync(query); var results = db.querySync(query);
if(!results) { if(!results) {
Logger.errlog.log("database.listUsers: query failed"); Logger.errlog.log("Channel.loadMysql: failed to load library for " + chan.name);
return false; return;
} }
if(results) {
var rows = results.fetchAllSync(); var rows = results.fetchAllSync();
db.closeSync(); for(var i = 0; i < rows.length; i++) {
return rows; chan.library[rows[i].id] = new Media(rows[i].id, rows[i].title, rows[i].seconds, rows[i].type);
} }
};
exports.listChannelRanks = function(chan) { // Load bans
if(!initialized) var query = "SELECT * FROM chan_{}_bans"
return false; .replace("{}", chan.name);
var db = mysql.createConnectionSync();
db.connectSync(Config.MYSQL_SERVER, Config.MYSQL_USER,
Config.MYSQL_PASSWORD, Config.MYSQL_DB);
var query = "SELECT * FROM `chan_{}_ranks`"
.replace(/\{\}/, chan);
console.log(query);
var results = db.querySync(query); var results = db.querySync(query);
if(!results) { if(!results) {
Logger.errlog.log("database.listChannelRanks: query failed"); Logger.errlog.log("Channel.loadMysql: failed to load banlist for " + chan.name);
return false; return;
}
var rows = results.fetchAllSync();
for(var i = 0; i < rows.length; i++) {
chan.ipbans[rows[i].ip] = [rows[i].name, rows[i].banner];
} }
if(results) { chan.logger.log("*** Loaded channel from database");
var rows = results.fetchAllSync(); Logger.syslog.log("Loaded channel " + chan.name + " from database");
db.closeSync(); db.closeSync();
return rows;
}
exports.registerChannel = function(chan) {
var db = exports.getConnection();
if(!db) {
chan.logger.log("!!! Could not connect to database");
return false;
} }
}; // Create library table
var query= "CREATE TABLE `chan_{}_library` \
(`id` VARCHAR(255) NOT NULL, \
`title` VARCHAR(255) NOT NULL, \
`seconds` INT NOT NULL, \
`playtime` VARCHAR(8) NOT NULL, \
`type` VARCHAR(2) NOT NULL, \
PRIMARY KEY (`id`)) \
ENGINE = MyISAM;"
.replace("{}", chan.name);
var results = db.querySync(query);
// Create rank table
var query = "CREATE TABLE `chan_{}_ranks` (\
`name` VARCHAR( 32 ) NOT NULL ,\
`rank` INT NOT NULL ,\
UNIQUE (\
`name`\
)\
) ENGINE = MYISAM"
.replace("{}", chan.name);
results = db.querySync(query) || results;
// Create ban table
var query = "CREATE TABLE `chan_{}_bans` (\
`ip` VARCHAR( 15 ) NOT NULL ,\
`name` VARCHAR( 32 ) NOT NULL ,\
`banner` VARCHAR( 32 ) NOT NULL ,\
PRIMARY KEY (\
`ip`\
)\
) ENGINE = MYISAM"
.replace("{}", chan.name);
results = db.querySync(query) || results;
// Insert into global channel table
var query = "INSERT INTO channels (`id`, `name`) VALUES (NULL, '{}')"
.replace("{}", chan.name);
results = db.querySync(query) || results;
db.closeSync();
return results;
}
exports.lookupChannelRank = function(channame, username) {
var db = exports.getConnection();
if(!db) {
Logger.errlog.log("database.lookupChannelRank: DB connection failed");
return Rank.Guest;
}
var query = "SELECT * FROM chan_{1}_ranks WHERE name='{2}'"
.replace("{1}", channame)
.replace("{2}", username);
var results = db.querySync(query);
if(!results)
return Rank.Guest;
var rows = results.fetchAllSync();
if(rows.length == 0) {
return Rank.Guest;
}
db.closeSync();
return rows[0].rank;
}
exports.saveChannelRank = function(channame, user) {
var db = exports.getConnection();
if(!db) {
Logger.errlog.log("database.saveChannelRank: DB connection failed");
return false;
}
var query = "UPDATE chan_{1}_ranks SET rank='{2}' WHERE name='{3}'"
.replace("{1}", channame)
.replace("{2}", user.rank)
.replace("{3}", user.name);
var results = db.querySync(query);
// Gonna have to insert a new one, bugger
if(!results.fetchAllSync) {
var query = "INSERT INTO chan_{1}_ranks (`name`, `rank`) VALUES ('{2}', '{3}')"
.replace("{1}", channame)
.replace("{2}", user.name)
.replace("{3}", user.rank);
results = db.querySync(query);
}
db.closeSync();
return results;
}
exports.cacheMedia = function(channame, media) {
var db = exports.getConnection();
if(!db) {
Logger.errlog.log("database.cacheMedia: DB connection failed");
return false;
}
var query = "INSERT INTO chan_{1}_library VALUES ('{2}', '{3}', {4}, '{5}', '{6}')"
.replace("{1}", channame)
.replace("{2}", media.id)
.replace("{3}", media.title)
.replace("{4}", media.seconds)
.replace("{5}", media.duration)
.replace("{6}", media.type);
var results = db.querySync(query);
db.closeSync();
return results;
}