2
0

server.js 45 KB

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