Подтвердить что ты не робот

Статус загрузки видео в Vimeo

Я загружаю видео в Vimeo, используя свое приложение, но некоторые из моих статусов видео не обновляются Снимок экрана видео на сайте Vimeo

Я выполнил документ api, указанный в этой ссылке: https://developer.vimeo.com/api/upload/videos:

Я использую код ниже:

public  boolean sendVideo(String file1, String completeURi, String     endpoint, String id) throws FileNotFoundException, IOException {

    File file = new File(file1);

    long contentLength = file.length();
    String contentLengthString = Long.toString(contentLength);
    FileInputStream is = new FileInputStream(file);

    int bufferSize = 20485760; 
    byte[] bytesPortion = new byte[bufferSize];
    int byteNumber = 0;

    while (is.read(bytesPortion, 0, bufferSize) != -1) {
        String contentRange = Integer.toString(byteNumber);
        boolean success = false;
        int bytesOnServer = 0;

        while (!success) {
            long bytesLeft = contentLength - (bytesOnServer);
            System.out.println(newline + newline + "Bytes Left: " + bytesLeft);
            if (bytesLeft < bufferSize) {
                //copy the bytesPortion array into a smaller array containing only the remaining bytes
                bytesPortion = Arrays.copyOf(bytesPortion, (int) bytesLeft);
                //This just makes it so it doesn't throw an IndexOutOfBounds exception on the next while iteration. It shouldn't get past another iteration
                bufferSize = (int) bytesLeft;
            }
             bytesOnServer = sendVideoBytes("Vimeo Video upload", endpoint, contentLengthString, "video/mp4", contentRange, bytesPortion, first,isuploaded);

            AppLog.e("bytesOnServer", "===contentLength===" + bytesOnServer +"&&=="+contentLengthString);

            if (bytesOnServer >= Integer.parseInt(contentLengthString)) {

                System.out.println("Success is  true!");
                return true;

            } else {
                contentRange = (bytesOnServer + 1) + "-" + (Integer.parseInt(contentLengthString)) + "/" + (Integer.parseInt(contentLengthString));

                System.out.println(bytesOnServer + " != " + contentLength);
                System.out.println("Success is not true!"+contentRange);

                success=false;
                first = true;
            }

        }



    }
    return true;
}

/**
 * Sends the given bytes to the given endpoint
 *
 * @return the last byte on the server (from verifyUpload(endpoint))
 */
private static int sendVideoBytes(String videoTitle, String endpoint, String contentLength, String fileType, String contentRange, byte[] fileBytes, boolean addContentRange,boolean isuploaded) throws FileNotFoundException, IOException {
    OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
    request.addHeader("Content-Length", contentLength);
    request.addHeader("Content-Type", fileType);


    if (addContentRange) {
        request.addHeader("Content-Range", "bytes " + contentRange);
    }


    request.addPayload(fileBytes);

    Response response = signAndSendToVimeo(request, "sendVideo with file bytes " + videoTitle, false);



    if (response.getCode() != 200 && !response.isSuccessful()) {
        return -1;
    }


    return verifyUpload(endpoint, contentLength, contentRange,isuploaded);
}

/**
 * Verifies the upload and returns whether it successful
 *
 * @param
 * @param contentLength
 * @param endpoint      to verify upload to  @return the last byte on the server
 */
public static int verifyUpload(String endpoint, String contentLength, String contentRange,boolean isuploaded) {
    // Verify the upload
    OAuthRequest request = new OAuthRequest(Verb.PUT, endpoint);
    request.addHeader("Content-Length", "0");
    request.addHeader("Content-Range", "bytes */*");

    Response response = signAndSendToVimeo(request, "verifyUpload to " + endpoint, true);

    AppLog.e("verifyUpload", "" + response.getCode());
    if (response.getCode() != 308 || !response.isSuccessful()) {
        return -1;
    }
    String range = response.getHeader("Range");

    AppLog.e("After verify","==range header contains"+Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)));
    //range = "bytes=0-10485759"
    return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)); //+1 remove
    //return Integer.parseInt(range.substring(range.lastIndexOf("-") + 1)) + 1;
    //The + 1 at the end is because Vimeo gives you 0-whatever byte where 0 = the first byte
}

public static Response signAndSendToVimeo(OAuthRequest request, String description, boolean printBody) throws org.scribe.exceptions.OAuthException {
    String newline = "\n";

    System.out.println(newline + newline
            + "Signing " + description + " request:"
            + ((printBody && !request.getBodyContents().isEmpty()) ? newline + "\tBody Contents:" + request.getBodyContents() : "")
            + ((!request.getHeaders().isEmpty()) ? newline + "\tHeaders: " + request.getHeaders() : ""));
    service.signRequest(OAuthConstants.EMPTY_TOKEN, request);



    Response response = request.send();
   // AppLog.e("Uplaod Video aftre Response", "" + response.getCode());

    return response;
}

Может ли кто-нибудь помочь с рабочим кодом для Android? Спасибо заранее!

4b9b3361

Ответ 1

Недавно у меня была такая же проблема с vimeo. Api возвращает состояние VIMUploadState_Succeeded для процесса загрузки, но если вы попытаетесь посмотреть видео на vimeo.com, оно застряло в состоянии загрузки и отобразится черный экран в приложении, когда вы пытаетесь воспроизвести видео.

Я получил следующие ответы от своей команды поддержки:

Похоже, это конкретное видео не изменилось из загруженного состояния в состояние отказа.

Извините, но видео, предоставленное в этих ссылках, никогда не завершало загрузку и потеряны. Они должны быть повторно загружены.

В нашей платформе есть несколько видеороликов, загружаемых каждый день, и, похоже, у них нет шаблонов для идентификации, когда эта проблема будет связана с загрузкой. Если вам не нужно повторно загружать видео, vimeo может быть хорошим решением, поскольку его цена действительно хороша по сравнению с другими видеоплатфами, в противном случае вы должны искать другое решение для хранения/воспроизведения видео.

Ответ 2

Трудно проверить код без правильной отладки.

Здесь обходной путь для вашего кода с добавлением немного дополнительных функций

Вы можете проверить код здесь