server.js 39 KB

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