server.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. Meteor.startup(function() {
  2. reCAPTCHA.config({
  3. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  4. });
  5. Avatar.setOptions({
  6. fallbackType: "initials",
  7. defaultImageUrl: "http://static.boredpanda.com/blog/wp-content/uploads/2014/04/amazing-fox-photos-182.jpg",
  8. generateCSS: true,
  9. imageSizes: {
  10. 'header': 40
  11. }
  12. });
  13. var stations = [{tag: "edm", display: "EDM"}, {tag: "pop", display: "Pop"}]; //Rooms to be set on server startup
  14. for(var i in stations){
  15. if(Rooms.find({type: stations[i]}).count() === 0){
  16. createRoom(stations[i].display, stations[i].tag, false);
  17. }
  18. }
  19. emojione.ascii = true;
  20. });
  21. var default_song = {id: "xKVcVSYmesU", mid: "ABCDEF", likes: 0, dislikes: 0, title: "Immortals", artist: "Fall Out Boy", img: "http://c.directlyrics.com/img/upload/fall-out-boy-sixth-album-cover.jpg", type: "YouTube", duration: 181, skipDuration: 0, requestedBy: "NONE", approvedBy: "NONE"};
  22. Alerts.update({active: true}, {$set: {active: false}}, { multi: true });
  23. var stations = [];
  24. var voteNum = 0;
  25. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  26. function createUniqueSongId() {
  27. var code = "";
  28. for (var i = 0; i < 6; i++) {
  29. code += chars[Math.floor(Math.random() * chars.length)];
  30. }
  31. if (Playlists.find({"songs.mid": code}).count() > 0) {
  32. return createUniqueSongId();
  33. } else {
  34. return code;
  35. }
  36. }
  37. function checkUsersPR() {
  38. var output = {};
  39. var connections = Meteor.server.stream_server.open_sockets;
  40. _.each(connections,function(connection){
  41. // named subscriptions
  42. if (connection._meteorSession !== undefined && connection._meteorSession !== null) {
  43. var subs = connection._meteorSession._namedSubs;
  44. //var ip = connection.remoteAddress;
  45. var used_subs = [];
  46. for (var sub in subs) {
  47. var mySubName = subs[sub]._name;
  48. if (subs[sub]._params.length > 0) {
  49. mySubName += subs[sub]._params[0]; // assume one id parameter for now
  50. }
  51. if (used_subs.indexOf(mySubName) === -1) {
  52. used_subs.push(mySubName);
  53. if (!output[mySubName]) {
  54. output[mySubName] = 1;
  55. } else {
  56. output[mySubName] += 1;
  57. }
  58. }
  59. }
  60. }
  61. // there are also these 'universal subscriptions'
  62. //not sure what these are, i count none in my tests
  63. //var usubs = connection._meteorSession._universalSubs;
  64. });
  65. var emptyStations = [];
  66. stations.forEach(function(station) {
  67. emptyStations.push(station);
  68. });
  69. for (var key in output) {
  70. getStation(key, function(station) {
  71. emptyStations.splice(emptyStations.indexOf(station), 1);
  72. Rooms.update({type: key}, {$set: {users: output[key]}});
  73. });
  74. }
  75. emptyStations.forEach(function(emptyStation) {
  76. Rooms.update({type: emptyStation.type}, {$set: {users: 0}});
  77. });
  78. return output;
  79. }
  80. function getStation(type, cb) {
  81. stations.forEach(function(station) {
  82. if (station.type === type) {
  83. cb(station);
  84. return;
  85. }
  86. });
  87. }
  88. function createRoom(display, tag, private) {
  89. var type = tag;
  90. if (Rooms.find({type: type}).count() === 0) {
  91. Rooms.insert({display: display, type: type, users: 0, private: private, currentSong: {song: default_song, started: 0}}, function(err) {
  92. if (err) {
  93. throw err;
  94. } else {
  95. stations.push(new Station(type));
  96. }
  97. });
  98. } else {
  99. return "Room already exists";
  100. }
  101. }
  102. function Station(type) {
  103. if (Playlists.find({type: type}).count() === 0) {
  104. Playlists.insert({type: type, songs: [default_song], lastSong: 0});
  105. } else if (Playlists.findOne({type: type}).songs.length === 0) {
  106. Playlists.update({type: type}, {$push: {songs: default_song}});
  107. }
  108. Meteor.publish(type, function() {
  109. return undefined;
  110. });
  111. var self = this;
  112. var startedAt = Date.now();
  113. var playlist = Playlists.findOne({type: type});
  114. var songs = playlist.songs;
  115. var currentSong = playlist.lastSong;
  116. if (currentSong < (songs.length - 1)) {
  117. currentSong++;
  118. } else currentSong = 0;
  119. var currentTitle = songs[currentSong].title;
  120. var res = Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}, users: 0}});
  121. console.log(res);
  122. this.skipSong = function() {
  123. self.voted = [];
  124. voteNum = 0;
  125. Rooms.update({type: type}, {$set: {votes: 0}});
  126. songs = Playlists.findOne({type: type}).songs;
  127. songs.forEach(function(song, index) {
  128. if (song.title === currentTitle) {
  129. currentSong = index;
  130. }
  131. });
  132. if (currentSong < (songs.length - 1)) {
  133. currentSong++;
  134. } else currentSong = 0;
  135. if (songs);
  136. if (currentSong === 0) {
  137. this.shufflePlaylist();
  138. } else {
  139. if (songs[currentSong].mid === undefined) {
  140. var newSong = songs[currentSong];
  141. newSong.mid = createUniqueSongId();
  142. songs[currentSong].mid = newSong.mid;
  143. Playlists.update({type: type, "songs": songs[currentSong]}, {$set: {"songs.$": newSong}});
  144. }
  145. currentTitle = songs[currentSong].title;
  146. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  147. Rooms.update({type: type}, {$set: {timePaused: 0}});
  148. this.songTimer();
  149. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  150. }
  151. };
  152. this.shufflePlaylist = function() {
  153. voteNum = 0;
  154. Rooms.update({type: type}, {$set: {votes: 0}});
  155. self.voted = [];
  156. songs = Playlists.findOne({type: type}).songs;
  157. currentSong = 0;
  158. Playlists.update({type: type}, {$set: {"songs": []}});
  159. songs = shuffle(songs);
  160. songs.forEach(function(song) {
  161. if (song.mid === undefined) {
  162. song.mid = createUniqueSongId();
  163. }
  164. Playlists.update({type: type}, {$push: {"songs": song}});
  165. });
  166. currentTitle = songs[currentSong].title;
  167. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  168. Rooms.update({type: type}, {$set: {timePaused: 0}});
  169. this.songTimer();
  170. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  171. };
  172. Rooms.update({type: type}, {$set: {timePaused: 0}});
  173. var timer;
  174. this.songTimer = function() {
  175. startedAt = Date.now();
  176. if (timer !== undefined) {
  177. timer.pause();
  178. }
  179. timer = new Timer(function() {
  180. self.skipSong();
  181. }, songs[currentSong].duration * 1000);
  182. };
  183. var state = Rooms.findOne({type: type}).state;
  184. this.pauseRoom = function() {
  185. if (state !== "paused") {
  186. timer.pause();
  187. Rooms.update({type: type}, {$set: {state: "paused"}});
  188. state = "paused";
  189. }
  190. };
  191. this.resumeRoom = function() {
  192. if (state !== "playing") {
  193. timer.resume();
  194. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  195. state = "playing";
  196. }
  197. };
  198. this.cancelTimer = function() {
  199. timer.pause();
  200. };
  201. this.getState = function() {
  202. return state;
  203. };
  204. this.type = type;
  205. var private = Rooms.findOne({type: type}).private;
  206. if (typeof private !== "boolean") {
  207. Rooms.update({type: type}, {$set: {"private": false}});
  208. private = false;
  209. }
  210. this.private = private;
  211. this.unlock = function() {
  212. if (self.private) {
  213. self.private = false;
  214. Rooms.update({type: type}, {$set: {"private": false}});
  215. }
  216. };
  217. this.lock = function() {
  218. if (!self.private) {
  219. self.private = true;
  220. Rooms.update({type: type}, {$set: {"private": true}});
  221. }
  222. };
  223. this.songTimer();
  224. this.voted = [];
  225. }
  226. function shuffle(array) {
  227. var currentIndex = array.length, temporaryValue, randomIndex ;
  228. // While there remain elements to shuffle...
  229. while (0 !== currentIndex) {
  230. // Pick a remaining element...
  231. randomIndex = Math.floor(Math.random() * currentIndex);
  232. currentIndex -= 1;
  233. // And swap it with the current element.
  234. temporaryValue = array[currentIndex];
  235. array[currentIndex] = array[randomIndex];
  236. array[randomIndex] = temporaryValue;
  237. }
  238. return array;
  239. }
  240. function Timer(callback, delay) {
  241. var timerId, start, remaining = delay;
  242. var timeWhenPaused = 0;
  243. var timePaused = new Date();
  244. this.pause = function() {
  245. Meteor.clearTimeout(timerId);
  246. remaining -= new Date() - start;
  247. timePaused = new Date();
  248. };
  249. this.resume = function() {
  250. start = new Date();
  251. Meteor.clearTimeout(timerId);
  252. timerId = Meteor.setTimeout(callback, remaining);
  253. timeWhenPaused += new Date() - timePaused;
  254. };
  255. this.timeWhenPaused = function() {
  256. return timeWhenPaused;
  257. };
  258. this.resume();
  259. }
  260. Meteor.users.deny({update: function () { return true; }});
  261. Meteor.users.deny({insert: function () { return true; }});
  262. Meteor.users.deny({remove: function () { return true; }});
  263. function getSongDuration(query, artistName){
  264. var duration;
  265. var search = query;
  266. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  267. for(var i in res.data){
  268. for(var j in res.data[i].items){
  269. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  270. duration = res.data[i].items[j].duration_ms / 1000;
  271. return duration;
  272. }
  273. }
  274. }
  275. return 0;
  276. }
  277. function getSongAlbumArt(query, artistName){
  278. var albumart;
  279. var search = query;
  280. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  281. for(var i in res.data){
  282. for(var j in res.data[i].items){
  283. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  284. albumart = res.data[i].items[j].album.images[1].url
  285. return albumart;
  286. }
  287. }
  288. }
  289. }
  290. //var room_types = ["edm", "nightcore"];
  291. var songsArr = [];
  292. Rooms.find({}).fetch().forEach(function(room) {
  293. var type = room.type;
  294. if (Playlists.find({type: type}).count() === 0) {
  295. Playlists.insert({type: type, songs: []});
  296. }
  297. if (Playlists.findOne({type: type}).songs.length === 0) {
  298. // Add a global video to Playlist so it can proceed
  299. } else {
  300. stations.push(new Station(type));
  301. }
  302. });
  303. Accounts.validateNewUser(function(user) {
  304. var username;
  305. if (user.services) {
  306. if (user.services.github) {
  307. username = user.services.github.username;
  308. } else if (user.services.facebook) {
  309. username = user.services.facebook.first_name;
  310. } else if (user.services.password) {
  311. username = user.username;
  312. }
  313. }
  314. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  315. throw new Meteor.Error(403, "An account with that username already exists.");
  316. } else {
  317. return true;
  318. }
  319. });
  320. Accounts.onCreateUser(function(options, user) {
  321. var username;
  322. if (user.services) {
  323. if (user.services.github) {
  324. username = user.services.github.username;
  325. } else if (user.services.facebook) {
  326. username = user.services.facebook.first_name;
  327. } else if (user.services.password) {
  328. username = user.username;
  329. }
  330. }
  331. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default", liked: [], disliked: [], settings: {showRating: false}, realname: ""};
  332. return user;
  333. });
  334. Meteor.publish("alerts", function() {
  335. return Alerts.find({active: true})
  336. });
  337. Meteor.publish("userData", function(userId) {
  338. if (userId !== undefined) {
  339. return Meteor.users.find(userId, {fields: {"services.github.username": 1, "punishments": 1}})
  340. } else {
  341. return undefined;
  342. }
  343. });
  344. Meteor.publish("allAlerts", function() {
  345. return Alerts.find({active: false})
  346. });
  347. Meteor.publish("playlists", function() {
  348. return Playlists.find({})
  349. });
  350. Meteor.publish("rooms", function() {
  351. return Rooms.find({});
  352. });
  353. Meteor.publish("queues", function() {
  354. return Queues.find({});
  355. });
  356. Meteor.publish("reports", function() {
  357. return Reports.find({});
  358. });
  359. Meteor.publish("chat", function() {
  360. return Chat.find({});
  361. });
  362. Meteor.publish("userProfiles", function(username) {
  363. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  364. if (settings !== undefined && settings.profile.settings) {
  365. settings = settings.profile.settings;
  366. if (settings.showRating === true) {
  367. return Meteor.users.find({"profile.usernameL": username}, {fields: {"profile.username": 1, "profile.usernameL": 1, "profile.rank": 1, createdAt: 1, "profile.liked": 1, "profile.disliked": 1, "profile.settings": 1, "profile.realname": 1}});
  368. }
  369. }
  370. return Meteor.users.find({"profile.usernameL": username}, {fields: {"profile.username": 1, "profile.usernameL": 1, "profile.rank": 1, createdAt: 1, "profile.settings": 1, "profile.realname": 1}});
  371. });
  372. Meteor.publish("isAdmin", function() {
  373. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  374. });
  375. Meteor.publish("isModerator", function() {
  376. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  377. });
  378. function isAdmin() {
  379. var userData = Meteor.users.find(Meteor.userId());
  380. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  381. return true;
  382. } else {
  383. return false;
  384. }
  385. }
  386. function isModerator() {
  387. var userData = Meteor.users.find(Meteor.userId());
  388. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  389. return true;
  390. } else {
  391. return isAdmin();
  392. }
  393. }
  394. function isBanned() {
  395. var userData = Meteor.users.findOne(Meteor.userId());
  396. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  397. var ban = userData.punishments.ban;
  398. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  399. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  400. return false;
  401. } else {
  402. return true;
  403. }
  404. } else {
  405. return false;
  406. }
  407. }
  408. function isMuted() {
  409. var userData = Meteor.users.findOne(Meteor.userId());
  410. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  411. var mute = userData.punishments.mute;
  412. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  413. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  414. return false;
  415. } else {
  416. return true;
  417. }
  418. } else {
  419. return false;
  420. }
  421. }
  422. Meteor.methods({
  423. lockRoom: function(type) {
  424. if (isAdmin() && !isBanned()) {
  425. getStation(type, function(station){
  426. station.lock();
  427. });
  428. } else {
  429. throw new Meteor.Error(403, "Invalid permissions.");
  430. }
  431. },
  432. unlockRoom: function(type) {
  433. if (isAdmin() && !isBanned()) {
  434. getStation(type, function(station){
  435. station.unlock();
  436. });
  437. } else {
  438. throw new Meteor.Error(403, "Invalid permissions.");
  439. }
  440. },
  441. banUser: function(username, period, reason) {
  442. if (isAdmin() && !isBanned()) {
  443. var user = Meteor.user();
  444. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  445. var bannedUntil = (new Date).getTime() + (period * 1000);
  446. if (bannedUntil > 8640000000000000) {
  447. bannedUntil = 8640000000000000;
  448. }
  449. bannedUntil = new Date(bannedUntil);
  450. var banObject = {bannedBy: user.profile.usernameL, bannedAt: new Date(Date.now()), bannedReason: reason, bannedUntil: bannedUntil};
  451. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  452. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  453. } else {
  454. throw new Meteor.Error(403, "Invalid permissions.");
  455. }
  456. },
  457. muteUser: function(username, period) {
  458. if (isAdmin() && !isBanned()) {
  459. var user = Meteor.user();
  460. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  461. if (period === undefined || Number(period) === 0) {
  462. mutedUntil = 8640000000000000;
  463. } else {
  464. var mutedUntil = (new Date).getTime() + (period * 1000);
  465. if (mutedUntil > 8640000000000000) {
  466. mutedUntil = 8640000000000000;
  467. }
  468. }
  469. mutedUntil = new Date(mutedUntil);
  470. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  471. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  472. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  473. } else {
  474. throw new Meteor.Error(403, "Invalid permissions.");
  475. }
  476. },
  477. unbanUser: function(username) {
  478. if (isAdmin() && !isBanned()) {
  479. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  480. } else {
  481. throw new Meteor.Error(403, "Invalid permissions.");
  482. }
  483. },
  484. unsilenceUser: function(username) {
  485. if (isAdmin() && !isBanned()) {
  486. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  487. } else {
  488. throw new Meteor.Error(403, "Invalid permissions.");
  489. }
  490. },
  491. isBanned: function() {
  492. return isBanned();
  493. },
  494. isMuted: function() {
  495. return isMuted();
  496. },
  497. updateSettings: function(showRating) {
  498. if (Meteor.userId() && !isBanned()) {
  499. var user = Meteor.user();
  500. if (showRating !== true && showRating !== false) {
  501. showRating = false;
  502. }
  503. if (user.profile.settings) {
  504. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  505. } else {
  506. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  507. }
  508. } else {
  509. throw new Meteor.Error(403, "Invalid permissions.");
  510. }
  511. },
  512. resetRating: function() {
  513. if (isAdmin() && !isBanned()) {
  514. stations.forEach(function (station) {
  515. var type = station.type;
  516. var temp_songs = Playlists.findOne({type: type}).songs;
  517. Playlists.update({type: type}, {$set: {"songs": []}});
  518. temp_songs.forEach(function (song) {
  519. song.likes = 0;
  520. song.dislikes = 0;
  521. Playlists.update({type: type}, {$push: {"songs": song}});
  522. });
  523. });
  524. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  525. } else {
  526. throw Meteor.Error(403, "Invalid permissions.");
  527. }
  528. },
  529. removeAlerts: function() {
  530. if (isAdmin() && !isBanned()) {
  531. Alerts.update({active: true}, {$set: {active: false}}, { multi: true });
  532. } else {
  533. throw Meteor.Error(403, "Invalid permissions.");
  534. }
  535. },
  536. addAlert: function(description, priority) {
  537. if (isAdmin()) {
  538. if (description.length > 0 && description.length < 400) {
  539. var username = Meteor.user().profile.username;
  540. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  541. priority = "warning";
  542. }
  543. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  544. return true;
  545. } else {
  546. throw Meteor.Error(403, "Invalid description length.");
  547. }
  548. } else {
  549. throw Meteor.Error(403, "Invalid permissions.");
  550. }
  551. },
  552. sendMessage: function(type, message) {
  553. if (Meteor.userId() && !isBanned() && !isMuted()) {
  554. var user = Meteor.user();
  555. var time = new Date();
  556. var rawrank = user.profile.rank;
  557. var username = user.profile.username;
  558. var profanity = false;
  559. var mentionUsername;
  560. var isCurUserMentioned;
  561. if(message.indexOf("@") !== -1) {
  562. var messageArr = message.split(" ");
  563. for (var i in messageArr) {
  564. if (messageArr[i].indexOf("@") !== -1) {
  565. var mention = messageArr[i];
  566. }
  567. }
  568. Meteor.users.find().forEach(function(user){
  569. if(mention.indexOf(user.profile.username) !== -1){
  570. mentionUsername = true;
  571. isCurUserMentioned = Meteor.user().profile.username === user.profile.username;
  572. };
  573. })
  574. }
  575. if (!message.replace(/\s/g, "").length > 0) {
  576. throw new Meteor.Error(406, "Message length cannot be 0.");
  577. }
  578. if (message.length > 300) {
  579. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  580. }
  581. else if (user.profile.rank === "admin") {
  582. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function(err,res){
  583. if(res.content.indexOf("true") > -1){
  584. return true;
  585. } else{
  586. Chat.insert({type: type, rawrank: rawrank, rank: "[A]", message: message, curUserMention: isCurUserMentioned, isMentioned: mentionUsername, time: time, username: username});
  587. }
  588. });
  589. return true;
  590. }
  591. else if (user.profile.rank === "moderator") {
  592. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function(err,res){
  593. if(res.content.indexOf("true") > -1){
  594. return true;
  595. } else{
  596. Chat.insert({type: type, rawrank: rawrank, rank: "[M]", message: message, time: time, username: username});
  597. }
  598. });
  599. return true;
  600. }
  601. else {
  602. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function(err,res){
  603. if(res.content.indexOf("true") > -1){
  604. return true;
  605. } else{
  606. Chat.insert({type: type, rawrank: rawrank, rank: "", message: message, time: time, username: username});
  607. }
  608. });
  609. return true;
  610. }
  611. } else {
  612. throw new Meteor.Error(403, "Invalid permissions.");
  613. }
  614. },
  615. likeSong: function(mid) {
  616. if (Meteor.userId() && !isBanned()) {
  617. var user = Meteor.user();
  618. if (user.profile.liked.indexOf(mid) === -1) {
  619. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  620. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  621. } else {
  622. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  623. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  624. }
  625. if (user.profile.disliked.indexOf(mid) !== -1) {
  626. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  627. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  628. }
  629. return true;
  630. } else {
  631. throw new Meteor.Error(403, "Invalid permissions.");
  632. }
  633. },
  634. dislikeSong: function(mid) {
  635. if (Meteor.userId() && !isBanned()) {
  636. var user = Meteor.user();
  637. if (user.profile.disliked.indexOf(mid) === -1) {
  638. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  639. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  640. } else {
  641. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  642. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  643. }
  644. if (user.profile.liked.indexOf(mid) !== -1) {
  645. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  646. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  647. }
  648. return true;
  649. } else {
  650. throw new Meteor.Error(403, "Invalid permissions.");
  651. }
  652. },
  653. voteSkip: function(type){
  654. if(Meteor.userId() && !isBanned()){
  655. var user = Meteor.user();
  656. getStation(type, function(station){
  657. if(station.voted.indexOf(user.profile.username) === -1){
  658. station.voted.push(user.profile.username);
  659. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  660. if(station.voted.length === 3){
  661. station.skipSong();
  662. }
  663. } else{
  664. throw new Meteor.Error(401, "Already voted.");
  665. }
  666. })
  667. }
  668. },
  669. submitReport: function(room, reportData) {
  670. if (Meteor.userId() && !isBanned()) {
  671. room = room.toLowerCase();
  672. if (Rooms.find({type: room}).count() === 1) {
  673. if (Reports.find({room: room}).count() === 0) {
  674. Reports.insert({room: room, report: []});
  675. }
  676. if (reportData !== undefined) {
  677. Reports.update({room: room}, {
  678. $push: {
  679. report: {
  680. song: reportData.song,
  681. type: reportData.type,
  682. reason: reportData.reason,
  683. other: reportData.other
  684. }
  685. }
  686. });
  687. return true;
  688. } else {
  689. throw new Meteor.Error(403, "Invalid data.");
  690. }
  691. } else {
  692. throw new Meteor.Error(403, "Invalid genre.");
  693. }
  694. } else {
  695. throw new Meteor.Error(403, "Invalid permissions.");
  696. }
  697. },
  698. shufflePlaylist: function(type) {
  699. if (isAdmin() && !isBanned()) {
  700. getStation(type, function(station) {
  701. if (station === undefined) {
  702. throw new Meteor.Error(404, "Station not found.");
  703. } else {
  704. station.cancelTimer();
  705. station.shufflePlaylist();
  706. }
  707. });
  708. }
  709. },
  710. skipSong: function(type) {
  711. if (isAdmin() && !isBanned()) {
  712. getStation(type, function(station) {
  713. if (station === undefined) {
  714. throw new Meteor.Error(404, "Station not found.");
  715. } else {
  716. station.skipSong();
  717. }
  718. });
  719. }
  720. },
  721. pauseRoom: function(type) {
  722. if (isAdmin() && !isBanned()) {
  723. getStation(type, function(station) {
  724. if (station === undefined) {
  725. throw new Meteor.Error(403, "Room doesn't exist.");
  726. } else {
  727. station.pauseRoom();
  728. }
  729. });
  730. } else {
  731. throw new Meteor.Error(403, "Invalid permissions.");
  732. }
  733. },
  734. resumeRoom: function(type) {
  735. if (isAdmin() && !isBanned()) {
  736. getStation(type, function(station) {
  737. if (station === undefined) {
  738. throw new Meteor.Error(403, "Room doesn't exist.");
  739. } else {
  740. station.resumeRoom();
  741. }
  742. });
  743. } else {
  744. throw new Meteor.Error(403, "Invalid permissions.");
  745. }
  746. },
  747. createUserMethod: function(formData, captchaData) {
  748. if (!isBanned()) {
  749. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  750. if (!verifyCaptchaResponse.success) {
  751. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  752. } else {
  753. Accounts.createUser({
  754. username: formData.username,
  755. email: formData.email,
  756. password: formData.password
  757. });
  758. }
  759. return true;
  760. }
  761. },
  762. addSongToQueue: function(type, songData) {
  763. if (Meteor.userId() && !isBanned()) {
  764. type = type.toLowerCase();
  765. var userId = Meteor.userId();
  766. if (Rooms.find({type: type}).count() === 1) {
  767. if (Queues.find({type: type}).count() === 0) {
  768. Queues.insert({type: type, songs: []});
  769. }
  770. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  771. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  772. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  773. songData.skipDuration = 0;
  774. songData.likes = 0;
  775. songData.dislikes = 0;
  776. var mid = createUniqueSongId();
  777. if (mid !== undefined) {
  778. songData.mid = mid;
  779. Queues.update({type: type}, {
  780. $push: {
  781. songs: {
  782. id: songData.id,
  783. mid: songData.mid,
  784. title: songData.title,
  785. artist: songData.artist,
  786. duration: songData.duration,
  787. skipDuration: songData.skipDuration,
  788. likes: songData.likes,
  789. dislikes: songData.dislikes,
  790. img: songData.img,
  791. type: songData.type,
  792. requestedBy: userId
  793. }
  794. }
  795. });
  796. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  797. songsRequested++;
  798. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  799. return true;
  800. } else {
  801. throw new Meteor.Error(500, "Am error occured.");
  802. }
  803. } else {
  804. throw new Meteor.Error(403, "Invalid data.");
  805. }
  806. } else {
  807. throw new Meteor.Error(403, "Invalid genre.");
  808. }
  809. } else {
  810. throw new Meteor.Error(403, "Invalid permissions.");
  811. }
  812. },
  813. updateQueueSong: function(genre, oldSong, newSong) {
  814. if (isModerator() && !isBanned()) {
  815. newSong.mid = oldSong.mid;
  816. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  817. return true;
  818. } else {
  819. throw new Meteor.Error(403, "Invalid permissions.");
  820. }
  821. },
  822. updatePlaylistSong: function(genre, oldSong, newSong) {
  823. if (isModerator() && !isBanned()) {
  824. newSong.mid = oldSong.mid;
  825. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  826. return true;
  827. } else {
  828. throw new Meteor.Error(403, "Invalid permissions.");
  829. }
  830. },
  831. removeSongFromQueue: function(type, mid) {
  832. if (isModerator() && !isBanned()) {
  833. type = type.toLowerCase();
  834. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  835. } else {
  836. throw new Meteor.Error(403, "Invalid permissions.");
  837. }
  838. },
  839. removeSongFromPlaylist: function(type, mid) {
  840. if (isModerator() && !isBanned()) {
  841. type = type.toLowerCase();
  842. var songs = Playlists.findOne({type: type}).songs;
  843. var song = undefined;
  844. songs.forEach(function(curr_song) {
  845. if (mid === curr_song.mid) {
  846. song = curr_song;
  847. return;
  848. }
  849. });
  850. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  851. if (song !== undefined) {
  852. song.deletedBy = Meteor.userId();
  853. song.deletedAt = new Date(Date.now());
  854. if (Deleted.find({type: type}).count() === 0) {
  855. Deleted.insert({type: type, songs: [song]});
  856. } else {
  857. Deleted.update({type: type}, {$push: {songs: song}});
  858. }
  859. }
  860. } else {
  861. throw new Meteor.Error(403, "Invalid permissions.");
  862. }
  863. },
  864. addSongToPlaylist: function(type, songData) {
  865. if (isModerator() && !isBanned()) {
  866. type = type.toLowerCase();
  867. if (Rooms.find({type: type}).count() === 1) {
  868. if (Playlists.find({type: type}).count() === 0) {
  869. Playlists.insert({type: type, songs: []});
  870. }
  871. var requiredProperties = ["type", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy"];
  872. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  873. for (var property in requiredProperties) {
  874. if (songData[requiredProperties[property]] === undefined) {
  875. throw new Meteor.Error(403, "Invalid data.");
  876. }
  877. }
  878. Playlists.update({type: type}, {
  879. $push: {
  880. songs: {
  881. id: songData.id,
  882. mid: songData.mid,
  883. title: songData.title,
  884. artist: songData.artist,
  885. duration: songData.duration,
  886. skipDuration: Number(songData.skipDuration),
  887. img: songData.img,
  888. type: songData.type,
  889. likes: Number(songData.likes),
  890. dislikes: Number(songData.dislikes),
  891. requestedBy: songData.requestedBy,
  892. approvedBy: Meteor.userId()
  893. }
  894. }
  895. });
  896. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  897. getStation(type, function(station) {
  898. if (station === undefined) {
  899. stations.push(new Station(type));
  900. }
  901. });
  902. return true;
  903. } else {
  904. throw new Meteor.Error(403, "Invalid data.");
  905. }
  906. } else {
  907. throw new Meteor.Error(403, "Invalid genre.");
  908. }
  909. } else {
  910. throw new Meteor.Error(403, "Invalid permissions.");
  911. }
  912. },
  913. createRoom: function(display, tag, private) {
  914. if (isAdmin() && !isBanned()) {
  915. createRoom(display, tag, private);
  916. } else {
  917. throw new Meteor.Error(403, "Invalid permissions.");
  918. }
  919. },
  920. deleteRoom: function(type){
  921. if (isAdmin() && !isBanned()) {
  922. Rooms.remove({type: type});
  923. Playlists.remove({type: type});
  924. Queues.remove({type: type});
  925. return true;
  926. } else {
  927. throw new Meteor.Error(403, "Invalid permissions.");
  928. }
  929. },
  930. getUserNum: function(){
  931. if (!isBanned()) {
  932. return Object.keys(Meteor.default_server.sessions).length;
  933. }
  934. },
  935. getTotalUsers: function(){
  936. return Meteor.users.find().count();
  937. },
  938. updateRealName: function(realname){
  939. if (Meteor.userId()) {
  940. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  941. Meteor.users.update(Meteor.userId(), {$set: {"profile.realname": realname}, $push: {"profile.realnames": oldName}});
  942. } else {
  943. throw new Meteor.Error(403, "Invalid permissions.");
  944. }
  945. },
  946. updateUserName: function(newUserName){
  947. if (Meteor.userId()) {
  948. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  949. Meteor.users.update(Meteor.userId(), {$set: {"username": newUserName, "profile.username": newUserName, "profile.usernameL": newUserName.toLowerCase()}, $push: {"profile.usernames": oldUsername}});
  950. } else {
  951. throw new Meteor.Error(403, "Invalid permissions.");
  952. }
  953. },
  954. /*updateUserRank: function(newRank){
  955. if (Meteor.userId()) {
  956. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  957. } else {
  958. throw new Meteor.Error(403, "Invalid permissions.");
  959. }
  960. },*/
  961. deleteAccount: function() {
  962. if (Meteor.userId()) {
  963. var user = Meteor.users.findOne(Meteor.userId());
  964. Deleted.insert({type: "account", user: user, deletedAt: Date.now()});
  965. Meteor.users.remove({_id: Meteor.userId()});
  966. } else {
  967. throw new Meteor.Error(403, "Invalid permissions.");
  968. }
  969. }
  970. });
  971. Meteor.setInterval(function() {
  972. checkUsersPR();
  973. }, 10000);