jarvis394 / Glitch Restart Button

// ==UserScript==
// @name         Glitch Restart Button
// @namespace    https://github.com/jarvis394/glitch-restart-button
// @version      3.1.0
// @description  Adds restart button to your Glitch project!
// @author       jarvis394
// @match        https://glitch.com/edit/*
// @run-at       document-start
// @grant        none
// @license      MIT
// @copyright    2019, jarvis394 (https://openuserjs.org/users/jarvis394)
// @iconURL      https://i.ibb.co/s9pfQH3/Flat-restart-icon-svg-1.png
// @updateURL    https://openuserjs.org/meta/jarvis394/Glitch_Restart_Button.meta.js
// @downloadURL  https://openuserjs.org/install/jarvis394/Glitch_Restart_Button.user.js
// ==/UserScript==

(async () => {
  'use strict'

  let button, data = {}

  /**
   * Adds styles to a page
   * @param {string} css Styles
   */
  const addCSS = (css) => {
    let head = document.getElementsByTagName('head')[0]

    if (!head) return

    let style = document.createElement('style')
    style.type = 'text/css'
    style.innerHTML = css
    head.appendChild(style)
  }

  const isInvalidData = () => {
    if (!data.token) return alert('Can\'t find your Glitch token, sorry!')
    if (!data.projectId) return alert('Can\'t find your project ID, sorry!')

    return false
  }

  /**
   * Reloads current project
   */
  const reloadProject = () => {
    if (isInvalidData()) return

    fetch(`https://api.glitch.com/projects/${data.projectId}/stop?authorization=${data.token}`, {
      method: 'POST'
    }).then(res => {
      if (res.status === 401) return alert('Sorry, you are not allowed to restart this project!')
    })
  }

  /**
   * Adds button
   */
  const addButton = () => {
    button = document.createElement('button')
    button.innerHTML = 'Restart'
    button.className += 'button-small button-restart'
    button.disabled = !data.isOwner
    button.onclick = () => reloadProject()

    document.getElementsByClassName('editor-container')[0].appendChild(button)

    console.log('%cAdded %c\'Restart\'%c button to the Editor!', 'color: #555', 'color: #2196F3', 'color: #555')
  }

  const updateButton = () => {
    button.disabled = !data.isOwner

    document.getElementsByClassName('editor-container')[0].appendChild(button)
  }

  const updateData = () => {
    const project = application.currentProject()
    const user = application.currentUser()
    const token = application.persistentToken()

    data = {
      user,
      token,
      project,
      projectId: project.id(),
      isOwner: project.users.some(u => u.id === user.id())
    }

    return data
  }

  window.onload = () => {
    data.isOwner = false

    application.projectIsLoaded.observe((v) => {
      if (v) {
        addCSS(`
          .button-restart {
            position: absolute;
            z-index: 5;
            bottom: 15px;
            right: 20px;
          }
        `)
        addButton()

        updateData()
        updateButton()
      }
    })
  }
})()