001package com.plivo.api.models.media; 002 003import java.io.File; 004import java.io.IOException; 005import java.nio.file.Files; 006import java.nio.file.Path; 007import java.nio.file.Paths; 008 009import com.plivo.api.PlivoClient; 010import com.plivo.api.exceptions.ResourceNotFoundException; 011import com.plivo.api.models.base.Creator; 012 013import okhttp3.MediaType; 014import okhttp3.MultipartBody; 015import okhttp3.MultipartBody.Builder; 016import okhttp3.RequestBody; 017import retrofit2.Call; 018 019import javax.activation.MimetypesFileTypeMap; 020 021public class MediaUploader extends Creator<MediaResponse> { 022 023 private RequestBody filesAsRequestBody = null; 024 025 MediaUploader(String[] fileNames) throws ResourceNotFoundException{ 026 filesAsRequestBody = getFilesForFilenames(fileNames); 027 } 028 029 private RequestBody getFilesForFilenames(String[] fileNames) throws ResourceNotFoundException { 030 Builder builder = new MultipartBody.Builder() 031 .setType(MultipartBody.FORM); 032 for(int i = 0; i < fileNames.length; i++) { 033 File tempFile = new File(fileNames[i]); 034 boolean exists = tempFile.exists(); 035 if(!exists) 036 throw new ResourceNotFoundException("File missing " + fileNames[i]); 037 try { 038 System.out.println(tempFile); 039 System.out.println(tempFile.toPath()); 040 // handle for java 8 041 String content_type = ""; 042 if (Files.probeContentType(tempFile.toPath()) != null ){ 043 content_type = Files.probeContentType(tempFile.toPath()); 044 } else { 045 Path source = Paths.get(fileNames[i]); 046 MimetypesFileTypeMap m = new MimetypesFileTypeMap(source.toString()); 047 content_type = m.getContentType(tempFile); 048 } 049 builder 050 .addFormDataPart("file", fileNames[i], 051 RequestBody.create(MediaType.parse(content_type), tempFile)); 052 } catch (IOException e) { 053 throw new ResourceNotFoundException("Unable to read file " + fileNames[i]); 054 } 055 } 056 return builder.build(); 057 } 058 059 public RequestBody getFilesAsRequestBody() { 060 return this.filesAsRequestBody; 061 } 062 063 064 @Override 065 public Creator<MediaResponse> client(final PlivoClient plivoClient) { 066 this.plivoClient = plivoClient; 067 return this; 068 } 069 070 071 @Override 072 protected Call<MediaResponse> obtainCall() { 073 return client().getApiService().uploadMedia(client().getAuthId(), this.getFilesAsRequestBody()); 074 } 075 076} 077