server.js 45 KB

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