dblock/slack-sup

View on GitHub
public/gcal.html.erb

Summary

Maintainability
Test Coverage
<html>
  <head>
    <title>S'Up for Slack Teams: Create a Calendar Event</title>
    <%= partial 'public/partials/_head.html.erb' %>
    <%= partial 'public/partials/_scripts.html' %>
  </head>
  <body style='text-align: center'>
    <p style='margin: 50px;'>
      <a href='/'><img src='img/icon.png' width='120px'></a>
    </p>
    <p>
      <h3>S'Up for Slack Teams: Creating a Calendar Event</h3>
    </p>
    <p id='messages' />

    <script type="text/javascript">

      var CLIENT_ID = '<%= ENV['GOOGLE_API_CLIENT_ID'] %>';
      var SCOPES = "https://www.googleapis.com/auth/calendar.events";

      <% sup = Sup.where(id: request.params['sup_id']).first %>

      var sup = {
        id: <%= sup ? "'#{sup.id}'" : "null" %>,
        with: "<%= sup && sup.users.map(&:real_name).and %>",
        emails: ['<%= sup && sup.users.map(&:email).join("','") %>'],
        access_token: '<%= request.params["access_token"] %>',
        access_token_valid: <%= !! (request.params["access_token"] && sup.team.short_lived_token_valid?(request.params["access_token"])) %>,
        dt_time_zone: '<%= sup && sup.team.sup_tzone.tzinfo.identifier %>',
        dt_start_iso8601: '<%= Time.at(request.params['dt'].to_i).strftime('%Y-%m-%dT%H:%M:%S.%L%z') %>',
        dt_end_iso8601: '<%= Time.at(request.params['dt'].to_i + 20 * 60).strftime('%Y-%m-%dT%H:%M:%S.%L%z') %>',
        dt: <%= request.params['dt'] ? request.params['dt'].to_i : "null" %>,
        dt_s: '<%= dt = Time.at(request.params['dt'].to_i).in_time_zone(sup && sup.team.sup_tzone); "#{dt.strftime('%A, %B %d, %Y')} at #{dt.strftime('%l:%M %P').strip}" %>'
      }

      function handleClientLoad() {
        if (!CLIENT_ID) {
          SlackSup.errorMessage("Missing GOOGLE_API_CLIENT_ID.");
        } else if (sup.id && sup.dt && sup.access_token_valid) {
          SlackSup.message("Adding S'Up calendar for <b>" + sup.with + "</b> on " + sup.dt_s + " ...");
          gisInit();
        } else if (!sup.id) {
          SlackSup.errorMessage("Missing or invalid S'Up ID.");
        } else if (!sup.dt) {
          SlackSup.errorMessage("Missing or invalid S'Up time.");
        } else if (!sup.access_token_valid) {
          SlackSup.errorMessage("This link has expired, ask for a new one on your S'Up channel.");
        } else {
          SlackSup.errorMessage("Unexpected error.");
        }
      }

      let tokenClient;
      let gapiInited;
      let gisInited;

      function checkBeforeStart() {
        if (gapiInited && gisInited){
          prepareCreateEvent()
        }
      }

      function gapiInit() {
        gapi.client.init({

        })
        .then(function() {
          gapi.client.load('https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest');
          gapiInited = true;
          checkBeforeStart();
        });
      }

      function gapiLoad() {
        gapi.load('client', gapiInit)
      }

      function gisInit() {
        tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: CLIENT_ID,
          scope: SCOPES,
          callback: this.createEvent, 
        });

        gisInited = true;
        checkBeforeStart();
      }

      function prepareCreateEvent() {
        tokenClient.callback = (resp) => {
          if (resp.error !== undefined) {
            throw(resp);
          }
          // console.log('gapi.client access token: ' + JSON.stringify(gapi.client.getToken()));
          createEvent();
        }

        if (gapi.client.getToken() === null) {
          tokenClient.requestAccessToken({ prompt: 'consent' });
        } else {
          tokenClient.requestAccessToken({ prompt: '' });
        }
      }

      function createEvent() {
        var event = {
          'summary': "S'Up with " + sup.with,
          'location': null,
          'description': "A 20 minute standup to talk about the awesome things we're working on.",
          'start': {
            'dateTime': sup.dt_start_iso8601,
            'timeZone': sup.dt_time_zone
          },
          'end': {
            'dateTime': sup.dt_end_iso8601,
            'timeZone': sup.dt_time_zone
          },
          'attendees': sup.emails.map(function(email) {
            return { "email" : email };
          }),
          'reminders': {
            'useDefault': true
          }
        };

        var request = gapi.client.calendar.events.insert({
          'calendarId': 'primary',
          'resource': event
        });

        request.execute(function(response) {
          if (response.error) {
            SlackSup.errorMessage(response.message || 'Unexpected error creating a Google Calendar event.');
          } else if (response.htmlLink) {
            $.ajax({
              type: 'PUT',
              url: '/api/sups/' + sup.id,
              beforeSend: function(request) {
                request.setRequestHeader('X-Access-Token', sup.access_token);
              },
              data: {
                gcal_html_link: response.htmlLink
              },
              success: function(data) {
                SlackSup.message("Added S'Up calendar for <b>" + sup.with + "</b> on " + sup.dt_s + ". You may close this window.");
              },
              error: function(xhr) {
                SlackSup.error(xhr);
              }
            });
          } else {
            SlackSup.errorMessage("Unexpected error creating a Google Calendar event.");
          }
        });
      }

    </script>

    <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoad()"></script>
    <script async defer src="https://accounts.google.com/gsi/client"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
  </body>
</html>