Created
September 18, 2019 08:08
-
-
Save aliwo/545567f946613c6c860fed77ab5ee8dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package buv.co.kr.util.youtube;/* | |
* Copyright (c) 2012 Google Inc. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except | |
* in compliance with the License. You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software distributed under the License | |
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express | |
* or implied. See the License for the specific language governing permissions and limitations under | |
* the License. | |
*/ | |
import android.app.Activity; | |
import android.content.Context; | |
import android.net.Uri; | |
import android.os.AsyncTask; | |
import android.util.Log; | |
import android.widget.Toast; | |
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; | |
import com.google.api.client.googleapis.json.GoogleJsonResponseException; | |
import com.google.api.client.googleapis.media.MediaHttpUploader; | |
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener; | |
import com.google.api.client.http.HttpTransport; | |
import com.google.api.client.http.InputStreamContent; | |
import com.google.api.client.http.javanet.NetHttpTransport; | |
import com.google.api.client.json.JsonFactory; | |
import com.google.api.client.json.gson.GsonFactory; | |
import com.google.api.services.youtube.YouTube; | |
import com.google.api.services.youtube.model.Video; | |
import com.google.api.services.youtube.model.VideoSnippet; | |
import com.google.api.services.youtube.model.VideoStatus; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FilenameFilter; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.Calendar; | |
import java.util.List; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import buv.co.kr.data.api.rest.request.IdResponse; | |
import buv.co.kr.data.api.rest.request.P_clipRequest; | |
import buv.co.kr.ui.thumbnail.util.ThumbnailUtils; | |
import buv.co.kr.ui.thumbnail.view.UploadActivity; | |
import buv.co.kr.ui.thumbnail.viewModel.UploadViewModel; | |
import buv.co.kr.util.SharedPreferenceUtilKt; | |
import buv.co.kr.util.network.NetworkUtilKt; | |
import io.reactivex.Single; | |
import io.reactivex.android.schedulers.AndroidSchedulers; | |
import io.reactivex.schedulers.Schedulers; | |
/** | |
* Demo of uploading a video to a user's account using the YouTube Data API (V3) with OAuth2 for | |
* authorization. | |
* <p> | |
* TODO: PLEASE NOTE, YOU MUST ADD YOUR VIDEO FILES TO THE PROJECT FOLDER TO UPLOAD THEM WITH THIS | |
* APPLICATION! | |
* | |
* @author Jeremy Walker | |
*/ | |
public class YoutubeUtil { | |
/** | |
* Global instance of the HTTP transport. | |
*/ | |
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); | |
/** | |
* Global instance of the JSON factory. | |
*/ | |
private static final JsonFactory JSON_FACTORY = new GsonFactory(); | |
/** | |
* Global instance of Youtube object to make all API requests. | |
*/ | |
private static YouTube youtube; | |
private static Video tempVideo; | |
/* Global instance of the format used for the video being uploaded (MIME category). */ | |
private static String VIDEO_FILE_FORMAT = "video/*"; | |
public static final int VIDEO = 0; | |
public static final int IMAGE = 1; | |
/** | |
* Authorizes the installed application to access user's protected data. | |
* | |
* @param scopes list of scopes needed to run youtube upload. | |
*/ | |
/** | |
* Uploads user selected video in the project folder to the user's YouTube account using OAuth2 | |
* for authentication. | |
* | |
* @param uri | |
*/ | |
public static void preUpload(int type, Context context, Uri uri, int category, String title, String description, Boolean enabled, UploadViewModel uploadVM) { | |
// Scope required to upload to YouTube. | |
// List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload"); | |
if (type == VIDEO) { | |
try { | |
// Authorization. | |
GoogleCredential credential = new GoogleCredential().setAccessToken(SharedPreferenceUtilKt.getSpStringData(SharedPreferenceUtilKt.clipTokenAtCookie)); | |
// GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Lists.newArrayList(Auth.SCOPES)); | |
// credential.setSelectedAccountName(""); | |
// credential.setBackOff(new ExponentialBackOff()); | |
// YouTube object used to make all API requests. | |
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( | |
"youtube-cmdline-YoutubeUtil-sample").build(); | |
// We get the user selected local video file to upload. | |
File videoFile = new File(uri.getPath()); | |
System.out.println("You chose " + videoFile + " to upload."); | |
// Add extra information to the video before uploading. | |
Video videoObjectDefiningMetadata = new Video(); | |
/* | |
* Set the video to public, so it is available to everyone (what most people want). This is | |
* actually the default, but I wanted you to see what it looked like in case you need to set | |
* it to "unlisted" or "private" via API. | |
*/ | |
VideoStatus status = new VideoStatus(); | |
status.setPrivacyStatus("public"); | |
videoObjectDefiningMetadata.setStatus(status); | |
// We set a majority of the metadata with the VideoSnippet object. | |
VideoSnippet snippet = new VideoSnippet(); | |
/* | |
* The Calendar instance is used to create a unique title and description for test purposes, so | |
* you can see multiple files being uploaded. You will want to remove this from your project | |
* and use your own standard names. | |
*/ | |
Calendar cal = Calendar.getInstance(); | |
snippet.setTitle(title); | |
snippet.setDescription(description); | |
// Set your keywords. | |
List<String> tags = new ArrayList<>(); | |
tags.add("buv"); | |
tags.add("streamer"); | |
snippet.setTags(tags); | |
// Set completed snippet to the video object. | |
videoObjectDefiningMetadata.setSnippet(snippet); | |
InputStreamContent mediaContent = new InputStreamContent( | |
VIDEO_FILE_FORMAT, new BufferedInputStream(new FileInputStream(videoFile))); | |
mediaContent.setLength(videoFile.length()); | |
/* | |
* The upload command includes: 1. Information we want returned after file is successfully | |
* uploaded. 2. Metadata we want associated with the uploaded video. 3. Video file itself. | |
*/ | |
YouTube.Videos.Insert videoInsert = youtube.videos() | |
.insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent); | |
// Set the upload category and add event listener. | |
MediaHttpUploader uploader = videoInsert.getMediaHttpUploader(); | |
/* | |
* Sets whether direct media upload is enabled or disabled. True = whole media created_at is | |
* uploaded in a single request. False (default) = resumable media upload protocol to upload | |
* in data chunks. | |
*/ | |
uploader.setDirectUploadEnabled(false); | |
MediaHttpUploaderProgressListener progressListener = uploader1 -> { | |
switch (uploader1.getUploadState()) { | |
case INITIATION_STARTED: | |
System.out.println("Initiation Started"); | |
break; | |
case INITIATION_COMPLETE: | |
System.out.println("Initiation Completed"); | |
break; | |
case MEDIA_IN_PROGRESS: | |
System.out.println("Upload in progress"); | |
System.out.println("Upload percentage: " + uploader1.getProgress()); | |
uploadVM.updateProgress(uploader1.getProgress()); | |
break; | |
case MEDIA_COMPLETE: | |
System.out.println("Upload Completed!"); | |
break; | |
case NOT_STARTED: | |
System.out.println("Upload Not Started!"); | |
break; | |
} | |
}; | |
uploader.setProgressListener(progressListener); | |
// Execute upload. | |
AsyncTask<Void, Void, Video> asyncTask = new AsyncTask<Void, Void, Video>() { | |
@Override | |
protected Video doInBackground(Void... voids) { | |
try { | |
Video returnedVideo = videoInsert.execute(); | |
// Print out returned results. | |
System.out.println("\n================== Returned Video ==================\n"); | |
System.out.println(" - Id: " + returnedVideo.getId()); | |
System.out.println(" - Title: " + returnedVideo.getSnippet().getTitle()); | |
System.out.println(" - Tags: " + returnedVideo.getSnippet().getTags()); | |
System.out.println(" - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus()); | |
System.out.println(" - Video Count: " + returnedVideo.getStatistics().getViewCount()); | |
return returnedVideo; | |
} catch (GoogleJsonResponseException e) { | |
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " | |
+ e.getDetails().getMessage()); | |
e.printStackTrace(); | |
} catch (IOException e) { | |
System.err.println("IOException: " + e.getMessage()); | |
e.printStackTrace(); | |
} catch (Throwable t) { | |
System.err.println("Throwable: " + t.getMessage()); | |
t.printStackTrace(); | |
} | |
return null; | |
} | |
@Override | |
protected void onPostExecute(Video video) { | |
super.onPostExecute(video); | |
tempVideo = video; | |
if (video != null) { | |
// val file = File(uri.path) | |
// val imageRequestBody = RequestBody.create(MediaType.parse("image/*"), file) | |
// | |
// val image = MultipartBody.Part.createFormData("image", file.title, imageRequestBody) | |
// val fileName = RequestBody.create(MediaType.parse("text/plain"), file.title) | |
// | |
// getNetworkInstance().postImage( | |
// getSpStringData(tokenAtCookie), | |
// fileName = fileName, | |
// image = image | |
// ) | |
// .subscribeOn(Schedulers.io()) | |
// .observeOn(AndroidSchedulers.mainThread()) | |
// .subscribe({response -> | |
// if (response.okay) { | |
// Log.d("UploadActivity ", "postAlbumClips response : $response") | |
// finish() | |
// } else { | |
// Toast.makeText(this, "업로드 실패", Toast.LENGTH_SHORT).show() | |
// } | |
// },{ | |
// throwable -> | |
// print(throwable.toString()) | |
// Toast.makeText(this, "네트워크 오류입니다. 관리자에게 문의하세요.", Toast.LENGTH_SHORT).show() | |
// }) | |
Log.d("thumbnail 확인 : ", ThumbnailUtils.INSTANCE.getBmpFileUrl()); | |
Single<IdResponse> postClip = NetworkUtilKt.getNetworkInstance().postClip( | |
SharedPreferenceUtilKt.getSpStringData(SharedPreferenceUtilKt.tokenAtCookie), | |
new P_clipRequest( | |
false, | |
video.getId(), | |
video.getSnippet().getTitle(), | |
video.getSnippet().getDescription(), | |
category, | |
ThumbnailUtils.INSTANCE.getBmpFileUrl(), | |
enabled)); | |
postClip.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe((response) -> { | |
if (response.getOkay()) { | |
((UploadActivity) context).setResult(Activity.RESULT_OK, ((UploadActivity) context).getIntent()); | |
((UploadActivity) context).finish(); | |
} else { | |
Toast.makeText(context, "업로드 실패", Toast.LENGTH_SHORT).show(); | |
} | |
}, (throwable) -> { | |
System.out.print(throwable.toString()); | |
Toast.makeText(context, "네트워크 오류입니다. 관리자에게 문의하세요.", Toast.LENGTH_SHORT).show(); | |
}); | |
} else { | |
Toast.makeText(context, "네트워크 오류입니다. 관리자에게 문의하세요.", Toast.LENGTH_SHORT).show(); | |
} | |
} | |
}; | |
asyncTask.execute(); | |
} catch (GoogleJsonResponseException e) { | |
System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " | |
+ e.getDetails().getMessage()); | |
e.printStackTrace(); | |
} catch (IOException e) { | |
System.err.println("IOException: " + e.getMessage()); | |
e.printStackTrace(); | |
} catch (Throwable t) { | |
System.err.println("Throwable: " + t.getMessage()); | |
t.printStackTrace(); | |
} | |
} else { | |
Single<IdResponse> postClip = NetworkUtilKt.getNetworkInstance().postClip( | |
SharedPreferenceUtilKt.getSpStringData(SharedPreferenceUtilKt.tokenAtCookie), | |
new P_clipRequest( | |
false, | |
null, | |
title, | |
description, | |
category, | |
ThumbnailUtils.INSTANCE.getBmpFileUrl(), | |
enabled)); | |
postClip.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.subscribe((response) -> { | |
if (response.getOkay()) { | |
((UploadActivity) context).setResult(Activity.RESULT_OK, ((UploadActivity) context).getIntent()); | |
((UploadActivity) context).finish(); | |
} else { | |
Toast.makeText(context, "업로드 실패", Toast.LENGTH_SHORT).show(); | |
} | |
}, (throwable) -> { | |
System.out.print(throwable.toString()); | |
Toast.makeText(context, "네트워크 오류입니다. 관리자에게 문의하세요.", Toast.LENGTH_SHORT).show(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment