001package ca.bc.webarts.tools.gapi; 002 003import com.google.api.client.auth.oauth2.Credential; 004import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; 005import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; 006import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 007import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; 008import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details; 009import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 010import com.google.api.client.googleapis.media.MediaHttpDownloader; 011import com.google.api.client.googleapis.media.MediaHttpUploader; 012import com.google.api.client.googleapis.media.MediaHttpDownloaderProgressListener; 013import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener; 014import com.google.api.client.http.FileContent; 015import com.google.api.client.http.GenericUrl; 016import com.google.api.client.http.HttpTransport; 017import com.google.api.client.json.JsonFactory; 018import com.google.api.client.json.jackson2.JacksonFactory; 019import com.google.api.client.util.Preconditions; 020import com.google.api.client.util.store.DataStoreFactory; 021import com.google.api.client.util.store.FileDataStoreFactory; 022import com.google.api.services.drive.Drive; 023import com.google.api.services.drive.DriveScopes; 024import com.google.api.services.drive.model.File; 025 026import java.io.FileOutputStream; 027import java.io.IOException; 028import java.io.InputStreamReader; 029import java.io.OutputStream; 030import java.security.GeneralSecurityException; 031import java.text.NumberFormat; 032import java.util.Collections; 033import java.util.List; 034import java.util.Properties; 035import java.util.Vector; 036 037 038public class GDriveDownloader 039{ 040 /** A holder for this clients System File Separator. */ 041 public final static String SYSTEM_FILE_SEPERATOR = java.io.File.separator; 042 043 /** A holder for this clients System line termination separator. */ 044 public final static String SYSTEM_LINE_SEPERATOR = 045 System.getProperty("line.separator"); 046 private static final String APPLICATION_NAME = "WebARTSDesign-GDriveDownloader/0.1"; 047 private static final String DEFAULT_DOWNLOAD_DIR = "."; 048 private static final String DEFAULT_LOAD_FILENAME = "./gDriveDocument.txt"; 049 private static final String DEFAULT_DATASTORE_DIR = System.getProperty("user.home")+ 050 SYSTEM_FILE_SEPERATOR+ 051 ".store"+ 052 SYSTEM_FILE_SEPERATOR+ 053 "GDriveDownloader"; 054 055 /** The Extension to use on the filename to markk it as AESEncrypted. **/ 056 private static final String ECRYPT_FILEMARKER="etbg"; 057 058 /** The VM classpath (used in some methods).. */ 059 public static String CLASSPATH = System.getProperty("class.path"); 060 061 /** The users home ditrectory. */ 062 public static String USERHOME = System.getProperty("user.home"); 063 064 /** The users pwd ditrectory. */ 065 public static String USERDIR = System.getProperty("user.dir"); 066 067 /** A holder This classes name (used when logging). */ 068 private static String CLASSNAME = "ca.bc.webarts.widgets.Util"; 069 070 071 private static GoogleClientSecrets clientSecrets_ = new GoogleClientSecrets(); 072 073 private String loadFilePath_ = DEFAULT_LOAD_FILENAME; 074 private String dirForDownload_ = DEFAULT_DOWNLOAD_DIR; 075 private java.io.File loadFile_ = new java.io.File(loadFilePath_); 076 077 /** Directory to store user credentials. */ 078 private java.io.File dataStoreDir_ = null; 079 080 /** 081 * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single 082 * globally shared instance across your application. 083 */ 084 private FileDataStoreFactory dataStoreFactory_ = null; 085 086 /** Class instance of the HTTP transport. */ 087 private HttpTransport httpTransport_ = null; 088 089 /** Class instance of the JSON factory. */ 090 private JsonFactory jsonFactory_ = null; 091 092 /** Class Drive API client. */ 093 private Drive drive = null; 094 095 096 public GDriveDownloader() throws GeneralSecurityException, IOException 097 { 098 loadFilePath_ = DEFAULT_LOAD_FILENAME; 099 dirForDownload_ = DEFAULT_DOWNLOAD_DIR; 100 loadFile_ = new java.io.File(loadFilePath_); 101 dataStoreDir_ = new java.io.File(DEFAULT_DATASTORE_DIR); 102 httpTransport_ = GoogleNetHttpTransport.newTrustedTransport(); 103 104 dataStoreFactory_ = new FileDataStoreFactory(dataStoreDir_); 105 jsonFactory_ = JacksonFactory.getDefaultInstance(); 106 } 107 108 public GDriveDownloader(String filenameToLoad) throws GeneralSecurityException, IOException 109 { 110 loadFilePath_ = filenameToLoad; 111 loadFile_ = new java.io.File(loadFilePath_); 112 dirForDownload_ = DEFAULT_DOWNLOAD_DIR; 113 dataStoreDir_ = new java.io.File(DEFAULT_DATASTORE_DIR); 114 httpTransport_ = GoogleNetHttpTransport.newTrustedTransport(); 115 116 dataStoreFactory_ = new FileDataStoreFactory(dataStoreDir_); 117 jsonFactory_ = JacksonFactory.getDefaultInstance(); 118 } 119 120 121 /** Set the filename path for the file that will be uploaded. **/ 122 private void setloadFilePath(String path) 123 { 124 loadFilePath_ = path; 125 loadFile_ = new java.io.File(loadFilePath_); 126 } 127 /** get the filename path for the file that will be uploaded. **/ 128 private String getloadFilePath() { return loadFilePath_; } 129 130 private void initDrive(Credential cred) 131 { 132 // set up the class Drive instance 133 drive = new Drive.Builder(httpTransport_, 134 jsonFactory_, 135 cred 136 ).setApplicationName(APPLICATION_NAME).build(); 137 } 138 139 140 /** Loads the Google secrets / api usage authentication coses for this class. **/ 141 private GoogleClientSecrets initSecrets() throws IOException 142 { 143 boolean readFromJSON = true; 144 145 /* client_secrets.json 146 { 147 "installed": 148 { 149 "auth_uri":"https://accounts.google.com/o/oauth2/auth", 150 "client_secret":"SEBhSW_5eO768sckzzDeyTBH", 151 "token_uri":"https://accounts.google.com/o/oauth2/token", 152 "client_email":"", 153 "redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"], 154 "client_x509_cert_url":"", 155 "client_id":"1035621424646.apps.googleusercontent.com", 156 "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs" 157 } 158 } 159 */ 160 161 if(readFromJSON) 162 { 163 java.io.InputStream is = GDriveDownloader.class.getResourceAsStream("/ca/bc/webarts/tools/gapi/client_secrets.json"); 164 clientSecrets_ = GoogleClientSecrets.load( jsonFactory_, 165 new InputStreamReader(is) 166 ); 167 } 168 else 169 { 170 //GoogleClientSecrets.Details secretDetails = clientSecrets_.getDetails(); 171 GoogleClientSecrets.Details secretDetails = new GoogleClientSecrets.Details(); 172 173 secretDetails.setClientId("1035621424646.apps.googleusercontent.com"); 174 secretDetails.setAuthUri("https://accounts.google.com/o/oauth2/auth"); 175 secretDetails.setClientSecret("SEBhSW_5eO768sckzzDeyTBH"); 176 secretDetails.setTokenUri("https://accounts.google.com/o/oauth2/token"); 177 Vector <String> v = new <String> Vector(); v.add("urn:ietf:wg:oauth:2.0:oob"); v.add("oob"); 178 secretDetails.setRedirectUris(v); 179 secretDetails.set("auth_provider_x509_cert_url","https://www.googleapis.com/oauth2/v1/certs"); 180 secretDetails.set("client_x509_cert_url",""); 181 secretDetails.set("client_email","tgutwin@webarts.ca"); 182 //clientSecrets_.setInstalled(secretDetails); 183 } 184 return clientSecrets_; 185 } 186 187 private Credential authorize() throws Exception 188 { 189 // load client secrets 190 initSecrets(); 191 192 // set up authorization code flow 193 GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport_, 194 jsonFactory_, 195 clientSecrets_, 196 Collections.singleton(DriveScopes.DRIVE_FILE) 197 ).setDataStoreFactory(dataStoreFactory_).build(); 198 // authorize 199 return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); 200 } 201 202 203 204 public static void main(String[] args) 205 { 206 try 207 { 208 GDriveDownloader instance = null; 209 if (args.length>0) 210 { 211 System.out.println(args[0]); 212 instance = new GDriveDownloader(args[0]); 213 } 214 else 215 instance = new GDriveDownloader(); 216 217 // authorization 218 Credential credential = instance.authorize(); 219 instance.initDrive(credential); 220 221 // Drive.About listRequest = instance.drive.files().list(); 222 223 224 //download file from GDrive 225 java.io.File downloadedFile = new java.io.File(instance.getloadFilePath()); 226 String queryStr = "'root'" + " in parents"; 227 228 if(true) 229 { 230 System.out.println("\nListing Drive Files"); 231 Drive.Files.List listRequest = instance.drive.files().list(); 232 233 if (true) queryStr = "'root'" + " in parents"; 234 if (false) queryStr = "'TomsDocs'" + " in parents"; 235 if (false) queryStr = "title contains 'Beer'"; 236 if (false) queryStr = "mimeType = 'application/vnd.google-apps.folder'"; 237 System.out.println("queryStr="+queryStr); 238 listRequest.setQ(queryStr); 239 240 com.google.api.services.drive.model.FileList 241 files = listRequest.execute(); 242 for (com.google.api.services.drive.model.File element : files.getItems()) 243 { 244 System.out.println(element.getTitle()); 245 } 246 } 247 248 //instance.downloadFile(true, instance.loadFile_); 249 250 if(false) 251 { 252 /* Now the folder children */ 253 String folderName = "My Drive"; 254 Drive.Children.List folderListRequest = instance.drive.children().list(folderName); 255 do 256 { 257 try 258 { 259 System.out.println("\nListing folder '"+folderName+"' Files"); 260 com.google.api.services.drive.model.ChildList 261 children = folderListRequest.execute(); 262 263 for (com.google.api.services.drive.model.ChildReference child : children.getItems()) 264 { 265 System.out.println("File Id: " + child.getId()); 266 } 267 folderListRequest.setPageToken(children.getNextPageToken()); 268 } 269 catch (IOException e) 270 { 271 System.out.println("An error occurred: " + e); 272 folderListRequest.setPageToken(null); 273 } 274 } while (folderListRequest.getPageToken() != null && 275 folderListRequest.getPageToken().length() > 0); 276 } 277 278 } 279 catch (GeneralSecurityException gSecEx) 280 { 281 System.err.println(gSecEx.getMessage()); 282 } 283 catch (IOException e) 284 { 285 System.err.println(e.getMessage()); 286 } 287 catch (Throwable t) 288 { 289 t.printStackTrace(); 290 } 291 System.exit(1); 292 } 293 294 295 /** Downloads a file using either resumable or direct media download. */ 296 private void downloadFile(boolean useDirectDownload, java.io.File fileToDownload) throws IOException 297 { 298 if (drive!=null) 299 { 300 // create parent directory (if necessary) 301 java.io.File parentDir = new java.io.File(dirForDownload_); 302 if (!parentDir.exists() && !parentDir.mkdirs()) 303 { 304 throw new IOException("Unable to create parent directory"); 305 } 306 OutputStream out = new FileOutputStream(new java.io.File(parentDir, loadFilePath_)); 307 308 MediaHttpDownloader downloader = new MediaHttpDownloader(httpTransport_, drive.getRequestFactory().getInitializer()); 309 downloader.setDirectDownloadEnabled(useDirectDownload); 310 downloader.setProgressListener(new FileDownloadProgressListener()); 311 // downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out); 312 } 313 } 314} 315