<commit_before>/*
 *  Copyright 2017 Google Inc. All Rights Reserved.
 *
 *  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.
 */

package com.google.android.apps.forscience.whistlepunk.filemetadata;

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.google.android.apps.forscience.whistlepunk.AppSingleton;
import com.google.android.apps.forscience.whistlepunk.Clock;
import com.google.android.apps.forscience.whistlepunk.ColorAllocator;
import com.google.android.apps.forscience.whistlepunk.PermissionUtils;
import com.google.android.apps.forscience.whistlepunk.R;
import com.google.android.apps.forscience.whistlepunk.WhistlePunkApplication;
import com.google.android.apps.forscience.whistlepunk.accounts.AppAccount;
import com.google.android.apps.forscience.whistlepunk.data.nano.GoosciDeviceSpec;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.GoosciExperiment;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.GoosciScalarSensorData;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.GoosciUserMetadata;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.Version;
import com.google.android.apps.forscience.whistlepunk.sensorapi.ScalarSensorDumpReader;
import io.reactivex.Single;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

/** MetadataManager backed by a file-based system using internal storage. */
// TODO: Extend MetadataManager
public class FileMetadataManager {
  public static final String COVER_IMAGE_FILE = "assets/ExperimentCoverImage.jpg";
  static final String ASSETS_DIRECTORY = "assets";
  public static final String EXPERIMENTS_DIRECTORY = "experiments";
  public static final String EXPERIMENT_FILE = "experiment.proto";
  public static final String EXPERIMENT_LIBRARY_FILE = "experiment_library.proto";
  public static final String SYNC_STATUS_FILE = "sync_status.proto";
  private static final String TAG = "FileMetadataManager";
  private static final String USER_METADATA_FILE = "user_metadata.proto";
  public static final String DOT_PROTO = ".proto";

  private AppAccount appAccount;
  private Clock clock;

  private ExperimentCache activeExperimentCache;
  private UserMetadataManager userMetadataManager;
  private final LocalSyncManager localSyncManager;
  private final ExperimentLibraryManager experimentLibraryManager;
  private ColorAllocator colorAllocator;

  public FileMetadataManager(Context applicationContext, AppAccount appAccount, Clock clock) {
    this(
        applicationContext,
        appAccount,
        clock,
        AppSingleton.getInstance(applicationContext).getExperimentLibraryManager(appAccount),
        AppSingleton.getInstance(applicationContext).getLocalSyncManager(appAccount));
  }

  public FileMetadataManager(
      Context applicationContext,
      AppAccount appAccount,
      Clock clock,
      ExperimentLibraryManager elm,
      LocalSyncManager lsm) {
    this.appAccount = appAccount;
    this.clock = clock;
    // TODO: Probably pass failure listeners from a higher level in order to propagate them
    // up to the user. b/62373187.
    ExperimentCache.FailureListener failureListener =
        new ExperimentCache.FailureListener() {
          @Override
          public void onWriteFailed(Experiment experimentToWrite) {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "write failed");
          }

          @Override
          public void onReadFailed(GoosciUserMetadata.ExperimentOverview experimentOverview) {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "read failed");
          }

