server.js 42 KB

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