|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +package org.apache.tika.pipes.fetchers.google; |
| 18 | + |
| 19 | +import java.io.ByteArrayInputStream; |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.InputStream; |
| 22 | +import java.nio.file.Files; |
| 23 | +import java.nio.file.Path; |
| 24 | +import java.util.ArrayList; |
| 25 | +import java.util.Base64; |
| 26 | +import java.util.List; |
| 27 | +import java.util.Map; |
| 28 | + |
| 29 | +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; |
| 30 | +import com.google.api.client.http.HttpRequestInitializer; |
| 31 | +import com.google.api.client.json.JsonFactory; |
| 32 | +import com.google.api.client.json.gson.GsonFactory; |
| 33 | +import com.google.api.services.drive.Drive; |
| 34 | +import com.google.api.services.drive.DriveScopes; |
| 35 | +import com.google.auth.http.HttpCredentialsAdapter; |
| 36 | +import com.google.auth.oauth2.GoogleCredentials; |
| 37 | +import org.slf4j.Logger; |
| 38 | +import org.slf4j.LoggerFactory; |
| 39 | + |
| 40 | +import org.apache.tika.config.Field; |
| 41 | +import org.apache.tika.config.Initializable; |
| 42 | +import org.apache.tika.config.InitializableProblemHandler; |
| 43 | +import org.apache.tika.config.Param; |
| 44 | +import org.apache.tika.exception.TikaConfigException; |
| 45 | +import org.apache.tika.exception.TikaException; |
| 46 | +import org.apache.tika.io.TemporaryResources; |
| 47 | +import org.apache.tika.io.TikaInputStream; |
| 48 | +import org.apache.tika.metadata.Metadata; |
| 49 | +import org.apache.tika.parser.ParseContext; |
| 50 | +import org.apache.tika.pipes.fetcher.AbstractFetcher; |
| 51 | +import org.apache.tika.pipes.fetchers.google.config.GoogleDriveFetcherConfig; |
| 52 | + |
| 53 | + |
| 54 | +/** |
| 55 | + * GoogleDrive Fetcher allows the fetching of files from a Google Drive, using a |
| 56 | + * service account key. |
| 57 | + * |
| 58 | + * Fetch Keys are ${fileId},${subjectUser}, where the subject user is the |
| 59 | + * organizer of the file. This user is necessary as part of the key as the |
| 60 | + * service account must act on behalf of the user when querying for the file. |
| 61 | + */ |
| 62 | +public class GoogleDriveFetcher extends AbstractFetcher implements Initializable { |
| 63 | + private static final Logger LOGGER = LoggerFactory.getLogger(GoogleDriveFetcher.class); |
| 64 | + private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); |
| 65 | + |
| 66 | + private GoogleCredentials baseCredentials; |
| 67 | + |
| 68 | + private Drive driveService; |
| 69 | + private boolean spoolToTemp; |
| 70 | + private List<String> scopes; |
| 71 | + |
| 72 | + private GoogleDriveFetcherConfig config = new GoogleDriveFetcherConfig(); |
| 73 | + |
| 74 | + public GoogleDriveFetcher() { |
| 75 | + scopes = new ArrayList<>(); |
| 76 | + scopes.add(DriveScopes.DRIVE_READONLY); |
| 77 | + } |
| 78 | + |
| 79 | + public GoogleDriveFetcher(GoogleDriveFetcherConfig config) { |
| 80 | + this.config = config; |
| 81 | + } |
| 82 | + |
| 83 | + @Field |
| 84 | + public void setThrottleSeconds(String commaDelimitedLongs) throws TikaConfigException { |
| 85 | + String[] longStrings = (commaDelimitedLongs == null ? "" : commaDelimitedLongs).split(","); |
| 86 | + long[] seconds = new long[longStrings.length]; |
| 87 | + for (int i = 0; i < longStrings.length; i++) { |
| 88 | + try { |
| 89 | + seconds[i] = Long.parseLong(longStrings[i]); |
| 90 | + } catch (NumberFormatException e) { |
| 91 | + throw new TikaConfigException(e.getMessage()); |
| 92 | + } |
| 93 | + } |
| 94 | + setThrottleSeconds(seconds); |
| 95 | + } |
| 96 | + |
| 97 | + public void setThrottleSeconds(long[] throttleSeconds) { |
| 98 | + config.setThrottleSeconds(throttleSeconds); |
| 99 | + } |
| 100 | + |
| 101 | + @Field |
| 102 | + public void setSpoolToTemp(boolean spoolToTemp) { |
| 103 | + config.setSpoolToTemp(spoolToTemp); |
| 104 | + } |
| 105 | + |
| 106 | + @Field |
| 107 | + public void setServiceAccountKeyBase64(String serviceAccountKeyBase64) { |
| 108 | + config.setServiceAccountKeyBase64(serviceAccountKeyBase64); |
| 109 | + } |
| 110 | + |
| 111 | + @Field |
| 112 | + public void setSubjectUser(String subjectUser) { |
| 113 | + config.setSubjectUser(subjectUser); |
| 114 | + } |
| 115 | + |
| 116 | + @Field |
| 117 | + public void setScopes(List<String> scopes) { |
| 118 | + config.setScopes(new ArrayList<>(scopes)); |
| 119 | + if (config.getScopes().isEmpty()) { |
| 120 | + config.getScopes().add(DriveScopes.DRIVE_READONLY); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + @Override |
| 125 | + public void initialize(Map<String, Param> map) throws TikaConfigException { |
| 126 | + try { |
| 127 | + baseCredentials = GoogleCredentials |
| 128 | + .fromStream(new ByteArrayInputStream(Base64.getDecoder().decode(config.getServiceAccountKeyBase64()))) |
| 129 | + .createScoped(scopes); |
| 130 | + } catch (IOException e) { |
| 131 | + throw new TikaConfigException("Failed to initialize Google Drive service", e); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + @Override |
| 136 | + public void checkInitialization(InitializableProblemHandler initializableProblemHandler) throws TikaConfigException { |
| 137 | + } |
| 138 | + |
| 139 | + @Override |
| 140 | + public InputStream fetch(String fetchKey, Metadata metadata, ParseContext parseContext) throws TikaException, IOException { |
| 141 | + int tries = 0; |
| 142 | + Exception ex = null; |
| 143 | + TemporaryResources tmp = null; |
| 144 | + |
| 145 | + do { |
| 146 | + long start = System.currentTimeMillis(); |
| 147 | + try { |
| 148 | + String[] fetchKeySplit = fetchKey.split(","); |
| 149 | + if (fetchKeySplit.length != 2) { |
| 150 | + throw new TikaException("Invalid fetch key, expected format ${fileId},${subjectUser}: " + fetchKey); |
| 151 | + } |
| 152 | + |
| 153 | + String fileId = fetchKeySplit[0]; |
| 154 | + String subjectUser = fetchKeySplit[1]; |
| 155 | + |
| 156 | + GoogleCredentials delegatedCredentials = baseCredentials.createDelegated(subjectUser); |
| 157 | + final HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(delegatedCredentials); |
| 158 | + |
| 159 | + driveService = new Drive.Builder( |
| 160 | + GoogleNetHttpTransport.newTrustedTransport(), |
| 161 | + JSON_FACTORY, |
| 162 | + requestInitializer).setApplicationName("tika-fetcher-google").build(); |
| 163 | + |
| 164 | + InputStream is = driveService.files() |
| 165 | + .get(fileId) |
| 166 | + .executeMediaAsInputStream(); |
| 167 | + |
| 168 | + if (is == null) { |
| 169 | + throw new IOException("Empty input stream when we tried to parse " + fetchKey); |
| 170 | + } |
| 171 | + |
| 172 | + if (spoolToTemp) { |
| 173 | + tmp = new TemporaryResources(); |
| 174 | + Path tmpPath = tmp.createTempFile(fileId + ".dat"); |
| 175 | + Files.copy(is, tmpPath); |
| 176 | + return TikaInputStream.get(tmpPath); |
| 177 | + } |
| 178 | + return TikaInputStream.get(is); |
| 179 | + |
| 180 | + } catch (Exception e) { |
| 181 | + LOGGER.warn("Exception fetching on retry=" + tries, e); |
| 182 | + ex = e; |
| 183 | + } finally { |
| 184 | + long elapsed = System.currentTimeMillis() - start; |
| 185 | + LOGGER.debug("Total to fetch {}", elapsed); |
| 186 | + } |
| 187 | + |
| 188 | + long[] throttleSeconds = config.getThrottleSeconds(); |
| 189 | + |
| 190 | + LOGGER.warn("Sleeping for {} seconds before retry", throttleSeconds[tries]); |
| 191 | + try { |
| 192 | + Thread.sleep(throttleSeconds[tries] * 1000); |
| 193 | + } catch (InterruptedException e) { |
| 194 | + Thread.currentThread().interrupt(); |
| 195 | + } |
| 196 | + } while (++tries < config.getThrottleSeconds().length); |
| 197 | + |
| 198 | + throw new TikaException("Could not fetch " + fetchKey, ex); |
| 199 | + } |
| 200 | +} |
0 commit comments