          @Override
          public void onNewerVersionDetected(
              GoosciUserMetadata.ExperimentOverview experimentOverview) {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "newer proto version detected than we can handle");
          }
        };
    UserMetadataManager.FailureListener userMetadataListener =
        new UserMetadataManager.FailureListener() {

          @Override
          public void onWriteFailed() {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "write failed");
          }

          @Override
          public void onReadFailed() {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "read failed");
          }

          @Override
          public void onNewerVersionDetected() {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "newer proto version detected than we can handle");
          }
        };
    activeExperimentCache = new ExperimentCache(applicationContext, appAccount, failureListener);
    userMetadataManager =
        new UserMetadataManager(applicationContext, appAccount, userMetadataListener);
    localSyncManager = lsm;
    experimentLibraryManager = elm;
    colorAllocator =
        new ColorAllocator(
            applicationContext.getResources().getIntArray(R.array.experiment_colors_array).length);
  }

  /**
   * Deletes all experiments in the list of experiment IDs. This really deletes everything and
   * should be used very sparingly!
   */
  public void deleteAll(List<String> experimentIds) {
    for (String experimentId : experimentIds) {
      deleteExperiment(experimentId);
    }
  }

  public Experiment getExperimentById(String experimentId) {
    GoosciUserMetadata.ExperimentOverview overview =
        userMetadataManager.getExperimentOverview(experimentId);
    if (overview == null) {
      return null;
    }
    return activeExperimentCache.getExperiment(overview);
  }

  public Experiment newExperiment() {
    long timestamp = clock.getNow();
    String localExperimentId = UUID.randomUUID().toString();
    List<GoosciUserMetadata.ExperimentOverview> overviews =
        userMetadataManager.getExperimentOverviews(true);
    int[] usedColors = new int[overviews.size()];
    for (int i = 0; i < overviews.size(); i++) {
      usedColors[i] = overviews.get(i).colorIndex;
    }
    int colorIndex = colorAllocator.getNextColor(usedColors);
    Experiment experiment = Experiment.newExperiment(timestamp, localExperimentId, colorIndex);
    localSyncManager.addExperiment(experiment.getExperimentId());
    experimentLibraryManager.addExperiment(experiment.getExperimentId());
    addExperiment(experiment);
    return experiment;<commit_msg>Another attempt to fix a null pointer on library upgrade from C.<commit_after>/*
 *  Copyright 2017 Google Inc. All Rights Reserved.
 *
 *  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.
 */

package com.google.android.apps.forscience.whistlepunk.filemetadata;

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.google.android.apps.forscience.whistlepunk.AppSingleton;
import com.google.android.apps.forscience.whistlepunk.Clock;
import com.google.android.apps.forscience.whistlepunk.ColorAllocator;
import com.google.android.apps.forscience.whistlepunk.PermissionUtils;
import com.google.android.apps.forscience.whistlepunk.R;
import com.google.android.apps.forscience.whistlepunk.WhistlePunkApplication;
import com.google.android.apps.forscience.whistlepunk.accounts.AppAccount;
import com.google.android.apps.forscience.whistlepunk.data.nano.GoosciDeviceSpec;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.GoosciExperiment;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.GoosciScalarSensorData;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.GoosciUserMetadata;
import com.google.android.apps.forscience.whistlepunk.metadata.nano.Version;
import com.google.android.apps.forscience.whistlepunk.sensorapi.ScalarSensorDumpReader;
import io.reactivex.Single;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;

/** MetadataManager backed by a file-based system using internal storage. */
// TODO: Extend MetadataManager
public class FileMetadataManager {
  public static final String COVER_IMAGE_FILE = "assets/ExperimentCoverImage.jpg";
  static final String ASSETS_DIRECTORY = "assets";
  public static final String EXPERIMENTS_DIRECTORY = "experiments";
  public static final String EXPERIMENT_FILE = "experiment.proto";
  public static final String EXPERIMENT_LIBRARY_FILE = "experiment_library.proto";
  public static final String SYNC_STATUS_FILE = "sync_status.proto";
  private static final String TAG = "FileMetadataManager";
  private static final String USER_METADATA_FILE = "user_metadata.proto";
  public static final String DOT_PROTO = ".proto";

  private AppAccount appAccount;
  private Clock clock;

  private ExperimentCache activeExperimentCache;
  private UserMetadataManager userMetadataManager;
  private final LocalSyncManager localSyncManager;
  private final ExperimentLibraryManager experimentLibraryManager;
  private ColorAllocator colorAllocator;

  public FileMetadataManager(Context applicationContext, AppAccount appAccount, Clock clock) {
    this(
        applicationContext,
        appAccount,
        clock,
        AppSingleton.getInstance(applicationContext).getExperimentLibraryManager(appAccount),
        AppSingleton.getInstance(applicationContext).getLocalSyncManager(appAccount));
  }

  public FileMetadataManager(
      Context applicationContext,
      AppAccount appAccount,
      Clock clock,
      ExperimentLibraryManager elm,
      LocalSyncManager lsm) {
    this.appAccount = appAccount;
    this.clock = clock;
    // TODO: Probably pass failure listeners from a higher level in order to propagate them
    // up to the user. b/62373187.
    ExperimentCache.FailureListener failureListener =
        new ExperimentCache.FailureListener() {
          @Override
          public void onWriteFailed(Experiment experimentToWrite) {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "write failed");
          }

          @Override
          public void onReadFailed(GoosciUserMetadata.ExperimentOverview experimentOverview) {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "read failed");
          }

          @Override
          public void onNewerVersionDetected(
              GoosciUserMetadata.ExperimentOverview experimentOverview) {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "newer proto version detected than we can handle");
          }
        };
    UserMetadataManager.FailureListener userMetadataListener =
        new UserMetadataManager.FailureListener() {

          @Override
          public void onWriteFailed() {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "write failed");
          }

          @Override
          public void onReadFailed() {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "read failed");
          }

          @Override
          public void onNewerVersionDetected() {
            // TODO: Propagate this up to the user somehow.
            Log.d(TAG, "newer proto version detected than we can handle");
          }
        };
    activeExperimentCache = new ExperimentCache(applicationContext, appAccount, failureListener);
    userMetadataManager =
        new UserMetadataManager(applicationContext, appAccount, userMetadataListener);
    localSyncManager = lsm;
    experimentLibraryManager = elm;
    colorAllocator =
        new ColorAllocator(
            applicationContext.getResources().getIntArray(R.array.experiment_colors_array).length);
  }

  /**
   * Deletes all experiments in the list of experiment IDs. This really deletes everything and
   * should be used very sparingly!
   */
  public void deleteAll(List<String> experimentIds) {
    for (String experimentId : experimentIds) {
      // This if block prevents null pointer exceptions in the upgrade flow.
      if (experimentLibraryManager.getExperiment(experimentId) == null) {
        experimentLibraryManager.addExperiment(experimentId);
        localSyncManager.addExperiment(experimentId);
      }
      deleteExperiment(experimentId);
    }
  }

  public Experiment getExperimentById(String experimentId) {
    GoosciUserMetadata.ExperimentOverview overview =
        userMetadataManager.getExperimentOverview(experimentId);
    if (overview == null) {
      return null;
    }
    return activeExperimentCache.getExperiment(overview);
  }

  public Experiment newExperiment() {
    long timestamp = clock.getNow();
    String localExperimentId = UUID.randomUUID().toString();
    List<GoosciUserMetadata.ExperimentOverview> overviews =
        userMetadataManager.getExperimentOverviews(true);
    int[] usedColors = new int[overviews.size()];
    for (int i = 0; i < overviews.size(); i++) {
      usedColors[i] = overviews.get(i).colorIndex;
    }
    int colorIndex = colorAllocator.getNextColor(usedColors);
    Experiment experiment = Experiment.newExperiment(timestamp, localExperimentId, colorIndex);
    localSyncManager.addExperiment(experiment.getExperimentId());
    experimentLibraryManager.addExperiment(experiment.getExperimentId());
    addExperiment(experiment);
    return experiment;
{'fraction_non_alphanumeric': 0.0801765105227427, 'fraction_numerical': 0.002308214528173795, 'mean_word_length': 3.6899076727156954, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4746589', 'n_tokens_mistral': 4078, 'n_tokens_neox': 3902, 'n_words': 1012}