Ejemplo n.º 1
0
 @POST
 @Path("/filters")
 @Produces({MediaType.APPLICATION_JSON})
 public String setConnectorFilterState(@FormParam("filterState") String stateJSON) {
   StatusModel result;
   Guest guest = AuthHelper.getGuest();
   if (guest == null) return "{}";
   try {
     settingsService.setConnectorFilterState(guest.getId(), stateJSON);
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=setConnectorFilterState")
             .append(" filterState=")
             .append(stateJSON)
             .append(" guestId=")
             .append(guest.getId());
     logger.info(sb.toString());
     result = new StatusModel(true, "Successfully updated filters state!");
   } catch (Exception e) {
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=setConnectorFilterState")
             .append(" guestId=")
             .append(guest.getId())
             .append(" filterState=")
             .append(stateJSON)
             .append(" stackTrace=<![CDATA[")
             .append(Utils.stackTrace(e))
             .append("]]>");
     logger.warn(sb.toString());
     result = new StatusModel(false, "Failed to udpate filters state!");
   }
   return gson.toJson(result);
 }
Ejemplo n.º 2
0
 @DELETE
 @Path("/{connector}")
 @Produces({MediaType.APPLICATION_JSON})
 public String deleteConnector(@PathParam("connector") String connector) {
   StatusModel result;
   Guest guest = AuthHelper.getGuest();
   // If no guest is logged in, return empty array
   if (guest == null) return "{}";
   try {
     Connector apiToRemove = Connector.fromString(connector);
     guestService.removeApiKeys(guest.getId(), apiToRemove);
     result = new StatusModel(true, "Successfully removed " + connector + ".");
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=deleteConnector")
             .append(" connector=")
             .append(connector)
             .append(" guestId=")
             .append(guest.getId());
     logger.info(sb.toString());
   } catch (Exception e) {
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=deleteConnector")
             .append(" connector=")
             .append(connector)
             .append(" guestId=")
             .append(guest.getId())
             .append(" stackTrace=<![CDATA[")
             .append(Utils.stackTrace(e))
             .append("]]>");
     logger.warn(sb.toString());
     result = new StatusModel(false, "Failed to remove " + connector + ".");
   }
   return gson.toJson(result);
 }
Ejemplo n.º 3
0
  public TimezoneMap getTimezoneMap(UpdateInfo updateInfo) throws Exception {
    OAuthConsumer consumer = setupConsumer(updateInfo.apiKey);
    String api_key = guestService.getApiKeyAttribute(updateInfo.apiKey, "bodymediaConsumerKey");
    JSONArray timezoneMapJson = getUserTimezoneHistory(updateInfo, api_key, consumer);
    TimezoneMap ret = new TimezoneMap();

    try {
      for (int i = 0; i < timezoneMapJson.size(); i++) {
        JSONObject jsonRecord = timezoneMapJson.getJSONObject(i);
        final String tzName = jsonRecord.getString("value");
        final String startDateStr = jsonRecord.getString("startDate");
        final String endDateStr = jsonRecord.optString("endDate");
        DateTime startDate;
        DateTime endDate;
        DateTimeZone tz;

        tz = DateTimeZone.forID(tzName);
        startDate = tzmapFormatter.parseDateTime(startDateStr);
        if (endDateStr.equals("")) {
          // Last entry in table has no endDate, set it to be one day in the future
          endDate = new DateTime(tz).plusDays(1);
        } else {
          endDate = tzmapFormatter.parseDateTime(endDateStr);
        }

        ret.add(startDate.getMillis(), endDate.getMillis(), tz);
      }

    } catch (Throwable e) {
      StringBuilder sb =
          new StringBuilder(
                  "module=updateQueue component=updater action=BodymediaUpdater.getTimezoneMap")
              .append(" message=\"exception while getting timezone map\" connector=")
              .append(updateInfo.apiKey.getConnector().toString())
              .append(" guestId=")
              .append(updateInfo.apiKey.getGuestId())
              .append(" stackTrace=<![CDATA[")
              .append(Utils.stackTrace(e))
              .append("]]>");
      ;
      logger.info(sb.toString());
    }
    return ret;
  }
