Программное продвижение бета-версии apk в рабочую версию

Я использую Google Play Developer API v2 для программной загрузки своих бета-пакетов в игровой магазин, и он работает нормально :-)

Теперь я хотел бы программно «продвинуть» бета-файлы apks с «бета-версии» на «рабочую» (так что мне больше не нужно делать это вручную в консоли разработчика Google. Мое приложение набор состоит из 10 приложений .. это требует времени)

Я пытаюсь, но не совсем понимаю, как мне обойтись без повторной загрузки файлов apks.
Я хочу изменить ранее загруженные файлы apks и просто изменить Отслеживать, от «бета» на «производство».

Ниже приведен код, который я написал:

  • Найти все треки
  • Найдите трек "бета"
  • найти соответствующий apk
  • Измените (но не правильным образом) трек apk с "бета" на "рабочий"
  • зафиксировать изменения -> исключение ниже:
SEVERE: Exception was thrown while updating listing
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "androidpublisher",
    "message" : "Testing-track (alpha/beta) APK with version code 1522428584 appears in another track",
    "reason" : "testingTrackApkInMultipleTracks"
  } ],
  "message" : "Testing-track (alpha/beta) APK with version code 1522428584 appears in another track"
}
  at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
  at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
  at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
  at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
  at com.elementique.tools.publish.elementique.ElementiquePromoteBetaApkToProduction.main(ElementiquePromoteBetaApkToProduction.java:74)

В соответствии с исключением, написанный мной код не изменяет существующий apk, а вместо этого пытается создать новый с тем же идентификатором, что и существующая бета-версия.
Я понимаю, что это неправильно, но могу ' Я не знаю, как это сделать правильно ..

Вот код: может кто-нибудь объяснить мне, как это сделать правильно?

Спасибо.

package com.elementique.tools.publish.elementique;

import com.elementique.tools.publish.AndroidPublisherHelper;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisher.Edits;
import com.google.api.services.androidpublisher.model.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

public class ElementiquePromoteBetaApkToProduction {

    private static final Log log = LogFactory.getLog(ElementiquePromoteBetaApkToProduction.class);

    private static final String PACKAGE_NAME = "com.elementique.home";

    public static final String TRACK_BETA = "beta";
    public static final String TRACK_PRODUCTION = "production";

    public static void main(String[] args) {
        try {
            // Create the API androidPublisher service.
            final AndroidPublisher androidPublisher = AndroidPublisherHelper.init("Elementique", null);
            final Edits edits = androidPublisher.edits();

            // Create a new edit to make changes.
            Edits.Insert insertEdit = edits.insert(PACKAGE_NAME, null);
            AppEdit insertAppEdit = insertEdit.execute();

            // search for 'beta' apk(s) in the 'beta' track..
            // first list all tracks..
            TracksListResponse trackListResponse = edits.tracks().list(PACKAGE_NAME, insertAppEdit.getId()).execute();
            for (Track track : trackListResponse.getTracks()) {
                // filter for beta track..
                if (TRACK_BETA.equals(track.getTrack())) {
                    // beta track found...
                    System.out.println("Beta Track found!\n" + track.toPrettyString());
                    // in my case, I am supposed to have exactly one 'beta' apk
                    List<Integer> betaApkVersionCodes = track.getVersionCodes();
                    if (betaApkVersionCodes.size() == 1) {
                        // one apk: OK, that's the 'beta' apk I want to promote to 'production'
                        Integer betaApkVersionCode = betaApkVersionCodes.get(0);

                        // now search for the given apk among all existing apks (is it the good way to proceed..??)
                        ApksListResponse apksListResponse = edits.apks().list(PACKAGE_NAME, insertAppEdit.getId()).execute();
                        for (Apk apk : apksListResponse.getApks()) {
                            // is it our 'beta' apk?
                            if (betaApkVersionCode.equals(apk.getVersionCode())) {
                                System.out.println("Beta apk found!\n" + apk.toPrettyString());
                                // OK, we got it.
                                // now trying to change the 'track' of this apk from 'beta' to 'production'
                                // and this is not the way to proceed...
                                List<Integer> apkVersionCodes = new ArrayList<>();
                                apkVersionCodes.add(apk.getVersionCode());
                                Edits.Tracks.Update updateTrackRequest =
                                        edits.tracks().update(
                                                PACKAGE_NAME,
                                                insertAppEdit.getId(),
                                                TRACK_PRODUCTION,
                                                new Track().setVersionCodes(apkVersionCodes));
                                Track updatedTrack = updateTrackRequest.execute();
                                log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

                                // Commit changes for edit.
                                Edits.Commit commitRequest = edits.commit(PACKAGE_NAME, insertAppEdit.getId());
                                AppEdit commitAppEdit = commitRequest.execute();
                                log.info(PACKAGE_NAME + " beta apk moved to production (" + commitAppEdit.getId());
                                System.exit(0);
                            }
                        }
                    }
                }
            }
        } catch (IOException | GeneralSecurityException ex) {
            log.error("Exception was thrown while updating listing", ex);
        }
    }
}

