diff --git a/src/main/java/android/net/Uri.kt b/src/main/java/android/net/Uri.kt index 9ab18a8..c8622da 100644 --- a/src/main/java/android/net/Uri.kt +++ b/src/main/java/android/net/Uri.kt @@ -1835,8 +1835,8 @@ abstract class Uri private constructor() : Parcelable, Comparable { /** Identifies a null parcelled Uri. */ private const val NULL_TYPE_ID = 0 - /** Reads Uris from Parcels. */ - @JvmStatic + /** Reads Uris from Parcels. A field rather than a getter, like Android, so that Parcel finds it reflectively. */ + @JvmField val CREATOR: Parcelable.Creator = object : Parcelable.Creator { override fun createFromParcel(`in`: Parcel): Uri? { diff --git a/src/main/java/android/os/Parcel.java b/src/main/java/android/os/Parcel.java new file mode 100644 index 0000000..4225b1b --- /dev/null +++ b/src/main/java/android/os/Parcel.java @@ -0,0 +1,769 @@ +package android.os; + +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.util.ArrayMap; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A container for the values a {@link Parcelable} flattens itself into, with the Android class's API for the members + * the ported Firebase libraries and their consumers use. The repackaged Firebase classes (Timestamp, RemoteMessage, + * Trace and others) expose {@code writeToParcel(Parcel, int)} and a {@code CREATOR}, so this class exists mainly so + * that code compiled against them can reference it. + *

+ * Nothing is transported between processes on the JVM, so there is no binary format to be compatible with: the parcel + * is an in-memory list of the values written to it, read back in the same order. {@link #dataPosition()}, + * {@link #setDataPosition} and {@link #dataSize()} therefore count values, not bytes, and {@link #marshall()} is a + * tagged byte stream of those values that only {@link #unmarshall} understands. A Serializable is kept as the bytes of + * its serialized form from the moment it is written, and only {@link #readSerializable()} deserializes it. Reading past + * the end or reading a value as another type throws an {@link IllegalStateException}. Instances are not pooled: + * {@link #obtain()} creates a fresh parcel and {@link #recycle()} empties it. + */ +public final class Parcel { + + private static final int VAL_NULL = -1; + private static final int VAL_STRING = 0; + private static final int VAL_INTEGER = 1; + private static final int VAL_MAP = 2; + private static final int VAL_BUNDLE = 3; + private static final int VAL_PARCELABLE = 4; + private static final int VAL_LONG = 6; + private static final int VAL_FLOAT = 7; + private static final int VAL_DOUBLE = 8; + private static final int VAL_BOOLEAN = 9; + private static final int VAL_LIST = 11; + private static final int VAL_BYTEARRAY = 13; + private static final int VAL_STRINGARRAY = 14; + private static final int VAL_BYTE = 20; + private static final int VAL_SERIALIZABLE = 21; + + // The tags of the marshalled stream, one for each type a value in the list can have once the typed writes have + // flattened lists, maps, bundles and parcelables into these. + private static final byte TAG_NULL = 0; + private static final byte TAG_STRING = 1; + private static final byte TAG_INT = 2; + private static final byte TAG_LONG = 3; + private static final byte TAG_FLOAT = 4; + private static final byte TAG_DOUBLE = 5; + private static final byte TAG_BYTES = 6; + private static final byte TAG_SERIALIZED = 7; + + private static final int EX_SECURITY = -1; + private static final int EX_ILLEGAL_ARGUMENT = -3; + private static final int EX_NULL_POINTER = -4; + private static final int EX_ILLEGAL_STATE = -5; + private static final int EX_UNSUPPORTED_OPERATION = -7; + + private final List values = new ArrayList<>(); + private int position; + + private Parcel() { + } + + /** A new, empty parcel. */ + @NonNull + public static Parcel obtain() { + return new Parcel(); + } + + /** Empties the parcel so that it can be written again. */ + public void recycle() { + values.clear(); + position = 0; + } + + /** The number of values written to the parcel. */ + public int dataSize() { + return values.size(); + } + + /** The number of values left to read from the current position. */ + public int dataAvail() { + return values.size() - position; + } + + /** The index of the next value to read or write. */ + public int dataPosition() { + return position; + } + + /** Moves to the value at {@code pos}, which is between 0 and {@link #dataSize()} inclusive. */ + public void setDataPosition(int pos) { + if (pos < 0 || pos > values.size()) { + throw new IllegalArgumentException("Position " + pos + " is outside the parcel of size " + values.size()); + } + position = pos; + } + + /** + * The values of the parcel as a tagged byte stream that {@link #unmarshall} reads back into a parcel: the number of + * values, then each as a tag byte and its data. Serializables stay the bytes of their serialized form. + * + * @throws IllegalStateException when a value is of a type the stream cannot carry, which the typed writes never store + */ + @NonNull + public byte[] marshall() { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream out = new DataOutputStream(bytes)) { + out.writeInt(values.size()); + for (Object value : values) { + if (value == null) { + out.writeByte(TAG_NULL); + } else if (value instanceof String) { + out.writeByte(TAG_STRING); + writeBytes(out, ((String) value).getBytes(StandardCharsets.UTF_8)); + } else if (value instanceof Integer) { + out.writeByte(TAG_INT); + out.writeInt((Integer) value); + } else if (value instanceof Long) { + out.writeByte(TAG_LONG); + out.writeLong((Long) value); + } else if (value instanceof Float) { + out.writeByte(TAG_FLOAT); + out.writeFloat((Float) value); + } else if (value instanceof Double) { + out.writeByte(TAG_DOUBLE); + out.writeDouble((Double) value); + } else if (value instanceof byte[]) { + out.writeByte(TAG_BYTES); + writeBytes(out, (byte[]) value); + } else if (value instanceof SerializedValue) { + out.writeByte(TAG_SERIALIZED); + writeBytes(out, ((SerializedValue) value).bytes); + } else { + throw new IllegalStateException("Parcel: cannot marshall a value of type " + value.getClass().getName()); + } + } + } catch (IOException e) { + throw new IllegalStateException("Unable to marshall the parcel", e); + } + return bytes.toByteArray(); + } + + /** + * Replaces the contents of the parcel with the values {@link #marshall()} produced, leaving the position at the end + * like Android does: call {@link #setDataPosition setDataPosition(0)} before reading them. Nothing is deserialized + * here: a Serializable in the data stays bytes until {@link #readSerializable()} asks for it. + * + * @throws IllegalArgumentException when the data is not a marshalled parcel + */ + public void unmarshall(@NonNull byte[] data, int offset, int length) { + List unmarshalled = new ArrayList<>(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data, offset, length))) { + int count = in.readInt(); + if (count < 0) { + throw new IOException("Negative value count " + count); + } + for (int i = 0; i < count; i++) { + byte tag = in.readByte(); + switch (tag) { + case TAG_NULL: + unmarshalled.add(null); + break; + case TAG_STRING: + unmarshalled.add(new String(readBytes(in), StandardCharsets.UTF_8)); + break; + case TAG_INT: + unmarshalled.add(in.readInt()); + break; + case TAG_LONG: + unmarshalled.add(in.readLong()); + break; + case TAG_FLOAT: + unmarshalled.add(in.readFloat()); + break; + case TAG_DOUBLE: + unmarshalled.add(in.readDouble()); + break; + case TAG_BYTES: + unmarshalled.add(readBytes(in)); + break; + case TAG_SERIALIZED: + unmarshalled.add(new SerializedValue(readBytes(in))); + break; + default: + throw new IOException("Unknown value tag " + tag); + } + } + if (in.read() != -1) { + throw new IOException("Data after the last value"); + } + } catch (IOException e) { + throw new IllegalArgumentException("The data is not a marshalled parcel", e); + } + values.clear(); + values.addAll(unmarshalled); + position = values.size(); + } + + private static void writeBytes(DataOutputStream out, byte[] bytes) throws IOException { + out.writeInt(bytes.length); + out.write(bytes); + } + + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length < 0 || length > in.available()) { + throw new IOException("Bad length " + length + " with " + in.available() + " bytes left"); + } + byte[] bytes = new byte[length]; + in.readFully(bytes); + return bytes; + } + + public void writeByte(byte val) { + writeInt(val); + } + + public void writeInt(int val) { + write(val); + } + + public void writeLong(long val) { + write(val); + } + + public void writeFloat(float val) { + write(val); + } + + public void writeDouble(double val) { + write(val); + } + + public void writeBoolean(boolean val) { + writeInt(val ? 1 : 0); + } + + public void writeString(@Nullable String val) { + write(val); + } + + /** The same as {@link #writeString}: there is no UTF-8 encoding to choose when nothing is encoded. */ + public void writeString8(@Nullable String val) { + write(val); + } + + /** Writes the array as a single value, or a null value for a null array. */ + public void writeByteArray(@Nullable byte[] b) { + write(b == null ? null : b.clone()); + } + + public void writeByteArray(@Nullable byte[] b, int offset, int len) { + if (b == null) { + write(null); + return; + } + byte[] copy = new byte[len]; + System.arraycopy(b, offset, copy, 0, len); + write(copy); + } + + /** Writes the size of the list, or -1 for a null list, followed by its strings. */ + public void writeStringList(@Nullable List val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (String s : val) { + writeString(s); + } + } + + /** Writes the size of the list, or -1 for a null list, followed by its elements with {@link #writeValue}. */ + public void writeList(@Nullable List val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (Object o : val) { + writeValue(o); + } + } + + /** Writes the size of the map, or -1 for a null map, followed by each key and value with {@link #writeValue}. */ + public void writeMap(@Nullable Map val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (Object entry : val.entrySet()) { + writeValue(((Map.Entry) entry).getKey()); + writeValue(((Map.Entry) entry).getValue()); + } + } + + /** Writes the size of the map, or -1 for a null map, followed by each key as a string and each value with {@link #writeValue}. */ + public void writeArrayMap(@Nullable ArrayMap val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (int i = 0; i < val.size(); i++) { + writeString(val.keyAt(i)); + writeValue(val.valueAt(i)); + } + } + + /** Writes the size of the bundle, or -1 for a null bundle, followed by each key as a string and each value with {@link #writeValue}. */ + public void writeBundle(@Nullable Bundle val) { + if (val == null) { + writeInt(-1); + return; + } + writeInt(val.size()); + for (String key : val.keySet()) { + writeString(key); + writeValue(val.get(key)); + } + } + + /** + * Writes the name of the Parcelable's class, or a null string for a null Parcelable, and then lets it write itself + * with {@link Parcelable#writeToParcel}. + */ + public void writeParcelable(@Nullable Parcelable p, int parcelableFlags) { + if (p == null) { + writeString(null); + return; + } + writeString(p.getClass().getName()); + p.writeToParcel(this, parcelableFlags); + } + + /** + * Writes a serialized snapshot of the object, so that changing it afterwards does not change the parcel and each + * {@link #readSerializable()} returns a fresh copy. + * + * @throws IllegalArgumentException when the object cannot be serialized + */ + public void writeSerializable(@Nullable Serializable s) { + write(s == null ? null : new SerializedValue(s)); + } + + /** + * Writes a value of one of the types the typed write methods take, with a tag for {@link #readValue} to know which, + * or a serialized snapshot of any other Serializable value. + * + * @throws IllegalArgumentException for a value of any other type + */ + public void writeValue(@Nullable Object v) { + if (v == null) { + writeInt(VAL_NULL); + } else if (v instanceof String) { + writeInt(VAL_STRING); + writeString((String) v); + } else if (v instanceof Integer) { + writeInt(VAL_INTEGER); + writeInt((Integer) v); + } else if (v instanceof Map) { + writeInt(VAL_MAP); + writeMap((Map) v); + } else if (v instanceof Bundle) { + writeInt(VAL_BUNDLE); + writeBundle((Bundle) v); + } else if (v instanceof Parcelable) { + writeInt(VAL_PARCELABLE); + writeParcelable((Parcelable) v, 0); + } else if (v instanceof Long) { + writeInt(VAL_LONG); + writeLong((Long) v); + } else if (v instanceof Float) { + writeInt(VAL_FLOAT); + writeFloat((Float) v); + } else if (v instanceof Double) { + writeInt(VAL_DOUBLE); + writeDouble((Double) v); + } else if (v instanceof Boolean) { + writeInt(VAL_BOOLEAN); + writeBoolean((Boolean) v); + } else if (v instanceof List) { + writeInt(VAL_LIST); + writeList((List) v); + } else if (v instanceof byte[]) { + writeInt(VAL_BYTEARRAY); + writeByteArray((byte[]) v); + } else if (v instanceof String[]) { + writeInt(VAL_STRINGARRAY); + writeStringList(Arrays.asList((String[]) v)); + } else if (v instanceof Byte) { + writeInt(VAL_BYTE); + writeByte((Byte) v); + } else if (v instanceof Serializable) { + writeInt(VAL_SERIALIZABLE); + writeSerializable((Serializable) v); + } else { + throw new IllegalArgumentException("Parcel: unable to marshal value " + v); + } + } + + /** + * Writes an exception for {@link #readException()} to rethrow: a code for the exception types Android transports + * (SecurityException, IllegalArgumentException, NullPointerException, IllegalStateException and + * UnsupportedOperationException) followed by the message. Any other exception is thrown here instead, like Android + * does, wrapped in a RuntimeException unless it is one. + */ + public void writeException(@NonNull Exception e) { + int code = exceptionCode(e); + if (code == 0) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + throw new RuntimeException(e); + } + writeInt(code); + writeString(e.getMessage()); + } + + /** Writes the code that tells {@link #readException()} that no exception occurred. */ + public void writeNoException() { + writeInt(0); + } + + /** Rethrows the exception {@link #writeException} wrote, if one was written at the current position. */ + public void readException() { + int code = readExceptionCode(); + if (code != 0) { + readException(code, readString()); + } + } + + /** The code of the exception written at the current position, or 0 when {@link #writeNoException()} was. */ + public int readExceptionCode() { + return readInt(); + } + + /** Throws the exception {@code code} stands for, with {@code msg}. */ + public void readException(int code, String msg) { + switch (code) { + case EX_SECURITY: + throw new SecurityException(msg); + case EX_ILLEGAL_ARGUMENT: + throw new IllegalArgumentException(msg); + case EX_NULL_POINTER: + throw new NullPointerException(msg); + case EX_ILLEGAL_STATE: + throw new IllegalStateException(msg); + case EX_UNSUPPORTED_OPERATION: + throw new UnsupportedOperationException(msg); + default: + throw new RuntimeException("Unknown exception code: " + code + " msg " + msg); + } + } + + public byte readByte() { + return (byte) readInt(); + } + + public int readInt() { + return read(Integer.class); + } + + public long readLong() { + return read(Long.class); + } + + public float readFloat() { + return read(Float.class); + } + + public double readDouble() { + return read(Double.class); + } + + public boolean readBoolean() { + return readInt() != 0; + } + + @Nullable + public String readString() { + return readNullable(String.class); + } + + /** The same as {@link #readString}, reading what either string method wrote. */ + @Nullable + public String readString8() { + return readNullable(String.class); + } + + @Nullable + public byte[] createByteArray() { + byte[] bytes = readNullable(byte[].class); + return bytes == null ? null : bytes.clone(); + } + + /** Reads an array of the same length as {@code val} into it. */ + public void readByteArray(@NonNull byte[] val) { + byte[] bytes = createByteArray(); + if (bytes == null || bytes.length != val.length) { + throw new IllegalStateException("bad array lengths"); + } + System.arraycopy(bytes, 0, val, 0, val.length); + } + + @Nullable + public ArrayList createStringArrayList() { + int n = readInt(); + if (n < 0) { + return null; + } + ArrayList list = new ArrayList<>(n); + for (int i = 0; i < n; i++) { + list.add(readString()); + } + return list; + } + + /** Replaces the contents of {@code list} with the strings {@link #writeStringList} wrote. */ + public void readStringList(@NonNull List list) { + list.clear(); + int n = readInt(); + for (int i = 0; i < n; i++) { + list.add(readString()); + } + } + + @Nullable + public ArrayList readArrayList(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + ArrayList list = new ArrayList<>(n); + readValues(n, list, loader); + return list; + } + + /** Adds the elements {@link #writeList} wrote to {@code outVal}. */ + @SuppressWarnings("unchecked") + public void readList(@NonNull List outVal, @Nullable ClassLoader loader) { + readValues(readInt(), outVal, loader); + } + + @Nullable + public HashMap readHashMap(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + HashMap map = new HashMap<>(n); + readEntries(n, map, loader); + return map; + } + + /** Adds the entries {@link #writeMap} wrote to {@code outVal}. */ + @SuppressWarnings("unchecked") + public void readMap(@NonNull Map outVal, @Nullable ClassLoader loader) { + readEntries(readInt(), outVal, loader); + } + + /** Adds the entries {@link #writeArrayMap} wrote to {@code outVal}. */ + public void readArrayMap(@NonNull ArrayMap outVal, @Nullable ClassLoader loader) { + int n = readInt(); + for (int i = 0; i < n; i++) { + outVal.put(readString(), readValue(loader)); + } + } + + @Nullable + public Bundle readBundle() { + return readBundle(null); + } + + @Nullable + public Bundle readBundle(@Nullable ClassLoader loader) { + int n = readInt(); + if (n < 0) { + return null; + } + Map map = new LinkedHashMap<>(); + for (int i = 0; i < n; i++) { + map.put(readString(), readValue(loader)); + } + return new Bundle(map); + } + + /** + * Creates the Parcelable {@link #writeParcelable} wrote with the {@code CREATOR} of its class, which is loaded + * through {@code loader} when one is given. + * + * @throws IllegalStateException when the class or its CREATOR cannot be found + */ + @Nullable + @SuppressWarnings("unchecked") + public T readParcelable(@Nullable ClassLoader loader) { + String name = readString(); + if (name == null) { + return null; + } + Parcelable.Creator creator; + try { + Class type = loader == null ? Class.forName(name) : Class.forName(name, true, loader); + creator = (Parcelable.Creator) type.getField("CREATOR").get(null); + } catch (ReflectiveOperationException | ClassCastException e) { + throw new IllegalStateException("Parcelable " + name + " has no public static CREATOR", e); + } + if (creator instanceof Parcelable.ClassLoaderCreator) { + return (T) ((Parcelable.ClassLoaderCreator) creator).createFromParcel(this, loader); + } + return (T) creator.createFromParcel(this); + } + + /** + * Deserializes a fresh copy of the object {@link #writeSerializable} wrote. This is the only place the parcel + * deserializes anything: {@link #unmarshall} keeps serialized objects as bytes until a caller asks for them here. + * + * @throws IllegalStateException when the bytes cannot be deserialized + */ + @Nullable + public Serializable readSerializable() { + SerializedValue value = readNullable(SerializedValue.class); + return value == null ? null : value.read(); + } + + /** Reads a value {@link #writeValue} wrote, creating a Parcelable through {@code loader} when one is given. */ + @Nullable + public Object readValue(@Nullable ClassLoader loader) { + int type = readInt(); + switch (type) { + case VAL_NULL: + return null; + case VAL_STRING: + return readString(); + case VAL_INTEGER: + return readInt(); + case VAL_MAP: + return readHashMap(loader); + case VAL_BUNDLE: + return readBundle(loader); + case VAL_PARCELABLE: + return readParcelable(loader); + case VAL_LONG: + return readLong(); + case VAL_FLOAT: + return readFloat(); + case VAL_DOUBLE: + return readDouble(); + case VAL_BOOLEAN: + return readBoolean(); + case VAL_LIST: + return readArrayList(loader); + case VAL_BYTEARRAY: + return createByteArray(); + case VAL_STRINGARRAY: + ArrayList strings = createStringArrayList(); + return strings == null ? null : strings.toArray(new String[0]); + case VAL_BYTE: + return readByte(); + case VAL_SERIALIZABLE: + return readSerializable(); + default: + throw new IllegalStateException("Parcel: unknown type code " + type + " at position " + (position - 1)); + } + } + + private void write(@Nullable Object value) { + if (position == values.size()) { + values.add(value); + } else { + values.set(position, value); + } + position++; + } + + @NonNull + private T read(Class type) { + T value = readNullable(type); + if (value == null) { + throw new IllegalStateException("Parcel: expected a " + type.getSimpleName() + " at position " + (position - 1) + " but read null"); + } + return value; + } + + @Nullable + private T readNullable(Class type) { + if (position >= values.size()) { + throw new IllegalStateException("Parcel: no value left to read at position " + position); + } + Object value = values.get(position); + if (value != null && !type.isInstance(value)) { + throw new IllegalStateException("Parcel: expected a " + type.getSimpleName() + " at position " + position + " but found a " + value.getClass().getSimpleName()); + } + position++; + return type.cast(value); + } + + private void readValues(int n, List outVal, @Nullable ClassLoader loader) { + for (int i = 0; i < n; i++) { + outVal.add(readValue(loader)); + } + } + + private void readEntries(int n, Map outVal, @Nullable ClassLoader loader) { + for (int i = 0; i < n; i++) { + outVal.put(readValue(loader), readValue(loader)); + } + } + + /** The bytes of a Serializable's serialized form, taken when it is written and deserialized afresh on every read. */ + private static final class SerializedValue { + + final byte[] bytes; + + SerializedValue(Serializable value) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { + out.writeObject(value); + } catch (IOException e) { + throw new IllegalArgumentException("Parcel: unable to marshal value " + value, e); + } + this.bytes = bytes.toByteArray(); + } + + SerializedValue(byte[] bytes) { + this.bytes = bytes; + } + + Serializable read() { + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { + return (Serializable) in.readObject(); + } catch (IOException | ClassNotFoundException | ClassCastException e) { + throw new IllegalStateException("Parcel: unable to read the serialized value", e); + } + } + } + + private static int exceptionCode(Exception e) { + if (e instanceof SecurityException) { + return EX_SECURITY; + } else if (e instanceof IllegalArgumentException) { + return EX_ILLEGAL_ARGUMENT; + } else if (e instanceof NullPointerException) { + return EX_NULL_POINTER; + } else if (e instanceof IllegalStateException) { + return EX_ILLEGAL_STATE; + } else if (e instanceof UnsupportedOperationException) { + return EX_UNSUPPORTED_OPERATION; + } + return 0; + } +} diff --git a/src/main/java/com/google/firebase/auth/Auth.kt b/src/main/java/com/google/firebase/auth/Auth.kt new file mode 100644 index 0000000..c70e9f1 --- /dev/null +++ b/src/main/java/com/google/firebase/auth/Auth.kt @@ -0,0 +1,43 @@ +/* + * The Kotlin extensions the Android SDK's firebase-auth ships as com.google.firebase.auth.AuthKt, so that code written + * against them compiles against this SDK like it does against the other ported libraries' facades (FirestoreKt, + * DatabaseKt and the rest, which come with their jars). + */ +package com.google.firebase.auth + +import com.google.firebase.Firebase +import com.google.firebase.FirebaseApp + +/** Returns the [FirebaseAuth] instance of the default [FirebaseApp]. */ +val Firebase.auth: FirebaseAuth + get() = FirebaseAuth.getInstance() + +/** Returns the [FirebaseAuth] instance of a given [FirebaseApp]. */ +fun Firebase.auth(app: FirebaseApp): FirebaseAuth = FirebaseAuth.getInstance(app) + +/** Returns a [ActionCodeSettings] instance initialized using the [init] function. */ +fun actionCodeSettings(init: ActionCodeSettings.Builder.() -> Unit): ActionCodeSettings = + ActionCodeSettings.newBuilder().apply(init).build() + +/** Returns a [OAuthProvider] instance initialized using the [init] function. */ +fun oAuthProvider( + providerId: String, + init: OAuthProvider.Builder.() -> Unit +): OAuthProvider = OAuthProvider.newBuilder(providerId).apply(init).build() + +/** Returns a [OAuthProvider] instance initialized using the [init] function. */ +fun oAuthProvider( + providerId: String, + firebaseAuth: FirebaseAuth, + init: OAuthProvider.Builder.() -> Unit +): OAuthProvider = OAuthProvider.newBuilder(providerId, firebaseAuth).apply(init).build() + +/** Returns a [AuthCredential] instance initialized using the [init] function. */ +fun oAuthCredential( + providerId: String, + init: OAuthProvider.CredentialBuilder.() -> Unit +): AuthCredential = OAuthProvider.newCredentialBuilder(providerId).apply(init).build() + +/** Returns a [UserProfileChangeRequest] instance initialized using the [init] function. */ +fun userProfileChangeRequest(init: UserProfileChangeRequest.Builder.() -> Unit): UserProfileChangeRequest = + UserProfileChangeRequest.Builder().apply(init).build() diff --git a/src/test/kotlin/FirebaseAuthKtTest.kt b/src/test/kotlin/FirebaseAuthKtTest.kt new file mode 100644 index 0000000..e36403c --- /dev/null +++ b/src/test/kotlin/FirebaseAuthKtTest.kt @@ -0,0 +1,61 @@ +/* + * Exercises the AuthKt facade, the Kotlin extensions the Android SDK's firebase-auth ships, against the builders and + * instances they stand for. None of it needs a server. + */ +import android.net.Uri +import com.google.firebase.Firebase +import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.auth.OAuthCredential +import com.google.firebase.auth.actionCodeSettings +import com.google.firebase.auth.auth +import com.google.firebase.auth.oAuthCredential +import com.google.firebase.auth.oAuthProvider +import com.google.firebase.auth.userProfileChangeRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class FirebaseAuthKtTest : FirebaseTest() { + + @Test + fun `auth extensions return the FirebaseAuth of the app`() { + assertSame(FirebaseAuth.getInstance(app), Firebase.auth(app)) + assertSame(FirebaseAuth.getInstance(), Firebase.auth) + } + + @Test + fun `builder functions apply their init to a new builder`() { + val auth = Firebase.auth(app) + + val settings = actionCodeSettings { + setUrl("https://example.com/finish") + setHandleCodeInApp(true) + } + assertEquals("https://example.com/finish", settings.url) + + val provider = oAuthProvider("apple.com") { setScopes(listOf("email")) } + assertEquals("apple.com", provider.providerId) + assertEquals(listOf("email"), provider.scopes) + + val providerWithAuth = oAuthProvider("github.com", auth) { addCustomParameter("locale", "fr") } + assertEquals("github.com", providerWithAuth.providerId) + assertEquals(mapOf("locale" to "fr"), providerWithAuth.customParameters) + + val credential = oAuthCredential("apple.com") { + setIdToken("id") + setAccessToken("access") + } + assertTrue(credential is OAuthCredential) + assertEquals("apple.com", credential.provider) + assertEquals("id", (credential as OAuthCredential).idToken) + assertEquals("access", credential.accessToken) + + val request = userProfileChangeRequest { + setDisplayName("Name") + setPhotoUri(Uri.parse("https://example.com/photo.png")) + } + assertEquals("Name", request.displayName) + assertEquals(Uri.parse("https://example.com/photo.png"), request.photoUri) + } +} diff --git a/src/test/kotlin/ParcelTest.kt b/src/test/kotlin/ParcelTest.kt new file mode 100644 index 0000000..145f84b --- /dev/null +++ b/src/test/kotlin/ParcelTest.kt @@ -0,0 +1,196 @@ +/* + * Tests the android.os.Parcel shim: the repackaged Firebase classes expose writeToParcel(Parcel, int) and a CREATOR, + * and this checks that values written to a parcel read back the way they do on Android. + */ +import android.net.Uri +import android.os.Bundle +import android.os.Parcel +import android.os.Parcelable +import android.util.ArrayMap +import com.google.firebase.Timestamp +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +class ParcelTest { + + @Test + fun `reads back primitives and strings in order`() { + val parcel = Parcel.obtain() + parcel.writeInt(42) + parcel.writeLong(1L shl 40) + parcel.writeDouble(42.5) + parcel.writeFloat(1.5f) + parcel.writeBoolean(true) + parcel.writeByte(7) + parcel.writeString("value") + parcel.writeString(null) + parcel.writeByteArray(byteArrayOf(1, 2, 3)) + parcel.writeByteArray(null) + assertEquals(10, parcel.dataSize()) + assertEquals(10, parcel.dataPosition()) + + parcel.setDataPosition(0) + assertEquals(42, parcel.readInt()) + assertEquals(1L shl 40, parcel.readLong()) + assertEquals(42.5, parcel.readDouble(), 0.0) + assertEquals(1.5f, parcel.readFloat(), 0.0f) + assertTrue(parcel.readBoolean()) + assertEquals(7.toByte(), parcel.readByte()) + assertEquals("value", parcel.readString()) + assertNull(parcel.readString()) + assertArrayEquals(byteArrayOf(1, 2, 3), parcel.createByteArray()) + assertNull(parcel.createByteArray()) + assertEquals(0, parcel.dataAvail()) + parcel.recycle() + assertEquals(0, parcel.dataSize()) + } + + @Test + fun `round trips a Firebase Parcelable through its CREATOR`() { + val parcel = Parcel.obtain() + parcel.writeParcelable(Timestamp(1_700_000_000L, 123_000), 0) + parcel.writeParcelable(null, 0) + parcel.setDataPosition(0) + + assertEquals(Timestamp(1_700_000_000L, 123_000), parcel.readParcelable(Timestamp::class.java.classLoader)) + assertNull(parcel.readParcelable(null)) + } + + @Test + fun `round trips a Uri through its CREATOR`() { + val hierarchical = Uri.parse("https://example.com/path/to?q=1&r=two#fragment") + val opaque = Uri.parse("mailto:someone@example.com") + val parcel = Parcel.obtain() + parcel.writeParcelable(hierarchical, 0) + parcel.writeValue(opaque) + parcel.setDataPosition(0) + + assertEquals(hierarchical, parcel.readParcelable(null)) + assertEquals(opaque, parcel.readValue(Uri::class.java.classLoader)) + } + + @Test + fun `serializables are snapshots, read as fresh copies`() { + val builder = StringBuilder("one") + val numbers = intArrayOf(1, 2) + val parcel = Parcel.obtain() + parcel.writeSerializable(builder) + parcel.writeValue(numbers) // falls back to the Serializable path + parcel.writeSerializable(null) + builder.append(" two") + numbers[0] = 99 + + parcel.setDataPosition(0) + val first = parcel.readSerializable() + assertEquals("one", first.toString()) + val read = parcel.readValue(null) as IntArray + assertArrayEquals(intArrayOf(1, 2), read) + assertNull(parcel.readSerializable()) + read[1] = 42 + parcel.setDataPosition(0) + val second = parcel.readSerializable() + assertEquals("one", second.toString()) + assertNotSame(first, second) + assertArrayEquals(intArrayOf(1, 2), parcel.readValue(null) as IntArray) + } + + @Test + fun `round trips collections, bundles and tagged values`() { + val parcel = Parcel.obtain() + parcel.writeStringList(listOf("a", "b")) + parcel.writeStringList(null) + parcel.writeList(listOf(1, "two", 3L, null)) + parcel.writeMap(mapOf("int" to 1, "list" to listOf(true))) + parcel.writeBundle(Bundle().apply { putString("key", "value"); putInt("int", 2) }) + parcel.writeBundle(null) + parcel.writeArrayMap(ArrayMap().apply { put("k", 1.5) }) + parcel.writeValue(Timestamp(1L, 2)) + parcel.writeValue(arrayOf("x", "y")) + parcel.writeValue(java.util.Date(5L)) + parcel.setDataPosition(0) + + assertEquals(listOf("a", "b"), parcel.createStringArrayList()) + assertNull(parcel.createStringArrayList()) + assertEquals(listOf(1, "two", 3L, null), parcel.readArrayList(null)) + assertEquals(mapOf("int" to 1, "list" to listOf(true)), parcel.readHashMap(null)) + val bundle = parcel.readBundle()!! + assertEquals("value", bundle.getString("key")) + assertEquals(2, bundle.getInt("int")) + assertNull(parcel.readBundle()) + val arrayMap = ArrayMap() + parcel.readArrayMap(arrayMap, null) + assertEquals(1.5, arrayMap["k"]) + assertEquals(Timestamp(1L, 2), parcel.readValue(null)) + assertArrayEquals(arrayOf("x", "y"), parcel.readValue(null) as Array<*>) + assertEquals(java.util.Date(5L), parcel.readValue(null)) + assertEquals(0, parcel.dataAvail()) + } + + @Test + fun `marshalls and unmarshalls`() { + val parcel = Parcel.obtain() + parcel.writeInt(1) + parcel.writeString("one") + parcel.writeParcelable(Timestamp(3L, 4), 0) + parcel.writeString(null) + parcel.writeLong(1L shl 40) + parcel.writeFloat(1.5f) + parcel.writeDouble(2.5) + parcel.writeByteArray(byteArrayOf(9, 8)) + parcel.writeValue(java.util.Date(5L)) + val bytes = parcel.marshall() + + val copy = Parcel.obtain() + copy.unmarshall(bytes, 0, bytes.size) + assertEquals(copy.dataSize(), copy.dataPosition()) + copy.setDataPosition(0) + assertEquals(1, copy.readInt()) + assertEquals("one", copy.readString()) + assertEquals(Timestamp(3L, 4), copy.readParcelable(null)) + assertNull(copy.readString()) + assertEquals(1L shl 40, copy.readLong()) + assertEquals(1.5f, copy.readFloat(), 0.0f) + assertEquals(2.5, copy.readDouble(), 0.0) + assertArrayEquals(byteArrayOf(9, 8), copy.createByteArray()) + assertEquals(java.util.Date(5L), copy.readValue(null)) + assertEquals(0, copy.dataAvail()) + + assertThrows(IllegalArgumentException::class.java) { Parcel.obtain().unmarshall(byteArrayOf(0, 0, 0, 1, 42), 0, 5) } + assertThrows(IllegalArgumentException::class.java) { Parcel.obtain().unmarshall(bytes, 0, bytes.size - 1) } + } + + @Test + fun `transports exceptions`() { + val parcel = Parcel.obtain() + parcel.writeNoException() + parcel.writeException(IllegalArgumentException("bad")) + parcel.setDataPosition(0) + + parcel.readException() + val e = assertThrows(IllegalArgumentException::class.java) { parcel.readException() } + assertEquals("bad", e.message) + assertThrows(RuntimeException::class.java) { parcel.writeException(java.io.IOException("not transported")) } + } + + @Test + fun `fails clearly on misuse`() { + val parcel = Parcel.obtain() + parcel.writeString("text") + assertThrows(IllegalStateException::class.java) { parcel.readInt() } + parcel.setDataPosition(0) + assertThrows(IllegalStateException::class.java) { parcel.readInt() } + assertThrows(IllegalArgumentException::class.java) { parcel.setDataPosition(2) } + parcel.setDataPosition(0) + parcel.writeInt(5) // overwrites the string, like writing at a position does on Android + assertEquals(1, parcel.dataSize()) + parcel.setDataPosition(0) + assertEquals(5, parcel.readInt()) + assertFalse(parcel.dataAvail() > 0) + } +}