Ejemplo n.º 4
0
 @POST
 @Path("/{connector}/channels")
 @Produces({MediaType.APPLICATION_JSON})
 public String setConnectorChannels(
     @PathParam("connector") String connectorName, @FormParam("channels") String channels) {
   StatusModel result;
   Guest guest = AuthHelper.getGuest();
   // If no guest is logged in, return empty array
   if (guest == null) return "{}";
   try {
     ApiKey apiKey = guestService.getApiKey(guest.getId(), Connector.getConnector(connectorName));
     settingsService.setChannelsForConnector(
         guest.getId(), apiKey.getConnector(), channels.split(","));
     result = new StatusModel(true, "Successfully updated channels for " + connectorName + ".");
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=setConnectorChannels")
             .append(" connector=")
             .append(connectorName)
             .append(" channels=")
             .append(channels)
             .append(" guestId=")
             .append(guest.getId());
     logger.info(sb.toString());
   } catch (Exception e) {
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=setConnectorChannels")
             .append(" connector=")
             .append(connectorName)
             .append(" guestId=")
             .append(guest.getId())
             .append(" stackTrace=<![CDATA[")
             .append(Utils.stackTrace(e))
             .append("]]>");
     logger.warn(sb.toString());
     result = new StatusModel(false, "Failed to set channels for " + connectorName + ".");
   }
   return gson.toJson(result);
 }
Ejemplo n.º 5
0
 @GET
 @Path("/uninstalled")
 @Produces({MediaType.APPLICATION_JSON})
 public String getUninstalledConnectors() {
   Guest guest = AuthHelper.getGuest();
   // If no guest is logged in, return empty array
   if (guest == null) return "[]";
   try {
     List<ConnectorInfo> allConnectors = sysService.getConnectors();
     List<ConnectorInfo> connectors = new ArrayList<ConnectorInfo>();
     for (ConnectorInfo connector : allConnectors) {
       if (connector.enabled && !connector.connectorName.equals("facebook"))
         connectors.add(connector);
     }
     for (int i = 0; i < connectors.size(); i++) {
       if (guestService.hasApiKey(guest.getId(), connectors.get(i).getApi()))
         connectors.remove(i--);
     }
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=getUninstalledConnectors")
             .append(" guestId=")
             .append(guest.getId());
     logger.info(sb.toString());
     return gson.toJson(connectors);
   } catch (Exception e) {
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=getUninstalledConnectors")
             .append(" guestId=")
             .append(guest.getId())
             .append(" stackTrace=<![CDATA[")
             .append(Utils.stackTrace(e))
             .append("]]>");
     logger.warn(sb.toString());
     return gson.toJson(
         new StatusModel(false, "Failed to get uninstalled connectors: " + e.getMessage()));
   }
 }
