|
| 1 | +/* |
| 2 | + * Copyright 2020 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.functions; |
| 18 | + |
| 19 | +import com.github.seratch.jslack.app_backend.SlackSignature; |
| 20 | +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; |
| 21 | +import com.google.api.client.json.jackson2.JacksonFactory; |
| 22 | +import com.google.api.services.kgsearch.v1.Kgsearch; |
| 23 | +import com.google.cloud.functions.HttpFunction; |
| 24 | +import com.google.cloud.functions.HttpRequest; |
| 25 | +import com.google.cloud.functions.HttpResponse; |
| 26 | +import com.google.gson.Gson; |
| 27 | +import com.google.gson.JsonArray; |
| 28 | +import com.google.gson.JsonObject; |
| 29 | +import java.io.BufferedWriter; |
| 30 | +import java.io.IOException; |
| 31 | +import java.net.HttpURLConnection; |
| 32 | +import java.security.GeneralSecurityException; |
| 33 | +import java.util.HashMap; |
| 34 | +import java.util.List; |
| 35 | +import java.util.logging.Logger; |
| 36 | +import java.util.stream.Collectors; |
| 37 | + |
| 38 | +public class SlackSlashCommand implements HttpFunction { |
| 39 | + |
| 40 | + private Kgsearch kgClient; |
| 41 | + private static final String API_KEY = System.getenv("KG_API_KEY"); |
| 42 | + private static final String SLACK_SECRET = System.getenv("SLACK_SECRET"); |
| 43 | + private static final Logger LOGGER = Logger.getLogger(SlackSlashCommand.class.getName()); |
| 44 | + private SlackSignature.Verifier verifier; |
| 45 | + private Gson gson = new Gson(); |
| 46 | + |
| 47 | + public SlackSlashCommand() throws IOException, GeneralSecurityException { |
| 48 | + kgClient = new Kgsearch.Builder( |
| 49 | + GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), null).build(); |
| 50 | + |
| 51 | + verifier = new SlackSignature.Verifier(new SlackSignature.Generator(SLACK_SECRET)); |
| 52 | + } |
| 53 | + |
| 54 | + boolean isValidSlackWebhook(HttpRequest request, String requestBody) throws IOException { |
| 55 | + |
| 56 | + // Check for headers |
| 57 | + HashMap<String, List<String>> headers = new HashMap(request.getHeaders()); |
| 58 | + if (!headers.containsKey("X-Slack-Request-Timestamp") |
| 59 | + || !headers.containsKey("X-Slack-Signature")) { |
| 60 | + return false; |
| 61 | + } |
| 62 | + return verifier.isValid( |
| 63 | + headers.get("X-Slack-Request-Timestamp").get(0), |
| 64 | + requestBody, |
| 65 | + headers.get("X-Slack-Signature").get(0), |
| 66 | + 1L); |
| 67 | + } |
| 68 | + |
| 69 | + void addPropertyIfPresent( |
| 70 | + JsonObject target, String targetName, JsonObject source, String sourceName) { |
| 71 | + if (source.has(sourceName)) { |
| 72 | + target.addProperty(targetName, source.get(sourceName).getAsString()); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + String formatSlackMessage(JsonObject kgResponse, String query) { |
| 77 | + JsonObject attachmentJson = new JsonObject(); |
| 78 | + JsonArray attachments = new JsonArray(); |
| 79 | + |
| 80 | + JsonObject responseJson = new JsonObject(); |
| 81 | + responseJson.addProperty("response_type", "in_channel"); |
| 82 | + responseJson.addProperty("text", String.format("Query: %s", query)); |
| 83 | + |
| 84 | + JsonArray entityList = kgResponse.getAsJsonArray("itemListElement"); |
| 85 | + |
| 86 | + // Extract the first entity from the result list, if any |
| 87 | + if (entityList.size() == 0) { |
| 88 | + attachmentJson.addProperty("text","No results match your query..."); |
| 89 | + |
| 90 | + attachments.add(attachmentJson); |
| 91 | + responseJson.add("attachments", attachmentJson); |
| 92 | + |
| 93 | + return gson.toJson(responseJson); |
| 94 | + } |
| 95 | + |
| 96 | + JsonObject entity = entityList.get(0).getAsJsonObject().getAsJsonObject("result"); |
| 97 | + |
| 98 | + // Construct Knowledge Graph response attachment |
| 99 | + String title = entity.get("name").getAsString(); |
| 100 | + if (entity.has("description")) { |
| 101 | + title = String.format("%s: %s", title, entity.get("description").getAsString()); |
| 102 | + } |
| 103 | + attachmentJson.addProperty("title", title); |
| 104 | + |
| 105 | + if (entity.has("detailedDescription")) { |
| 106 | + JsonObject detailedDescJson = entity.getAsJsonObject("detailedDescription"); |
| 107 | + addPropertyIfPresent(attachmentJson, "title_link", detailedDescJson, "url"); |
| 108 | + addPropertyIfPresent(attachmentJson, "text", detailedDescJson, "articleBody"); |
| 109 | + } |
| 110 | + |
| 111 | + if (entity.has("image")) { |
| 112 | + JsonObject imageJson = entity.getAsJsonObject("image"); |
| 113 | + addPropertyIfPresent(attachmentJson, "image_url", imageJson, "contentUrl"); |
| 114 | + } |
| 115 | + |
| 116 | + // Construct top level response |
| 117 | + attachments.add(attachmentJson); |
| 118 | + responseJson.add("attachments", attachmentJson); |
| 119 | + |
| 120 | + return gson.toJson(responseJson); |
| 121 | + } |
| 122 | + |
| 123 | + JsonObject searchKnowledgeGraph(String query) throws IOException { |
| 124 | + Kgsearch.Entities.Search kgRequest = kgClient.entities().search(); |
| 125 | + kgRequest.setQuery(query); |
| 126 | + kgRequest.setKey(API_KEY); |
| 127 | + |
| 128 | + return gson.fromJson(kgRequest.execute().toString(), JsonObject.class); |
| 129 | + } |
| 130 | + |
| 131 | + @Override |
| 132 | + public void service(HttpRequest request, HttpResponse response) throws IOException { |
| 133 | + |
| 134 | + // Validate request |
| 135 | + if (request.getMethod() != "POST") { |
| 136 | + response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); |
| 137 | + return; |
| 138 | + } |
| 139 | + |
| 140 | + // reader can only be read once per request, so we preserve its contents |
| 141 | + String bodyString = request.getReader().lines().collect(Collectors.joining()); |
| 142 | + JsonObject body = (new Gson()).fromJson(bodyString, JsonObject.class); |
| 143 | + |
| 144 | + if (body == null || !body.has("text")) { |
| 145 | + response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); |
| 146 | + return; |
| 147 | + } |
| 148 | + |
| 149 | + if (!isValidSlackWebhook(request, bodyString)) { |
| 150 | + response.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED); |
| 151 | + return; |
| 152 | + } |
| 153 | + |
| 154 | + String query = body.get("text").getAsString(); |
| 155 | + |
| 156 | + // Call knowledge graph API |
| 157 | + JsonObject kgResponse = searchKnowledgeGraph(query); |
| 158 | + |
| 159 | + // Format response to Slack |
| 160 | + BufferedWriter writer = response.getWriter(); |
| 161 | + writer.write(formatSlackMessage(kgResponse, query)); |
| 162 | + } |
| 163 | +} |
0 commit comments