server.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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. function isAdmin() {
  446. var userData = Meteor.users.find(Meteor.userId());
  447. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  448. return true;
  449. } else {
  450. return false;
  451. }
  452. }
  453. function isModerator() {
  454. var userData = Meteor.users.find(Meteor.userId());
  455. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  456. return true;
  457. } else {
  458. return isAdmin();
  459. }
  460. }
  461. function isBanned() {
  462. var userData = Meteor.users.findOne(Meteor.userId());
  463. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  464. var ban = userData.punishments.ban;
  465. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  466. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  467. return false;
  468. } else {
  469. return true;
  470. }
  471. } else {
  472. return false;
  473. }
  474. }
  475. function isMuted() {
  476. var userData = Meteor.users.findOne(Meteor.userId());
  477. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  478. var mute = userData.punishments.mute;
  479. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  480. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  481. return false;
  482. } else {
  483. return true;
  484. }
  485. } else {
  486. return false;
  487. }
  488. }
  489. Meteor.methods({
  490. lockRoom: function (type) {
  491. if (isAdmin() && !isBanned()) {
  492. getStation(type, function (station) {
  493. station.lock();
  494. });
  495. } else {
  496. throw new Meteor.Error(403, "Invalid permissions.");
  497. }
  498. },
  499. unlockRoom: function (type) {
  500. if (isAdmin() && !isBanned()) {
  501. getStation(type, function (station) {
  502. station.unlock();
  503. });
  504. } else {
  505. throw new Meteor.Error(403, "Invalid permissions.");
  506. }
  507. },
  508. banUser: function (username, period, reason) {
  509. if (isAdmin() && !isBanned()) {
  510. var user = Meteor.user();
  511. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  512. var bannedUntil = (new Date).getTime() + (period * 1000);
  513. if (bannedUntil > 8640000000000000) {
  514. bannedUntil = 8640000000000000;
  515. }
  516. bannedUntil = new Date(bannedUntil);
  517. var banObject = {
  518. bannedBy: user.profile.usernameL,
  519. bannedAt: new Date(Date.now()),
  520. bannedReason: reason,
  521. bannedUntil: bannedUntil
  522. };
  523. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  524. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  525. } else {
  526. throw new Meteor.Error(403, "Invalid permissions.");
  527. }
  528. },
  529. muteUser: function (username, period) {
  530. if (isAdmin() && !isBanned()) {
  531. var user = Meteor.user();
  532. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  533. if (period === undefined || Number(period) === 0) {
  534. mutedUntil = 8640000000000000;
  535. } else {
  536. var mutedUntil = (new Date).getTime() + (period * 1000);
  537. if (mutedUntil > 8640000000000000) {
  538. mutedUntil = 8640000000000000;
  539. }
  540. }
  541. mutedUntil = new Date(mutedUntil);
  542. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  543. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  544. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  545. } else {
  546. throw new Meteor.Error(403, "Invalid permissions.");
  547. }
  548. },
  549. unbanUser: function (username) {
  550. if (isAdmin() && !isBanned()) {
  551. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  552. } else {
  553. throw new Meteor.Error(403, "Invalid permissions.");
  554. }
  555. },
  556. unsilenceUser: function (username) {
  557. if (isAdmin() && !isBanned()) {
  558. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  559. } else {
  560. throw new Meteor.Error(403, "Invalid permissions.");
  561. }
  562. },
  563. isBanned: function () {
  564. return isBanned();
  565. },
  566. isMuted: function () {
  567. return isMuted();
  568. },
  569. updateSettings: function (showRating) {
  570. if (Meteor.userId() && !isBanned()) {
  571. var user = Meteor.user();
  572. if (showRating !== true && showRating !== false) {
  573. showRating = false;
  574. }
  575. if (user.profile.settings) {
  576. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  577. } else {
  578. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  579. }
  580. } else {
  581. throw new Meteor.Error(403, "Invalid permissions.");
  582. }
  583. },
  584. resetRating: function () {
  585. if (isAdmin() && !isBanned()) {
  586. stations.forEach(function (station) {
  587. var type = station.type;
  588. var temp_songs = Playlists.findOne({type: type}).songs;
  589. Playlists.update({type: type}, {$set: {"songs": []}});
  590. temp_songs.forEach(function (song) {
  591. song.likes = 0;
  592. song.dislikes = 0;
  593. Playlists.update({type: type}, {$push: {"songs": song}});
  594. });
  595. });
  596. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  597. } else {
  598. throw Meteor.Error(403, "Invalid permissions.");
  599. }
  600. },
  601. removeAlerts: function () {
  602. if (isAdmin() && !isBanned()) {
  603. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  604. } else {
  605. throw Meteor.Error(403, "Invalid permissions.");
  606. }
  607. },
  608. addAlert: function (description, priority) {
  609. if (isAdmin()) {
  610. if (description.length > 0 && description.length < 400) {
  611. var username = Meteor.user().profile.username;
  612. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  613. priority = "warning";
  614. }
  615. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  616. return true;
  617. } else {
  618. throw Meteor.Error(403, "Invalid description length.");
  619. }
  620. } else {
  621. throw Meteor.Error(403, "Invalid permissions.");
  622. }
  623. },
  624. sendMessage: function (type, message) {
  625. if (Meteor.userId() && !isBanned() && !isMuted()) {
  626. var user = Meteor.user();
  627. var time = new Date();
  628. var rawrank = user.profile.rank;
  629. var username = user.profile.username;
  630. var profanity = false;
  631. var mentionUsername;
  632. var isCurUserMentioned;
  633. if (message.indexOf("@") !== -1) {
  634. var messageArr = message.split(" ");
  635. for (var i in messageArr) {
  636. if (messageArr[i].indexOf("@") !== -1) {
  637. var mention = messageArr[i];
  638. }
  639. }
  640. Meteor.users.find().forEach(function (user) {
  641. if (mention.indexOf(user.profile.username) !== -1) {
  642. mentionUsername = true;
  643. isCurUserMentioned = Meteor.user().profile.username === user.profile.username;
  644. }
  645. ;
  646. })
  647. }
  648. if (!message.replace(/\s/g, "").length > 0) {
  649. throw new Meteor.Error(406, "Message length cannot be 0.");
  650. }
  651. if (message.length > 300) {
  652. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  653. }
  654. else if (user.profile.rank === "admin") {
  655. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  656. if (res.content.indexOf("true") > -1) {
  657. return true;
  658. } else {
  659. Chat.insert({
  660. type: type,
  661. rawrank: rawrank,
  662. rank: "[A]",
  663. message: message,
  664. curUserMention: isCurUserMentioned,
  665. isMentioned: mentionUsername,
  666. time: time,
  667. username: username
  668. });
  669. }
  670. });
  671. return true;
  672. }
  673. else if (user.profile.rank === "moderator") {
  674. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  675. if (res.content.indexOf("true") > -1) {
  676. return true;
  677. } else {
  678. Chat.insert({
  679. type: type,
  680. rawrank: rawrank,
  681. rank: "[M]",
  682. message: message,
  683. time: time,
  684. username: username
  685. });
  686. }
  687. });
  688. return true;
  689. }
  690. else {
  691. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  692. if (res.content.indexOf("true") > -1) {
  693. return true;
  694. } else {
  695. Chat.insert({
  696. type: type,
  697. rawrank: rawrank,
  698. rank: "",
  699. message: message,
  700. time: time,
  701. username: username
  702. });
  703. }
  704. });
  705. return true;
  706. }
  707. } else {
  708. throw new Meteor.Error(403, "Invalid permissions.");
  709. }
  710. },
  711. likeSong: function (mid) {
  712. if (Meteor.userId() && !isBanned()) {
  713. var user = Meteor.user();
  714. if (user.profile.liked.indexOf(mid) === -1) {
  715. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  716. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  717. } else {
  718. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  719. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  720. }
  721. if (user.profile.disliked.indexOf(mid) !== -1) {
  722. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  723. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  724. }
  725. return true;
  726. } else {
  727. throw new Meteor.Error(403, "Invalid permissions.");
  728. }
  729. },
  730. dislikeSong: function (mid) {
  731. if (Meteor.userId() && !isBanned()) {
  732. var user = Meteor.user();
  733. if (user.profile.disliked.indexOf(mid) === -1) {
  734. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  735. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  736. } else {
  737. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  738. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  739. }
  740. if (user.profile.liked.indexOf(mid) !== -1) {
  741. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  742. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  743. }
  744. return true;
  745. } else {
  746. throw new Meteor.Error(403, "Invalid permissions.");
  747. }
  748. },
  749. voteSkip: function (type) {
  750. if (Meteor.userId() && !isBanned()) {
  751. var user = Meteor.user();
  752. getStation(type, function (station) {
  753. if (station.voted.indexOf(user.profile.username) === -1) {
  754. station.voted.push(user.profile.username);
  755. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  756. if (station.voted.length === 3) {
  757. station.skipSong();
  758. }
  759. } else {
  760. throw new Meteor.Error(401, "Already voted.");
  761. }
  762. })
  763. }
  764. },
  765. submitReport: function (room, reportData) {
  766. if (Meteor.userId() && !isBanned()) {
  767. room = room.toLowerCase();
  768. if (Rooms.find({type: room}).count() === 1) {
  769. if (Reports.find({room: room}).count() === 0) {
  770. Reports.insert({room: room, report: []});
  771. }
  772. if (reportData !== undefined) {
  773. Reports.update({room: room}, {
  774. $push: {
  775. report: {
  776. song: reportData.song,
  777. type: reportData.type,
  778. reason: reportData.reason,
  779. other: reportData.other
  780. }
  781. }
  782. });
  783. return true;
  784. } else {
  785. throw new Meteor.Error(403, "Invalid data.");
  786. }
  787. } else {
  788. throw new Meteor.Error(403, "Invalid genre.");
  789. }
  790. } else {
  791. throw new Meteor.Error(403, "Invalid permissions.");
  792. }
  793. },
  794. shufflePlaylist: function (type) {
  795. if (isAdmin() && !isBanned()) {
  796. getStation(type, function (station) {
  797. if (station === undefined) {
  798. throw new Meteor.Error(404, "Station not found.");
  799. } else {
  800. station.cancelTimer();
  801. station.shufflePlaylist();
  802. }
  803. });
  804. }
  805. },
  806. skipSong: function (type) {
  807. if (isAdmin() && !isBanned()) {
  808. getStation(type, function (station) {
  809. if (station === undefined) {
  810. throw new Meteor.Error(404, "Station not found.");
  811. } else {
  812. station.skipSong();
  813. }
  814. });
  815. }
  816. },
  817. pauseRoom: function (type) {
  818. if (isAdmin() && !isBanned()) {
  819. getStation(type, function (station) {
  820. if (station === undefined) {
  821. throw new Meteor.Error(403, "Room doesn't exist.");
  822. } else {
  823. station.pauseRoom();
  824. }
  825. });
  826. } else {
  827. throw new Meteor.Error(403, "Invalid permissions.");
  828. }
  829. },
  830. resumeRoom: function (type) {
  831. if (isAdmin() && !isBanned()) {
  832. getStation(type, function (station) {
  833. if (station === undefined) {
  834. throw new Meteor.Error(403, "Room doesn't exist.");
  835. } else {
  836. station.resumeRoom();
  837. }
  838. });
  839. } else {
  840. throw new Meteor.Error(403, "Invalid permissions.");
  841. }
  842. },
  843. createUserMethod: function (formData, captchaData) {
  844. if (!isBanned()) {
  845. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  846. if (!verifyCaptchaResponse.success) {
  847. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  848. } else {
  849. Accounts.createUser({
  850. username: formData.username,
  851. email: formData.email,
  852. password: formData.password
  853. });
  854. }
  855. return true;
  856. }
  857. },
  858. addSongToQueue: function (type, songData) {
  859. if (Meteor.userId() && !isBanned()) {
  860. type = type.toLowerCase();
  861. var userId = Meteor.userId();
  862. if (Rooms.find({type: type}).count() === 1) {
  863. if (Queues.find({type: type}).count() === 0) {
  864. Queues.insert({type: type, songs: []});
  865. }
  866. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  867. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  868. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  869. songData.skipDuration = 0;
  870. songData.likes = 0;
  871. songData.dislikes = 0;
  872. var mid = createUniqueSongId();
  873. if (mid !== undefined) {
  874. songData.mid = mid;
  875. Queues.update({type: type}, {
  876. $push: {
  877. songs: {
  878. id: songData.id,
  879. mid: songData.mid,
  880. title: songData.title,
  881. artist: songData.artist,
  882. duration: songData.duration,
  883. skipDuration: songData.skipDuration,
  884. likes: songData.likes,
  885. dislikes: songData.dislikes,
  886. img: songData.img,
  887. type: songData.type,
  888. requestedBy: userId
  889. }
  890. }
  891. });
  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. } else {
  897. throw new Meteor.Error(500, "Am error occured.");
  898. }
  899. } else {
  900. throw new Meteor.Error(403, "Invalid data.");
  901. }
  902. } else {
  903. throw new Meteor.Error(403, "Invalid genre.");
  904. }
  905. } else {
  906. throw new Meteor.Error(403, "Invalid permissions.");
  907. }
  908. },
  909. updateQueueSong: function (genre, oldSong, newSong) {
  910. if (isModerator() && !isBanned()) {
  911. newSong.mid = oldSong.mid;
  912. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  913. return true;
  914. } else {
  915. throw new Meteor.Error(403, "Invalid permissions.");
  916. }
  917. },
  918. updatePlaylistSong: function (genre, oldSong, newSong) {
  919. if (isModerator() && !isBanned()) {
  920. newSong.mid = oldSong.mid;
  921. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  922. return true;
  923. } else {
  924. throw new Meteor.Error(403, "Invalid permissions.");
  925. }
  926. },
  927. removeSongFromQueue: function (type, mid) {
  928. if (isModerator() && !isBanned()) {
  929. type = type.toLowerCase();
  930. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  931. } else {
  932. throw new Meteor.Error(403, "Invalid permissions.");
  933. }
  934. },
  935. removeSongFromPlaylist: function (type, mid) {
  936. if (isModerator() && !isBanned()) {
  937. type = type.toLowerCase();
  938. var songs = Playlists.findOne({type: type}).songs;
  939. var song = undefined;
  940. songs.forEach(function (curr_song) {
  941. if (mid === curr_song.mid) {
  942. song = curr_song;
  943. return;
  944. }
  945. });
  946. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  947. if (song !== undefined) {
  948. song.deletedBy = Meteor.userId();
  949. song.deletedAt = new Date(Date.now());
  950. if (Deleted.find({type: type}).count() === 0) {
  951. Deleted.insert({type: type, songs: [song]});
  952. } else {
  953. Deleted.update({type: type}, {$push: {songs: song}});
  954. }
  955. }
  956. } else {
  957. throw new Meteor.Error(403, "Invalid permissions.");
  958. }
  959. },
  960. addSongToPlaylist: function (type, songData) {
  961. if (isModerator() && !isBanned()) {
  962. type = type.toLowerCase();
  963. if (Rooms.find({type: type}).count() === 1) {
  964. if (Playlists.find({type: type}).count() === 0) {
  965. Playlists.insert({type: type, songs: []});
  966. }
  967. var requiredProperties = ["type", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy"];
  968. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  969. for (var property in requiredProperties) {
  970. if (songData[requiredProperties[property]] === undefined) {
  971. throw new Meteor.Error(403, "Invalid data.");
  972. }
  973. }
  974. Playlists.update({type: type}, {
  975. $push: {
  976. songs: {
  977. id: songData.id,
  978. mid: songData.mid,
  979. title: songData.title,
  980. artist: songData.artist,
  981. duration: songData.duration,
  982. skipDuration: Number(songData.skipDuration),
  983. img: songData.img,
  984. type: songData.type,
  985. likes: Number(songData.likes),
  986. dislikes: Number(songData.dislikes),
  987. requestedBy: songData.requestedBy,
  988. approvedBy: Meteor.userId()
  989. }
  990. }
  991. });
  992. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  993. getStation(type, function (station) {
  994. if (station === undefined) {
  995. stations.push(new Station(type));
  996. }
  997. });
  998. return true;
  999. } else {
  1000. throw new Meteor.Error(403, "Invalid data.");
  1001. }
  1002. } else {
  1003. throw new Meteor.Error(403, "Invalid genre.");
  1004. }
  1005. } else {
  1006. throw new Meteor.Error(403, "Invalid permissions.");
  1007. }
  1008. },
  1009. createRoom: function (display, tag, private) {
  1010. if (isAdmin() && !isBanned()) {
  1011. createRoom(display, tag, private);
  1012. } else {
  1013. throw new Meteor.Error(403, "Invalid permissions.");
  1014. }
  1015. },
  1016. deleteRoom: function (type) {
  1017. if (isAdmin() && !isBanned()) {
  1018. Rooms.remove({type: type});
  1019. Playlists.remove({type: type});
  1020. Queues.remove({type: type});
  1021. return true;
  1022. } else {
  1023. throw new Meteor.Error(403, "Invalid permissions.");
  1024. }
  1025. },
  1026. getUserNum: function () {
  1027. if (!isBanned()) {
  1028. return Object.keys(Meteor.default_server.sessions).length;
  1029. }
  1030. },
  1031. getTotalUsers: function () {
  1032. return Meteor.users.find().count();
  1033. },
  1034. updateRealName: function (realname) {
  1035. if (Meteor.userId()) {
  1036. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1037. Meteor.users.update(Meteor.userId(), {
  1038. $set: {"profile.realname": realname},
  1039. $push: {"profile.realnames": oldName}
  1040. });
  1041. } else {
  1042. throw new Meteor.Error(403, "Invalid permissions.");
  1043. }
  1044. },
  1045. updateUserName: function (newUserName) {
  1046. if (Meteor.userId()) {
  1047. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1048. Meteor.users.update(Meteor.userId(), {
  1049. $set: {
  1050. "username": newUserName,
  1051. "profile.username": newUserName,
  1052. "profile.usernameL": newUserName.toLowerCase()
  1053. }, $push: {"profile.usernames": oldUsername}
  1054. });
  1055. } else {
  1056. throw new Meteor.Error(403, "Invalid permissions.");
  1057. }
  1058. },
  1059. /*updateUserRank: function(newRank){
  1060. if (Meteor.userId()) {
  1061. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  1062. } else {
  1063. throw new Meteor.Error(403, "Invalid permissions.");
  1064. }
  1065. },*/
  1066. deleteAccount: function () {
  1067. if (Meteor.userId()) {
  1068. var user = Meteor.users.findOne(Meteor.userId());
  1069. Deleted.insert({type: "account", user: user, deletedAt: Date.now()});
  1070. Meteor.users.remove({_id: Meteor.userId()});
  1071. } else {
  1072. throw new Meteor.Error(403, "Invalid permissions.");
  1073. }
  1074. },
  1075. sendFeedback: function(user, message){
  1076. }
  1077. });
  1078. Meteor.setInterval(function () {
  1079. checkUsersPR();
  1080. }, 10000);
  1081. Meteor.users.after.insert(function (err, user) {
  1082. Accounts.sendVerificationEmail(user._id);
  1083. });