server.js 41 KB

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