server.js 44 KB

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