Ejemplo n.º 6
0
 @GET
 @Path("/filters")
 @Produces({MediaType.APPLICATION_JSON})
 public String getConnectorFilterState() {
   long vieweeId = AuthHelper.getGuestId();
   try {
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=getConnectorFilterState")
             .append(" guestId=")
             .append(vieweeId);
     logger.info(sb.toString());
     return settingsService.getConnectorFilterState(vieweeId);
   } catch (Exception e) {
     StringBuilder sb =
         new StringBuilder("module=API component=connectorStore action=getConnectorFilterState")
             .append(" guestId=")
             .append(vieweeId)
             .append(" stackTrace=<![CDATA[")
             .append(Utils.stackTrace(e))
             .append("]]>");
     logger.warn(sb.toString());
     return gson.toJson(new StatusModel(false, "Failed to get filters: " + e.getMessage()));
   }
 }
  private Calendar getCalendar(final ApiKey apiKey) throws UpdateFailedException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    // Get all the attributes for this connector's oauth token from the stored attributes
    final String accessToken = guestService.getApiKeyAttribute(apiKey, "accessToken");
    final String refreshToken = guestService.getApiKeyAttribute(apiKey, "refreshToken");
    final String clientId = guestService.getApiKeyAttribute(apiKey, "google.client.id");
    final String clientSecret = guestService.getApiKeyAttribute(apiKey, "google.client.secret");
    final GoogleCredential.Builder builder = new GoogleCredential.Builder();
    builder.setTransport(httpTransport);
    builder.setJsonFactory(jsonFactory);
    builder.setClientSecrets(clientId, clientSecret);
    GoogleCredential credential = builder.build();
    final Long tokenExpires = Long.valueOf(guestService.getApiKeyAttribute(apiKey, "tokenExpires"));
    credential.setExpirationTimeMilliseconds(tokenExpires);
    credential.setAccessToken(accessToken);
    credential.setRefreshToken(refreshToken);
    try {
      if (tokenExpires < System.currentTimeMillis()) {
        boolean tokenRefreshed = false;

        // Don't worry about checking if we are running on a mirrored test instance.
        // Refreshing tokens independently on both the main server and a mirrored instance
        // seems to work just fine.

        // Try to swap the expired access token for a fresh one.
        tokenRefreshed = credential.refreshToken();

        if (tokenRefreshed) {
          Long newExpireTime = credential.getExpirationTimeMilliseconds();
          logger.info(
              "google calendar token has been refreshed, new expire time = " + newExpireTime);
          // Update stored expire time
          guestService.setApiKeyAttribute(apiKey, "accessToken", credential.getAccessToken());
          guestService.setApiKeyAttribute(apiKey, "tokenExpires", newExpireTime.toString());
        }
      }
    } catch (TokenResponseException e) {
      logger.warn(
          "module=GoogleCalendarUpdater component=background_updates action=refreshToken"
              + " connector="
              + apiKey.getConnector().getName()
              + " guestId="
              + apiKey.getGuestId()
              + " status=permanently failed");
      // Notify the user that the tokens need to be manually renewed
      notificationsService.addNamedNotification(
          apiKey.getGuestId(),
          Notification.Type.WARNING,
          connector().statusNotificationName(),
          "Heads Up. We failed in our attempt to automatically refresh your Google Calendar authentication tokens.<br>"
              + "Please head to <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a>,<br>"
              + "scroll to the Google Calendar connector, and renew your tokens (look for the <i class=\"icon-resize-small icon-large\"></i> icon)");

      // Record permanent update failure since this connector is never
      // going to succeed
      guestService.setApiKeyStatus(
          apiKey.getId(), ApiKey.Status.STATUS_PERMANENT_FAILURE, Utils.stackTrace(e));
      throw new UpdateFailedException(
          "refresh token attempt permanently failed due to a bad token refresh response", e, true);
    } catch (IOException e) {
      logger.warn(
          "module=GoogleCalendarUpdater component=background_updates action=refreshToken"
              + " connector="
              + apiKey.getConnector().getName()
              + " guestId="
              + apiKey.getGuestId()
              + " status=temporarily failed");
      // Notify the user that the tokens need to be manually renewed
      throw new UpdateFailedException("refresh token attempt failed", e, true);
    }
    final Calendar.Builder calendarBuilder =
        new Calendar.Builder(httpTransport, jsonFactory, credential);
    final Calendar calendar = calendarBuilder.build();
    return calendar;
  }
