[
  {
    "path": ".gitignore",
    "content": "\n# Created by https://www.gitignore.io/api/node,linux,windows,sublimetext\n\n### Linux ###\n*~\n\n# temporary files which can be created if a process still has a handle open of a deleted file\n.fuse_hidden*\n\n# KDE directory preferences\n.directory\n\n# Linux trash folder which might appear on any partition or disk\n.Trash-*\n\n# .nfs files are created when an open file is removed but is still being accessed\n.nfs*\n\n### Node ###\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Typescript v1 declaration files\ntypings/\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n\n\n### SublimeText ###\n# cache files for sublime text\n*.tmlanguage.cache\n*.tmPreferences.cache\n*.stTheme.cache\n\n# workspace files are user-specific\n*.sublime-workspace\n\n# project files should be checked into the repository, unless a significant\n# proportion of contributors will probably not be using SublimeText\n# *.sublime-project\n\n# sftp configuration file\nsftp-config.json\n\n# Package control specific files\nPackage Control.last-run\nPackage Control.ca-list\nPackage Control.ca-bundle\nPackage Control.system-ca-bundle\nPackage Control.cache/\nPackage Control.ca-certs/\nPackage Control.merged-ca-bundle\nPackage Control.user-ca-bundle\noscrypto-ca-bundle.crt\nbh_unicode_properties.cache\n\n# Sublime-github package stores a github token in this file\n# https://packagecontrol.io/packages/sublime-github\nGitHub.sublime-settings\n\n### Windows ###\n# Windows thumbnail cache files\nThumbs.db\nehthumbs.db\nehthumbs_vista.db\n\n# Folder config file\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n\n\n# End of https://www.gitignore.io/api/node,linux,windows,sublimetext\n\nmisc/"
  },
  {
    "path": "README.md",
    "content": "<img src=\"assets/default.png?raw=true\" width=\"128\" height=\"128\" align=\"left\">\n<h1>Soundcloud Rich Presence</h1>\nAdds Discord Rich Presence support to Soundcloud.\n<br><br>\n\n## Introduction\n\nSoundcloud Rich Presence allows you to show off your Soundcloud listening session to your friends using Discord Rich Presence. \n\nIt is a combination of a server, communicating with discord itself, and a user-script, running on your browser to send playback information to the server. Sadly, due to restrictions in the rich presence protocol, it is mandatory to run both the server and the user-script in order for the system to work.\n\nArtwork upload is not available by default due to Discord's asset limit (150). In order to activate it, you need to create a new app on the developer interface, and set the new ClientID and your APIKey of the developer interface. More details at **[Artwork Upload](#artwork-upload)**.\n\n## Preview\n\n### With artwork upload\n\n| Profile | Popup |\n| ------ | ----- |\n| ![](doc/preview-artwork-profile.png?raw=true) | ![](doc/preview-artwork-popup.png?raw=true) |\n\n### Without artwork upload\n\n| Profile | Popup |\n| ------ | ----- |\n| ![](doc/preview-no-artwork-profile.png?raw=true) | ![](doc/preview-no-artwork-popup.png?raw=true) |\n\n## Installation\n\nYou will need to install [nodejs (v10) and npm (v6)](https://nodejs.org/en/download/current/) first. Make sure the `node` & `npm` commands are installed on your **PATH**.\n\n**Server:**\n1. Clone the repository somewhere on your hard drive or [unzip this archive](https://github.com/demaisj/soundcloud-rp/archive/master.zip) if you don't have git installed\n2. Open a terminal in the **soundcloud-rp** directory\n3. Install the dependencies with `npm install`\n4. Retrieve your Soundcloud ClientID :\n   - Open [Soundcloud](https://soundcloud.com/) then hit Ctrl+Shift+I to open the devtools\n   - Go to the **Network** tab\n   - Filter by `api-v2.soundcloud.com`\n   - Click on the first result. If there is no results, try changing page on Soundcloud to trigger some requests\n   - Scroll down to the **Query String Parameters** section\n   - Look for the **client_id** field and copy the value\n   - Paste it in the corresponding field of the `config/default.json` file\n5. Start the server with `npm run start`\n6. Additionnaly create a systemd service (linux) or startup shortcut (windows) to start the server on bootup\n\n**Browser:**\n1. Install a userscript extension for your browser like [Tampermonkey](https://tampermonkey.net/)\n2. Download & install [`soundcloud-rp.user.js`](soundcloud-rp.user.js?raw=true)\n3. Open soundcloud & enjoy\n\n## Artwork upload\n\nHere is a step by step guide to activate artwork upload:\n1. In the `config/default.json` file, change `uploadArtwork` from `false` to `true`\n2. Go to the [developer interface](https://discordapp.com/developers/applications/me) of Discord\n3. Create a new app, give it a cool name and save it\n4. Paste the Client ID (found in App Details on the top of the page) into the `config/default.json` file\n5. ~~Scroll down and click \"*Enable Rich Presence*\"~~\n6. Hit save changes just in case\n7. Retrieve your APIKey\n   - Hit ctrl+shift+i to open the devtools\n   - Go to the **Network** tab\n   - Filter by `/api/`\n   - Click on the first result. If there is no results, try changing page to trigger some requests\n   - Scroll down to the **Request Headers** section\n   - Look for the **authorization** field and copy the value\n   - Paste it in the corresponding field of the `config/default.json` file (do not forget to wrap it in double quotes as in `\"value\"`)\n8. Restart your server and it should be ok!\n"
  },
  {
    "path": "bin/soundcloud-rp",
    "content": "#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar server = require('../src/');\nvar debug = require('debug')('soundcloud-rp:server');\n\n/**\n * Get port from environment and store in Express.\n */\n\nvar port = normalizePort(process.env.PORT || '7769');\n\n/**\n * Listen on provided port, locally\n */\n\nserver.listen(port, \"127.0.0.1\");\nserver.on('error', onError);\nserver.on('listening', onListening);\n\n/**\n * Normalize a port into a number, string, or false.\n */\n\nfunction normalizePort(val) {\n  var port = parseInt(val, 10);\n\n  if (isNaN(port)) {\n    // named pipe\n    return val;\n  }\n\n  if (port >= 0) {\n    // port number\n    return port;\n  }\n\n  return false;\n}\n\n/**\n * Event listener for HTTP server \"error\" event.\n */\n\nfunction onError(error) {\n  if (error.syscall !== 'listen') {\n    throw error;\n  }\n\n  var bind = typeof port === 'string'\n    ? 'Pipe ' + port\n    : 'Port ' + port;\n\n  // handle specific listen errors with friendly messages\n  switch (error.code) {\n    case 'EACCES':\n      console.error(bind + ' requires elevated privileges');\n      process.exit(1);\n      break;\n    case 'EADDRINUSE':\n      console.error(bind + ' is already in use');\n      process.exit(1);\n      break;\n    default:\n      throw error;\n  }\n}\n\n/**\n * Event listener for HTTP server \"listening\" event.\n */\n\nfunction onListening() {\n  var addr = server.address();\n  var bind = typeof addr === 'string'\n    ? 'pipe ' + addr\n    : 'port ' + addr.port;\n  debug('Listening on ' + bind);\n}\n"
  },
  {
    "path": "config/default.json",
    "content": "{\n  \"discord\": {\n    \"ClientID\": \"443074120758853643\",\n    \"APIKey\": null\n  },\n  \"soundcloud\": {\n    \"ClientID\": \"{insert soundcloud client_id}\"\n  },\n  \"uploadArtwork\": false\n}"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"soundcloud-rp\",\n  \"version\": \"2.0.3\",\n  \"description\": \"Adds Discord Rich Presence support to Soundcloud.\",\n  \"main\": \"src/index.js\",\n  \"dependencies\": {\n    \"cors\": \"^2.8.4\",\n    \"datauri\": \"^1.1.0\",\n    \"discord-rpc\": \"^3.0.0\",\n    \"express\": \"^4.16.3\",\n    \"hbs\": \"^4.0.1\",\n    \"request\": \"^2.87.0\",\n    \"request-promise-native\": \"^1.0.5\",\n    \"socket.io\": \"^2.1.1\"\n  },\n  \"devDependencies\": {\n    \"nodemon\": \"^1.18.3\"\n  },\n  \"scripts\": {\n    \"start\": \"node bin/soundcloud-rp\",\n    \"watch\": \"nodemon --watch src/ --watch config/ --exec npm start\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"demaisj\",\n  \"license\": \"ISC\"\n}\n"
  },
  {
    "path": "soundcloud-rp.sublime-project",
    "content": "{\n\t\"folders\":\n\t[\n\t\t{\n\t\t\t\"path\": \".\"\n\t\t}\n\t]\n}\n"
  },
  {
    "path": "soundcloud-rp.user.js",
    "content": "// ==UserScript==\n// @name         Soundcloud Rich Presence\n// @namespace    https://github.com/demaisj/soundcloud-rp\n// @version      2.0.0\n// @description  Adds Discord Rich Presence support to Soundcloud. A server is needed to run in background in order for the system to work.\n// @author       demaisj\n// @match        https://soundcloud.com/*\n// @grant        none\n// ==/UserScript==\n\n(function(){\n  function load_script() {\n    var head = document.getElementsByTagName('head')[0];\n    var script = document.createElement('script');\n    script.id = 'soundcloud-rp-client';\n    var match = document.getElementById(script.id);\n    if (match)\n      match.remove();\n    script.type = 'text/javascript';\n    script.src = 'http://127.0.0.1:7769/client.js';\n    script.onerror = function(){\n      setTimeout(load_script, 10 * 1000);\n    };\n    head.appendChild(script);\n  }\n  load_script();\n})();"
  },
  {
    "path": "src/helpers/artwork.js",
    "content": "module.exports = {\n  MAX_ARTWORK: 150,\n  ARTWORK_TRACK: 1,\n  ARTWORK_ARTIST: 2\n};"
  },
  {
    "path": "src/helpers/discord.js",
    "content": "const request = require('request-promise-native');\nconst trace = require('debug')('soundcloud-rp:trace');\n\nmodule.exports = (config) => {\n\n  function getAssetList() {\n    trace(\"discord.getAssetList\");\n\n    return request.get(`https://discordapp.com/api/oauth2/applications/${config.discord.ClientID}/assets`, {\n      headers: {\n        authorization: config.discord.APIKey\n      },\n      json: true\n    });\n  }\n\n  function uploadAsset(type, key, data) {\n    trace('discord.uploadAsset', type, key);\n\n    return request.post(`https://discordapp.com/api/oauth2/applications/${config.discord.ClientID}/assets`, {\n      headers: {\n        authorization: config.discord.APIKey\n      },\n      json: true,\n      body: {\n        name: key,\n        type: type,\n        image: data\n      }\n    })\n  }\n\n  function deleteAsset(id) {\n    trace('discord.deleteAsset', id);\n\n    return request.delete(`https://discordapp.com/api/oauth2/applications/${config.discord.ClientID}/assets/${id}`, {\n      headers: {\n        authorization: config.discord.APIKey\n      }\n    })\n  }\n\n  return {\n    getAssetList,\n    uploadAsset,\n    deleteAsset\n  };\n}"
  },
  {
    "path": "src/helpers/image.js",
    "content": "const request = require('request-promise-native');\nconst trace = require('debug')('soundcloud-rp:trace');\nconst DataURI = require('datauri');\nconst url_parser = require('url').parse;\nconst path = require('path');\n\nfunction imageDataFromFile(pathname) {\n  trace('image.imageDataFromFile', pathname);\n\n  const datauri = new DataURI();\n\n  return new Promise((resolve, reject) => {\n    datauri\n      .on('encoded', resolve)\n      .on('error', reject)\n      .encode(pathname)\n  });\n}\n\nfunction imageDataFromUrl(url) {\n  trace('image.imageDataFromUrl', url);\n\n  const datauri = new DataURI();\n\n  return new Promise((resolve, reject) => {\n\n    request.get(url, {\n      encoding: null\n    })\n    .then((buffer) => {\n      let parsed = url_parser(url),\n        filename = path.basename(parsed.pathname);\n\n      datauri.format(filename, buffer);\n      resolve(datauri.content);\n    })\n    .catch(reject);\n  })\n}\n\nmodule.exports = {\n  imageDataFromUrl,\n  imageDataFromFile\n};"
  },
  {
    "path": "src/helpers/soundcloud.js",
    "content": "const request = require('request-promise-native');\nconst trace = require('debug')('soundcloud-rp:trace');\n\nmodule.exports = (config) => {\n\n  function getTrackData(url) {\n    trace('soundcloud.getTrackData', url);\n\n    return request.get('https://api-v2.soundcloud.com/resolve', {\n      qs: {\n        client_id: config.soundcloud.ClientID,\n        url\n      },\n      json: true\n    });\n  }\n\n  function sanitizeArtworkUrl(url) {\n    trace('soundcloud.sanitizeArtworkUrl', url);\n\n    return url.replace('large', 't500x500');\n  }\n\n  return {\n    getTrackData,\n    sanitizeArtworkUrl\n  };\n}"
  },
  {
    "path": "src/index.js",
    "content": "const express = require('express');\nconst http = require('http');\nconst socketio = require('socket.io')\nconst path = require('path');\nconst bodyParser = require('body-parser');\nconst debug = require('debug')('soundcloud-rp:server');\nconst cors = require('cors');\n\nconst config = require('../config/default.json');\n\nif (config.soundcloud.ClientID == '{insert soundcloud client_id}')\n  throw new Error('Please edit the default soundcloud client_id before starting the server');\n\nconst rpc = require('./rpc')(config);\n\n\nconst app = express();\nconst server = http.createServer(app);\nconst io = socketio(server);\n\napp.use(cors());\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: false }));\n\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'hbs');\n\nconst client_routes = require('./routes/client');\n\napp.use(client_routes);\n\nconst client_protocol = require('./protocols/client')(config, io, rpc);\n\n// error handler\napp.use(function(err, req, res, next) {\n  // set locals, only providing error in development\n  let data = {\n    code: err.status || err.statusCode || 500,\n    error: err.name,\n    message: err.message\n  };\n\n  if (req.app.get('env') !== 'production') {\n    data.debug = err;\n    data.stack = err.stack;\n  }\n\n  // render the error page\n  debug(`${err.stack}`);\n  res.status(data.code);\n  res.json(data);\n});\n\n\nmodule.exports = server;"
  },
  {
    "path": "src/procedures/activity.js",
    "content": "const trace = require('debug')('soundcloud-rp:trace');\nconst debug = require('debug')('soundcloud-rp:activity');\nconst { MAX_ARTWORK, ARTWORK_TRACK, ARTWORK_ARTIST } = require('../helpers/artwork');\nconst image = require('../helpers/image');\n\nconst WAIT_BEFORE_CLEAR = 15;\n\nmodule.exports = (config, rpc) => {\n\n  const soundcloud = require('../helpers/soundcloud')(config);\n  const discord = require('../helpers/discord')(config);\n\n  function processArtwork(type, id, url) {\n    trace('activity.processArtwork', type, id, url);\n\n    return new Promise((resolve, reject) => {\n      const key = `${type == ARTWORK_TRACK ? 'track' : 'artist'}_${id}`;\n\n      debug(\"Generated key for artwork:\", key);\n\n      if (!config.uploadArtwork) {\n        debug(\"Uploading artworks is not supported, falling back to default\");\n\n        if (config.discord.ClientID == '443074120758853643') {\n          if (type == ARTWORK_TRACK)\n            return resolve(`default_large_${id % 11}`);\n          else if (type == ARTWORK_ARTIST)\n            return resolve('default_small');\n        }\n        return resolve('default');\n      }\n\n      debug(\"Checking if artwork is already uploaded...\");\n      discord.getAssetList()\n      .then((assets) => {\n\n        for (let i = 0; i < assets.length; i++) {\n          if (assets[i].name == key) {\n            debug(\"Artwork already uploaded, no action needed.\");\n            return resolve(key);\n          }\n        }\n\n        debug(\"Artwork not already uploaded.\");\n\n        function continueUpload() {\n          let image_processor;\n\n          if (url == null || url.startsWith('http://a1.sndcdn.com/images/default_avatar_large.png')) {\n            debug(\"Artwork is placeholder, getting datauri from stock ones...\");\n            image_processor = image.imageDataFromFile(`assets/placeholder-${id % 11}.png`);\n          }\n          else {\n            debug(\"Getting artwork datauri from soundcloud cdn...\");\n            image_processor = image.imageDataFromUrl(soundcloud.sanitizeArtworkUrl(url));\n          }\n\n          image_processor\n          .then((data) => {\n            debug(\"Uploading artwork to discord...\");\n            discord.uploadAsset(type, key, data)\n            .then(() => {\n              debug(\"Artwork processed successfully!\");\n              resolve(key);\n            })\n            .catch(reject)\n          })\n          .catch(reject)\n        }\n\n        if (assets.length >= MAX_ARTWORK) {\n          debug(\"Asset limit reached, deleting old unused assets...\");\n          discord.deleteAsset(assets[0].id)\n          .then(continueUpload)\n          .catch(reject);\n        } else {\n          continueUpload();\n        }\n\n      })\n      .catch(reject)\n    });\n  }\n\n  let LOCKED = false;\n\n  return (request_data) => {\n    trace('activity', request_data);\n\n    return new Promise((resolve, reject) => {\n\n    if (!('url' in request_data) || !('pos' in request_data)) {\n      debug(\"Bad Request, missing arguments\");\n      reject(new Error('Missing url/pos argument.'));\n      return;\n    }\n\n    if (!rpc.status) {\n      debug(\"Service Unavailable, rpc not connected\");\n      reject(new Error('RPC not connected to Discord.'));\n      return;\n    }\n\n    if (LOCKED) {\n      debug(\"LOCKED state, we are already updating activity\");\n      reject(new Error('An activity request is already being processed.'));\n      return;\n    }\n\n    function success() {\n      LOCKED = false;\n      resolve();\n    }\n\n    function error(err) {\n      LOCKED = false;\n      reject(err);\n    }\n\n    try{\n\n    LOCKED = true;\n\n    let last_activity = rpc.getActivity();\n    if (last_activity && last_activity.trackURL == request_data.url) {\n      debug('track info already sent, updating timestamps only...');\n      last_activity.startTimestamp = Math.round(new Date().getTime() / 1000) - request_data.pos;\n      last_activity.endTimestamp = last_activity.startTimestamp + Math.round(last_activity.trackDuration / 1000);\n\n      rpc.setActivity(last_activity)\n      .then(() => {\n        rpc.setActivityTimeout(last_activity.endTimestamp + WAIT_BEFORE_CLEAR);\n\n        success();\n      })\n      .catch(error);\n      return;\n    }\n\n    debug(\"getting track info...\");\n    soundcloud.getTrackData(request_data.url)\n    .then((track_data) => {\n      debug(\"Track info downloaded successfully.\", track_data.id);\n\n      let startTimestamp = Math.round(new Date().getTime() / 1000) - request_data.pos,\n        endTimestamp = startTimestamp + Math.round(track_data.duration / 1000);\n\n      debug(\"Processing artwork...\");\n      let keys = [];\n\n      processArtwork(ARTWORK_TRACK, track_data.id, track_data.artwork_url)\n      .then((key) => keys.push(key))\n      .then(() => processArtwork(ARTWORK_ARTIST, track_data.user.id, track_data.user.avatar_url))\n      .then((key) => keys.push(key))\n      .then(() => {\n        debug('Artwork processed successfully', keys);\n\n        let activity_data = {\n          details: track_data.title,\n          state: `by ${track_data.user.username}`,\n          startTimestamp,\n          endTimestamp,\n          largeImageKey: keys[0],\n          largeImageText: track_data.title,\n          smallImageKey: keys[1],\n          smallImageText: track_data.user.username,\n          trackURL: request_data.url,\n          trackDuration: track_data.duration\n        };\n\n        debug(\"Everything ok, updating activity.\", activity_data);\n        rpc.setActivity(activity_data)\n        .then(() => {\n          rpc.setActivityTimeout(endTimestamp + WAIT_BEFORE_CLEAR);\n\n          success();\n        })\n        .catch(error);\n      })\n      .catch(error);\n    })\n    .catch(error);\n\n    }\n    catch(err) {\n      error(err);\n    }\n  });\n  };\n};"
  },
  {
    "path": "src/protocols/client.js",
    "content": "const trace = require('debug')('soundcloud-rp:trace');\nconst debug = require('debug')('soundcloud-rp:client-protocol');\n\nmodule.exports = function(config, io, rpc) {\n\n  const activity = require('../procedures/activity')(config, rpc);\n\n  io.on('connection', function(socket){\n    trace('client.connection', socket.id);\n\n    socket.on('activity', function(data){\n      trace('client.event', socket.id, 'activity', data);\n\n      activity(data)\n      .then(() => {\n        socket.emit('activity', true, {});\n      })\n      .catch((err) => {\n        socket.emit('activity', false, {\n          error: err.name,\n          message: err.message\n        });\n      })\n    });\n\n    socket.on('disconnect', function(){\n      trace('client.disconnect', socket.id);\n    });\n  });\n};"
  },
  {
    "path": "src/routes/client.js",
    "content": "const router = require('express').Router();\nconst trace = require('debug')('soundcloud-rp:trace');\n\nrouter.get('/client.js', (req, res) => {\n  trace('GET client');\n\n  res.set('content-type', 'application/javascript');\n  res.render('client', {\n    host: req.get('host')\n  });\n});\n\nmodule.exports = router;"
  },
  {
    "path": "src/rpc.js",
    "content": "const { Client } = require('discord-rpc');\nconst trace = require('debug')('soundcloud-rp:trace');\nconst debug = require('debug')('soundcloud-rp:rpc');\n\nconst WAIT_BETWEEN_TRIES = 10;\nconst TIMEOUT = 10;\n\nmodule.exports = (config) => {\n\n  class RPCWrapper {\n    constructor(config, rpc) {\n      trace(\"rpc.constructor\");\n\n      this._config = config;\n      this._rpc = rpc;\n\n      this.activity_timeout = 0;\n      this.current_activity = false;\n\n      this.initRPC();\n    }\n\n    initRPC() {\n      trace(\"rpc.init\");\n\n      this.status = false;\n\n      this._rpc.on('ready', () => {\n        trace(\"rpc.event.ready\");\n      });\n\n      this.connect();\n    }\n\n    connect() {\n      trace(\"rpc.connect\");\n      debug(\"Connecting to discord...\");\n\n      this._rpc.login({clientId: this._config.discord.ClientID })\n      .then(() => {\n        trace(\"rpc.connect.success\");\n        debug(\"Connected to discord!\");\n\n        this.status = true;\n      })\n      .catch((err) => {\n        trace(\"rpc.connect.fail\");\n        this.status = false;\n\n        debug(\"Failed to connect to discord\", err);\n        debug(`Trying again in ${WAIT_BETWEEN_TRIES} seconds...`);\n        setTimeout(() => {\n          this.connect()\n        }, WAIT_BETWEEN_TRIES * 1000);\n      });\n    }\n\n    setActivity(data) {\n      trace(\"rpc.setActivity\", data);\n\n      function pad(str) {\n        while (str.length < 2)\n          str += \" \";\n        return str;\n      }\n\n      data.details = pad(data.details);\n      data.state = pad(data.state);\n      data.largeImageText = pad(data.largeImageText);\n      data.smallImageText = pad(data.smallImageText);\n\n      this.current_activity = data;\n\n      // We need to timeout ourselves, this method doesn't throw any error\n      return new Promise((resolve, reject) => {\n\n        var request_timeout = setTimeout(() => {\n          trace(\"rpc.setActivity.fail\");\n          this.status = false;\n          var err = new Error('RPC timeout.');\n\n          debug(\"Failed to interact with discord\", err);\n          debug(`Reconnecting again in ${WAIT_BETWEEN_TRIES} seconds...`);\n          setTimeout(() => {\n            this.connect()\n          }, WAIT_BETWEEN_TRIES * 1000);\n\n          reject(err);\n        }, TIMEOUT * 1000);\n\n        this._rpc.setActivity(data).then(() => {\n          trace(\"rpc.setActivity.success\");\n\n          clearTimeout(request_timeout);\n          resolve();\n        });\n      });\n    }\n\n    getActivity() {\n      trace(\"rpc.getActivity\");\n\n      return this.current_activity;\n    }\n\n    clearActivity() {\n      trace(\"rpc.clearActivity\");\n\n      this.current_activity = false;\n      this.clearActivityTimeout();\n\n      // We need to timeout ourselves, this method doesn't throw any error\n      return new Promise((resolve, reject) => {\n\n        var request_timeout = setTimeout(() => {\n          trace(\"rpc.clearActivity.fail\");\n          this.status = false;\n          var err = new Error('RPC timeout.');\n\n          debug(\"Failed to interact with discord\", err);\n          debug(`Reconnecting again in ${WAIT_BETWEEN_TRIES} seconds...`);\n          setTimeout(() => {\n            this.connect()\n          }, WAIT_BETWEEN_TRIES * 1000);\n\n          reject(err);\n        }, TIMEOUT * 1000);\n\n        this._rpc.clearActivity().then(() => {\n          trace(\"rpc.clearActivity.success\");\n\n          clearTimeout(request_timeout);\n          resolve();\n        });\n      });\n    }\n\n    setActivityTimeout(timestamp) {\n      trace(\"rpc.setActivityTimeout\", timestamp);\n      let now = Math.round(new Date().getTime() / 1000);\n\n      this.clearActivityTimeout();\n      this.activity_timeout = setTimeout(() => {\n        trace(\"rpc.setActivityTimeout.timeout\");\n\n        this.clearActivity();\n      }, (timestamp - now) * 1000);\n    }\n\n    clearActivityTimeout() {\n      trace(\"rpc.clearActivityTimeout\");\n      clearTimeout(this.activity_timeout);\n    }\n  }\n\n  const rpc = new Client({transport: 'ipc'});\n\n  return new RPCWrapper(config, rpc);\n}"
  },
  {
    "path": "src/views/client.hbs",
    "content": "(function(){\n  function load_script(url) {\n    return new Promise(function (resolve, reject){\n      var head = document.getElementsByTagName('head')[0];\n      var script = document.createElement('script');\n      script.type = 'text/javascript';\n      script.onload = resolve;\n      script.onerror = reject;\n      script.src = url;\n      head.appendChild(script);\n    })\n  }\n\n  load_script('http://{{host}}/socket.io/socket.io.js')\n  .then(function(){\n    var socket = io.connect('http://{{host}}');\n    var interval = 10;\n\n    function poll_activity() {\n      var $title = document.querySelector(\".playbackSoundBadge__titleLink\"),\n        $progress = document.querySelector(\".playbackTimeline__progressWrapper\"),\n        $play = document.querySelector(\".playControls__play\");\n\n      if (!$title || !$progress || !$play)\n        return;\n\n      var url = \"https://soundcloud.com\" + $title.getAttribute(\"href\"),\n        pos = parseInt($progress.getAttribute(\"aria-valuenow\"), 10),\n        playing = $play.classList.contains(\"playing\");\n\n      if (!playing)\n        return;\n\n      socket.emit('activity', { url, pos });\n    }\n\n    poll_activity();\n    setInterval(poll_activity, interval * 1000);\n  })\n  .catch(function(err) {\n    console.error('soundcloud-rp', err);\n  });\n\n})();"
  }
]