(Не говорите мне про круглые скобки, я просто написал этот код, чтобы сделать простой тест ;-)

Примечания:

  • Исходный проект Google Smaple: здесь и артефакт maven "Google Play Developer API V2" здесь
  • Дополнительная информация: javadoc здесь и некоторая дополнительная (не java) информация здесь

person Pascal    schedule 31.03.2018    source источник
comment
Думаю, я нашел правильную страницу документации, на которой объясняется, как это сделать, позвонив по телефону Edits.tracks: обновить дважды . Я попробую и обновлю свой вопрос / опубликую ответ на основе результатов этого эксперимента.   -  person Pascal    schedule 01.04.2018


Ответы (1)


Прикол :-)
Пояснения можно найти здесь: https://developers.google.com/android-publisher/tracks

Пример кода для программного продвижения бета-версии в рабочую версию:

package com.elementique.tools.publish.elementique;

import com.elementique.tools.publish.AndroidPublisherHelper;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisher.Edits;
import com.google.api.services.androidpublisher.model.AppEdit;
import com.google.api.services.androidpublisher.model.Track;
import com.google.api.services.androidpublisher.model.TracksListResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

// Google Play Developer API v2 javadoc:
// https://developers.google.com/resources/api-libraries/documentation/androidpublisher/v2/java/latest/index.html?com/google/api/services/androidpublisher/AndroidPublisher.html
// + this: https://developers.google.com/android-publisher/api-ref/

public class ElementiquePromoteBetaApkToProduction {

    private static final Log log = LogFactory.getLog(ElementiquePromoteBetaApkToProduction.class);

    private static final String PACKAGE_NAME = "com.elementique.home";

    public static final String TRACK_BETA = "beta";
    public static final String TRACK_PRODUCTION = "production";

    public static void main(String[] args) {
        try {
            final AndroidPublisher androidPublisher = AndroidPublisherHelper.init("Elementique", null);
            final Edits edits = androidPublisher.edits();

            // Create a new edit to make changes.
            Edits.Insert insertEdit = edits.insert(PACKAGE_NAME, null);
            AppEdit insertAppEdit = insertEdit.execute();

            // Promote beta to production: doc here:
            // https://developers.google.com/android-publisher/tracks

            TracksListResponse trackListResponse = edits.tracks().list(PACKAGE_NAME, insertAppEdit.getId()).execute();

            Track betaTrack = null;
            Track productionTrack = null;

            // list current tracks.
            // searching for exactly one beta and one production...
            for (Track track : trackListResponse.getTracks()) {
                if (TRACK_BETA.equals(track.getTrack())) {
                    if (track.getVersionCodes().size() == 1) {
                        // one version: OK, that's the 'beta' apk I want to promote to 'production'
                        betaTrack = track;
                        log.info(PACKAGE_NAME + ": found 'beta' apk " + betaTrack.getVersionCodes().get(0));
                    }
                } else if (TRACK_PRODUCTION.equals(track.getTrack())) {
                    if (track.getVersionCodes().size() == 1) {
                        // one version: OK, that's the 'production' apk I want to replace with the former 'beta' apk
                        productionTrack = track;
                        log.info(PACKAGE_NAME + ": found 'production' apk" + productionTrack.getVersionCodes().get(0));
                    }
                }
            }

            if (betaTrack != null && productionTrack != null) {
                // first set production track to version of current beta
                Edits.Tracks.Update updateProductionTrackRequest =
                        edits.tracks().update(
                                PACKAGE_NAME,
                                insertAppEdit.getId(),
                                TRACK_PRODUCTION,
                                new Track().setVersionCodes(betaTrack.getVersionCodes()));
                updateProductionTrackRequest.execute();

                // .. then clear beta version(no more beta apk)
                Edits.Tracks.Update updateBetaTrackRequest =
                        edits.tracks().update(
                                PACKAGE_NAME,
                                insertAppEdit.getId(),
                                TRACK_BETA,
                                new Track().setVersionCodes(new ArrayList<>()));
                updateBetaTrackRequest.execute();

                // Commit changes for edit
                Edits.Commit commitRequest = edits.commit(PACKAGE_NAME, insertAppEdit.getId());
                AppEdit commitAppEdit = commitRequest.execute();
                log.info(PACKAGE_NAME + ":" +
                        " 'production' apk " + productionTrack.getVersionCodes().get(0) + "" +
                        " replaced by 'beta' apk " + betaTrack.getVersionCodes().get(0));
            }
        } catch (IOException | GeneralSecurityException ex) {
            log.error(PACKAGE_NAME + " : Error while trying to promote 'beta' apk to 'production'", ex);
        }
    }
}
person Pascal    schedule 02.04.2018