Ejemplo n.º 8
0
  @GET
  @Path("/installed")
  @Produces({MediaType.APPLICATION_JSON})
  public String getInstalledConnectors() {
    Guest guest = AuthHelper.getGuest();
    // If no guest is logged in, return empty array
    if (guest == null) return "[]";
    ResourceBundle res = ResourceBundle.getBundle("messages/connectors");
    try {
      List<ConnectorInfo> connectors = sysService.getConnectors();
      JSONArray connectorsArray = new JSONArray();
      for (int i = 0; i < connectors.size(); i++) {
        final ConnectorInfo connectorInfo = connectors.get(i);
        final Connector api = connectorInfo.getApi();
        if (api == null) {
          StringBuilder sb =
              new StringBuilder(
                  "module=API component=connectorStore action=getInstalledConnectors ");
          logger.warn("message=\"null connector for " + connectorInfo.getName() + "\"");
          continue;
        }
        if (!guestService.hasApiKey(guest.getId(), api)
            || api.getName().equals("facebook") /*HACK*/) {
          connectors.remove(i--);
        } else {
          ConnectorInfo connector = connectorInfo;
          JSONObject connectorJson = new JSONObject();
          Connector conn = Connector.fromValue(connector.api);
          ApiKey apiKey = guestService.getApiKey(guest.getId(), conn);

          connectorJson.accumulate("prettyName", conn.prettyName());
          List<String> facetTypes = new ArrayList<String>();
          ObjectType[] objTypes = conn.objectTypes();
          if (objTypes != null) {
            for (ObjectType obj : objTypes) {
              facetTypes.add(connector.connectorName + "-" + obj.getName());
            }
          }
          connectorJson.accumulate("facetTypes", facetTypes);
          connectorJson.accumulate(
              "status", apiKey.status != null ? apiKey.status.toString() : "NA");
          connectorJson.accumulate("name", connector.name);
          connectorJson.accumulate("connectUrl", connector.connectUrl);
          connectorJson.accumulate("image", connector.image);
          connectorJson.accumulate("connectorName", connector.connectorName);
          connectorJson.accumulate("enabled", connector.enabled);
          connectorJson.accumulate("manageable", connector.manageable);
          connectorJson.accumulate("text", connector.text);
          connectorJson.accumulate("api", connector.api);
          connectorJson.accumulate("apiKeyId", apiKey.getId());
          connectorJson.accumulate(
              "lastSync", connector.supportsSync ? getLastSync(apiKey) : Long.MAX_VALUE);
          connectorJson.accumulate("latestData", getLatestData(apiKey));
          final String auditTrail = checkForErrors(apiKey);
          connectorJson.accumulate("errors", auditTrail != null);
          connectorJson.accumulate("auditTrail", auditTrail != null ? auditTrail : "");
          connectorJson.accumulate("syncing", checkIfSyncInProgress(guest.getId(), conn));
          connectorJson.accumulate(
              "channels", settingsService.getChannelsForConnector(guest.getId(), conn));
          connectorJson.accumulate("sticky", connector.connectorName.equals("fluxtream_capture"));
          connectorJson.accumulate("supportsRenewToken", connector.supportsRenewTokens);
          connectorJson.accumulate("supportsSync", connector.supportsSync);
          connectorJson.accumulate("supportsFileUpload", connector.supportsFileUpload);
          connectorJson.accumulate("prettyName", conn.prettyName());
          final String uploadMessageKey = conn.getName() + ".upload";
          if (res.containsKey(uploadMessageKey)) {
            final String uploadMessage = res.getString(uploadMessageKey);
            connectorJson.accumulate("uploadMessage", uploadMessage);
          }
          connectorsArray.add(connectorJson);
        }
      }
      StringBuilder sb =
          new StringBuilder("module=API component=connectorStore action=getInstalledConnectors")
              .append(" guestId=")
              .append(guest.getId());
      logger.info(sb.toString());
      return connectorsArray.toString();
    } catch (Exception e) {
      StringBuilder sb =
          new StringBuilder("module=API component=connectorStore action=getInstalledConnectors")
              .append(" guestId=")
              .append(guest.getId())
              .append(" stackTrace=<![CDATA[")
              .append(Utils.stackTrace(e))
              .append("]]>");
      System.out.println(sb.toString());
      logger.warn(sb.toString());
      return gson.toJson(
          new StatusModel(false, "Failed to get installed connectors: " + e.getMessage()));
    }
  }