index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/asynchronous/RevAiJob.java
package ai.rev.speechtotext.models.asynchronous; import java.util.List; import com.google.gson.annotations.SerializedName; /** A RevAi Job object provides all the information associated with a job submitted by the user. */ public class RevAiJob { @SerializedName("id") private String jobId; @SerializedName("status") private RevAiJobStatus jobStatus; @SerializedName("created_on") private String createdOn; @SerializedName("completed_on") private String completedOn; @SerializedName("callback_url") private String callbackUrl; @SerializedName("duration_seconds") private Double durationSeconds; @SerializedName("media_url") private String mediaUrl; @SerializedName("metadata") private String metadata; @SerializedName("name") private String name; @SerializedName("type") private RevAiJobType type; @SerializedName("failure_details") private String failureDetails; @SerializedName("failure") private RevAiFailureType failure; @SerializedName("delete_after_seconds") private Integer deleteAfterSeconds; @SerializedName("skip_diarization") private Boolean skipDiarization; @SerializedName("skip_punctuation") private Boolean skipPunctuation; @SerializedName("remove_disfluencies") private Boolean removeDisfluencies; @SerializedName("filter_profanity") private Boolean filterProfanity; @SerializedName("custom_vocabulary_id") private String customVocabularyId; @SerializedName("speaker_channels_count") private Integer speakerChannelsCount; @SerializedName("language") private String language; @SerializedName("transcriber") private String transcriber; @SerializedName("verbatim") private Boolean verbatim; @SerializedName("rush") private Boolean rush; @SerializedName("segments_to_transcribe") private List<SegmentToTranscribe> segmentsToTranscribe; /** * Returns a String that contains the job ID. * * @return A String that contains the job ID. */ public String getJobId() { return jobId; } /** * Sets the Job ID. * * @param jobId The String value to set as the job ID. */ public void setJobId(String jobId) { this.jobId = jobId; } /** * Returns the {@link RevAiJobStatus} enumeration value. * * @return The {@link RevAiJobStatus} enumeration value. * @see RevAiJobStatus */ public RevAiJobStatus getJobStatus() { return jobStatus; } /** * Sets the job status to the provided {@link RevAiJobStatus} enumeration value. * * @param jobStatus The enumeration value to set as the job status. * @see RevAiJobStatus */ public void setJobStatus(RevAiJobStatus jobStatus) { this.jobStatus = jobStatus; } /** * Returns a String that contains the date and time the job was created on in ISO-8601 UTC form. * * @return A String that contains the date and time the job was created on in ISO-8601 UTC form. */ public String getCreatedOn() { return createdOn; } /** * Sets the time and date the job was created on. * * @param createdOn The String value to set as the created on date and time. */ public void setCreatedOn(String createdOn) { this.createdOn = createdOn; } /** * Returns a String that contains the date and time the job was completed on in ISO-8601 UTC form. * * @return A String that contains the date and time the job was completed on in ISO-8601 UTC form. */ public String getCompletedOn() { return completedOn; } /** * Set the date and time the job was completed on. * * @param completedOn The String value to set as the date and time the job was completed on. */ public void setCompletedOn(String completedOn) { this.completedOn = completedOn; } /** * Returns the callback url provided in the submission request. * * @return A String containing the callback url provided in the submission request. */ public String getCallbackUrl() { return callbackUrl; } /** * Sets the callback url. * * @param callbackUrl A String value to set as the callback url. */ public void setCallbackUrl(String callbackUrl) { this.callbackUrl = callbackUrl; } /** * Returns the audio duration of the file in seconds. * * @return The audio duration of the file in seconds. */ public Double getDurationSeconds() { return durationSeconds; } /** * Sets the audio duration. * * @param durationSeconds A Double value to set as audio duration. */ public void setDurationSeconds(Double durationSeconds) { this.durationSeconds = durationSeconds; } /** * Returns the media url provided in the submission request. * * @return A String containing the media url provided in the submission request. */ public String getMediaUrl() { return mediaUrl; } /** * Sets the media url. * * @param mediaUrl A String value to set as the media url. */ public void setMediaUrl(String mediaUrl) { this.mediaUrl = mediaUrl; } /** * Returns the metadata provided in the submission request. * * @return A String containing the metadata provided in the submission request. */ public String getMetadata() { return metadata; } /** * Sets the metadata. * * @param metadata A String to set as the metadata. */ public void setMetadata(String metadata) { this.metadata = metadata; } /** * Returns the name of the file provided in the submission request. * * @return A String that contains the name of the file provided in the submission request. */ public String getName() { return name; } /** * Sets the file name. * * @param name A String to set as the file name. */ public void setName(String name) { this.name = name; } /** * Returns the {@link RevAiJobType} enumeration value. * * @return the enumeration value. * @see RevAiJobType */ public RevAiJobType getType() { return type; } /** * Sets the job type to the provided {@link RevAiJobType} enumeration. * * @param type The enumeration value to set as the job type. * @see RevAiJobType */ public void setType(RevAiJobType type) { this.type = type; } /** * Returns a detailed, human readable explanation of the failure. * * @return A detailed, human readable explanation of the failure. */ public String getFailureDetails() { return failureDetails; } /** * Sets the failure details to the provided value. * * @param failureDetails A String to set as the failure details. */ public void setFailureDetails(String failureDetails) { this.failureDetails = failureDetails; } /** * Returns the {@link RevAiFailureType} enumeration value. * * @return The {@link RevAiFailureType} enumeration value. * @see RevAiFailureType */ public RevAiFailureType getFailure() { return failure; } /** * Sets the failure to the provided {@link RevAiFailureType} enumeration. * * @param failure The enumeration value to set as the failure. * @see RevAiFailureType */ public void setFailure(RevAiFailureType failure) { this.failure = failure; } /** * Returns the duration in seconds before job is deleted * * @return The duration in seconds. */ public Integer getDeleteAfterSeconds() { return deleteAfterSeconds; } /** * Sets the duration in seconds before job is deleted * * @param deleteAfterSeconds An Integer value to set as seconds before deletion. */ public void setDeleteAfterSeconds(Integer deleteAfterSeconds) { this.deleteAfterSeconds = deleteAfterSeconds; } /** * Returns value of skip diarization for job * * @return Whether job is skipping diarization */ public Boolean getSkipDiarization() { return skipDiarization; } /** * Sets skip diarization option for job * * @param skipDiarization An Boolean value to set for skipping diarization */ public void setSkipDiarization(Boolean skipDiarization) { this.skipDiarization = skipDiarization; } /** * Returns value of skip punctuation for job * * @return Whether job is skipping punctuation */ public Boolean getSkipPunctuation() { return skipPunctuation; } /** * Sets skip punctuation option for job * * @param skipPunctuation An Boolean value to set for skipping punctuation */ public void setSkipPunctuation(Boolean skipPunctuation) { this.skipPunctuation = skipPunctuation; } /** * Returns value of remove disfluencies for job * * @return Whether job is removing disfluencies */ public Boolean getRemoveDisfluencies() { return removeDisfluencies; } /** * Sets remove disfluencies option for job * * @param removeDisfluencies An Boolean value to set for remove disfluencies */ public void setRemoveDisfluencies(Boolean removeDisfluencies) { this.removeDisfluencies = removeDisfluencies; } /** * Returns value of filter profanity for job * * @return Whether job is filtering profanity */ public Boolean getFilterProfanity() { return filterProfanity; } /** * Sets filter profanity option for job * * @param filterProfanity An Boolean value to set for filter profanity */ public void setFilterProfanity(Boolean filterProfanity) { this.filterProfanity = filterProfanity; } /** * Returns custom vocabulary id (if specified) associated to the job * * @return User-supplied custom vocabulary ID */ public String getCustomVocabularyId() { return customVocabularyId; } /** * Sets the user-supplied custom vocabulary ID for job * * @param customVocabularyId An String value to set for custom vocabulary ID */ public void setCustomVocabularyId(String customVocabularyId) { this.customVocabularyId = customVocabularyId; } /** * Returns number of speaker channels (if specified) for job * * @return Total number of unique speaker channels */ public Integer getSpeakerChannelsCount() { return speakerChannelsCount; } /** * Sets speaker channels count for job * * @param speakerChannelsCount An Integer value to set for speaker channels count */ public void setSpeakerChannelsCount(Integer speakerChannelsCount) { this.speakerChannelsCount = speakerChannelsCount; } /** * Returns language of the job * * @return language of the job */ public String getLanguage() { return language; } /** * Sets the language for job * * @param language An String value to set for language */ public void setLanguage(String language) { this.language = language; } /** * Returns transcriber used for the job * * @return transcriber used for the job */ public String getTranscriber() { return transcriber; } /** * Sets the transcriber used for job * * @param transcriber An String value to set for transcriber */ public void setTranscriber(String transcriber) { this.transcriber = transcriber; } /** * Returns value of verbatim for job transcribed by human * * @return Whether job transcribed by human is verbatim */ public Boolean getVerbatim() { return verbatim; } /** * Sets verbatim for job transcribed by human * * @param verbatim An Boolean value to set for verbatim */ public void setVerbatim(Boolean verbatim) { this.verbatim = verbatim; } /** * Returns value of rush for job transcribed by human * * @return Whether job transcribed by human has rush */ public Boolean getRush() { return rush; } /** * Sets rush option for job transcribed by human * * @param rush An Boolean value to set for rush */ public void setRush(Boolean rush) { this.rush = rush; } /** * Returns segments to transcribe for job transcribed by human * * @return List of segments to be transcribed */ public List<SegmentToTranscribe> getSegmentsToTranscribe() { return segmentsToTranscribe; } /** * Sets segments to be transcribed for job transcribed by human * * @param segmentsToTranscribe List of segments to be transcribed */ public void setSegmentsToTranscribe(List<SegmentToTranscribe> segmentsToTranscribe) { this.segmentsToTranscribe = segmentsToTranscribe; } @Override public String toString() { return "{" + "jobID='" + jobId + '\'' + ", jobStatus=" + jobStatus + ", createdOn='" + createdOn + '\'' + ", completedOn='" + completedOn + '\'' + ", callbackUrl='" + callbackUrl + '\'' + ", durationSeconds=" + durationSeconds + ", mediaUrl='" + mediaUrl + '\'' + ", metadata='" + metadata + '\'' + ", name='" + name + '\'' + ", type='" + type.getJobType() + '\'' + ", failureDetails='" + failureDetails + '\'' + ", failure='" + failure.getFailureType() + '\'' + ", deleteAfterSeconds='" + deleteAfterSeconds + '\'' + ", skipDiarization='" + skipDiarization + '\'' + ", removeDisfluencies='" + removeDisfluencies + '\'' + ", filterProfanity='" + filterProfanity + '\'' + ", customVocabularyId='" + customVocabularyId + '\'' + ", speakerChannelsCount='" + speakerChannelsCount + '\'' + ", language='" + language + '\'' + ", transcriber='" + transcriber + '\'' + ", verbatim='" + verbatim + '\'' + ", rush='" + rush + '\'' + ", segmentsToTranscribe='" + segmentsToTranscribe + '\'' + '}'; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/asynchronous/RevAiJobOptions.java
package ai.rev.speechtotext.models.asynchronous; import ai.rev.speechtotext.models.vocabulary.CustomVocabulary; import com.google.gson.annotations.SerializedName; import java.util.List; /** * A RevAiJobOptions object represents parameters that are submitted along a new job. * * @see <a * href="https://www.rev.ai/docs#operation/SubmitTranscriptionJob">https://www.rev.ai/docs#operation/SubmitTranscriptionJob</a> */ public class RevAiJobOptions { /** The media url where the file can be downloaded. */ @SerializedName("media_url") private String mediaUrl; /** The callback url that Rev.ai will send a POST to when the job has finished. */ @SerializedName("callback_url") private String callbackUrl; /** Optional parameter for the speech engine to skip diarization. */ @SerializedName("skip_diarization") private Boolean skipDiarization; /** Optional parameter for the speech engine to skip punctuation. */ @SerializedName("skip_punctuation") private Boolean skipPunctuation; /** * Optional parameter to process each audio channel separately. Account will be charged the file * duration multiplied by the number of specified channels. */ @SerializedName("speaker_channels_count") private Integer speakerChannelsCount; /** Optional parameter for the id of a pre-computed custom vocabulary to be used */ @SerializedName("custom_vocabulary_id") private String customVocabularyId; /** Optional array of {@link CustomVocabulary} objects. */ @SerializedName("custom_vocabularies") private List<CustomVocabulary> customVocabularies; /** * Optional information that can be provided. */ @SerializedName("metadata") private String metadata; /** * Optional parameter to filter profanity in the transcript */ @SerializedName("filter_profanity") private Boolean filterProfanity; /** * Optional parameter to remove disfluencies (ums, ahs) in the transcript */ @SerializedName("remove_disfluencies") private Boolean removeDisfluencies; /** * Optional number of seconds after job completion when job is auto-deleted */ @SerializedName("delete_after_seconds") private Integer deleteAfterSeconds; /** * Optional language parameter using a supported ISO 639-1 2-letter or ISO 639-3 (3-letter) language code * as defined in the API reference */ @SerializedName("language") private String language; /** * Specifies the type of transcriber to use to transcribe the media file */ @SerializedName("transcriber") private String transcriber; /** * Optional and only available with transcriber "human". * Whether transcriber will transcribe every syllable. */ @SerializedName("verbatim") private Boolean verbatim; /** * Optional and only available with transcriber "human". * Whether job is given higher priority by human transcriber for higher price. */ @SerializedName("rush") private Boolean rush; /** * Optional and only available with transcriber "human". * Whether job is mocked and no real transcription actually happens. */ @SerializedName("test_mode") private Boolean testMode; /** * Optional and only available with transcriber "human". * Sections of the transcript that should be transcribed instead of the whole file. */ @SerializedName("segments_to_transcribe") private List<SegmentToTranscribe> segmentsToTranscribe; /** * Returns the media url. * * @return The media url. */ public String getMediaUrl() { return mediaUrl; } /** * Specifies the url where the media can be downloaded. * * @param mediaUrl The direct download url to the file. */ public void setMediaUrl(String mediaUrl) { this.mediaUrl = mediaUrl; } /** * Returns the callback url. * * @return the callback url. */ public String getCallbackUrl() { return callbackUrl; } /** * Specifies the callback url that Rev.ai will POST to when job processing is complete. This * property is optional. * * @param callbackUrl The url to POST to when job processing is complete. */ public void setCallbackUrl(String callbackUrl) { this.callbackUrl = callbackUrl; } /** * Returns the value of the skip diarization Boolean. * * @return The skip diarization value. */ public Boolean getSkipDiarization() { return skipDiarization; } /** * Specifies if speaker diarization will be skipped by the speech engine. This property is * optional and defaults to false. * * @param skipDiarization The value of the Boolean. */ public void setSkipDiarization(Boolean skipDiarization) { this.skipDiarization = skipDiarization; } /** * Returns the value of the skip punctuation Boolean. * * @return The skip punctuation value. */ public Boolean getSkipPunctuation() { return skipPunctuation; } /** * Specifies if the "punct" elements will be skipped by the speech engine. This property is * optional and defaults to false. * * @param skipPunctuation The value of the Boolean. */ public void setSkipPunctuation(Boolean skipPunctuation) { this.skipPunctuation = skipPunctuation; } /** * Returns the speaker channel count. * * @return The speaker channel count. */ public Integer getSpeakerChannelsCount() { return speakerChannelsCount; } /** * Specifies the number of speaker channels in the audio. Each speaker channel is processed * separately. When set the account will be charged the file * duration multiplied by the number * of specified channels. This property is optional and defaults to null. * * @param speakerChannelsCount The number of separate speaker channels in the audio. */ public void setSpeakerChannelsCount(Integer speakerChannelsCount) { this.speakerChannelsCount = speakerChannelsCount; } /** * Returns the custom vocabulary ID. * * @return The custom vocabulary ID. */ public String getCustomVocabularyId() { return customVocabularyId; } /** * Specifies the ID of the custom vocabulary the speech engine should use while processing audio * samples. Custom vocabularies are submitted prior to usage in the stream and assigned an Id. * * @param customVocabularyId The ID of the custom vocabulary. */ public void setCustomVocabularyId(String customVocabularyId) { this.customVocabularyId = customVocabularyId; } /** * Returns a list of {@link CustomVocabulary} objects. * * @return A list of {@link CustomVocabulary} objects. * @see CustomVocabulary */ public List<CustomVocabulary> getCustomVocabularies() { return customVocabularies; } /** * Provides the custom vocabularies to be used by the speech engine when processing the * transcript. List size is limited to 50 items. Providing custom vocabularies is optional. * * @param customVocabularies A list of custom vocabularies. * @see CustomVocabulary */ public void setCustomVocabularies(List<CustomVocabulary> customVocabularies) { this.customVocabularies = customVocabularies; } /** * Returns the metadata. * * @return A String that contains the metadata. */ public String getMetadata() { return metadata; } /** * Optional metadata that is provided during job submission limited to 512 characters. * * @param metadata A String to set as the metadata. */ public void setMetadata(String metadata) { this.metadata = metadata; } /** * Returns the value of the filterProfanity Boolean * * @return The filter profanity value. */ public Boolean getFilterProfanity() { return filterProfanity; } /** * Specifies whether or not the speech engine should filter profanity in the output. Setting the * profanity filter is optional. * * @param filterProfanity The option to filter profanity. */ public void setFilterProfanity(Boolean filterProfanity) { this.filterProfanity = filterProfanity; } /** * Returns the value of the removeDisfluencies Boolean * * @return The removeDisfluencies value. */ public Boolean getRemoveDisfluencies() { return removeDisfluencies; } /** * Specifies whether or not the speech engine should remove disfluencies in the output. Setting * the option to remove disfluencies is optional. * * @param removeDisfluencies The option to remove disfluencies. */ public void setRemoveDisfluencies(Boolean removeDisfluencies) { this.removeDisfluencies = removeDisfluencies; } /** * Returns the value of deleteAfterSeconds. * * @return The deleteAfterSeconds value. */ public Integer getDeleteAfterSeconds() { return deleteAfterSeconds; } /** * Specifies the number of seconds to be waited until the job is auto-deleted after its * completion. * * @param deleteAfterSeconds The number of seconds after job completion when job is auto-deleted. */ public void setDeleteAfterSeconds(Integer deleteAfterSeconds) { this.deleteAfterSeconds = deleteAfterSeconds; } /** * Returns the value of language. * * @return the language value. */ public String getLanguage() { return language; } /** * Specifies language for ASR system using ISO 639-1 2-letter language code. * * @param language ISO 639-1 2-letter language code of desired ASR language. */ public void setLanguage(String language) { this.language = language; } /** * Specifies the type of transcriber to use to transcribe the media file * * @return the name of the transcriber type */ public String getTranscriber() { return transcriber; } /** * Specifies the type of transcriber to use to transcribe the media file * * @param transcriber the name of the transcriber type */ public void setTranscriber(String transcriber) { this.transcriber = transcriber; } /** * Returns the value of verbatim * * @return Whether verbatim is true or false */ public Boolean getVerbatim() { return verbatim; } /** * Sets whether transcriber will transcribe every syllable including disfluencies. This * property is optional but can only be used with "human" transcriber. * Defaults to false. * * @param verbatim Whether to transcribe every syllable */ public void setVerbatim(Boolean verbatim) { this.verbatim = verbatim; } /** * Returns the value of rush * * @return Whether rush is true or false */ public Boolean getRush() { return rush; } /** * Sets whether job is given higher priority by human transcriber to be worked on sooner in * exchange for a higher price. This property is optional but can only be used with "human" transcriber. * Defaults to false. * * @param rush Whether to give higher priority to the job */ public void setRush(Boolean rush) { this.rush = rush; } /** * Returns the value of testMode * * @return Whether testMode is true or false */ public Boolean getTestMode() { return testMode; } /** * Sets whether job is a mocked job which will return a mock transcript. * This property is optional but can only be used with "human" transcriber. * Defaults to false. * * @param testMode Whether to set job to be test mode */ public void setTestMode(Boolean testMode) { this.testMode = testMode; } /** * Returns the segments in media to transcribe * * @return Segments to transcribe for the job */ public List<SegmentToTranscribe> getSegmentsToTranscribe() { return segmentsToTranscribe; } /** * Specifies specific segments of the media to transcribe. * This property is optional but can only be used with "human" transcriber. * * @param segmentsToTranscribe List of segments to transcribe */ public void setSegmentsToTranscribe(List<SegmentToTranscribe> segmentsToTranscribe) { this.segmentsToTranscribe = segmentsToTranscribe; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/asynchronous/RevAiJobStatus.java
package ai.rev.speechtotext.models.asynchronous; import com.google.gson.annotations.SerializedName; /** Specifies constants that define Rev.ai job statuses. */ public enum RevAiJobStatus { /** The status when transcription has failed. */ @SerializedName("failed") FAILED("failed"), /** The status when transcription of the file is in progress. */ @SerializedName("in_progress") IN_PROGRESS("in_progress"), /** The status when the file has been transcribed. */ @SerializedName("transcribed") TRANSCRIBED("transcribed"); private String status; RevAiJobStatus(String status) { this.status = status; } /** * Returns the String value of the enumeration. * * @return The String value of the enumeration. */ public String getStatus() { return status; } @Override public String toString() { return "{" + "status='" + status + '\'' + '}'; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/asynchronous/RevAiJobType.java
package ai.rev.speechtotext.models.asynchronous; import com.google.gson.annotations.SerializedName; /** Specifies constants that define Rev.ai job types. */ public enum RevAiJobType { /** The type used for asynchronous jobs. */ @SerializedName("async") ASYNC("async"), /** The type used for streaming jobs. */ @SerializedName("stream") STREAM("stream"); private String jobType; RevAiJobType(String type) { this.jobType = type; } /** * Returns the String value of the enumeration. * * @return The String value of the enumeration. */ public String getJobType() { return jobType; } @Override public String toString() { return "{" + "type='" + jobType + '\'' + '}'; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/streaming/ConnectedMessage.java
package ai.rev.speechtotext.models.streaming; import com.google.gson.annotations.SerializedName; /** Represents the connected message sent from Rev.ai and contains the id of the stream */ public class ConnectedMessage extends StreamingResponseMessage { @SerializedName("id") private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "{" + "type='" + getType() + '\'' + ", id='" + id + '\'' + '}'; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/streaming/Hypothesis.java
package ai.rev.speechtotext.models.streaming; import ai.rev.speechtotext.models.asynchronous.Element; import com.google.gson.annotations.SerializedName; import java.util.Arrays; /** * Represents the message returned over WebSocket containing the transcription of audio data. * * @see <a * href="https://www.rev.ai/docs/streaming#section/Rev.ai-to-Client-Response/Hypothesis-Object">https://www.rev.ai/docs/streaming#section/Rev.ai-to-Client-Response/Hypothesis-Object</a> */ public class Hypothesis extends StreamingResponseMessage { @SerializedName("ts") private Double ts; @SerializedName("end_ts") private Double endTs; @SerializedName("elements") private Element[] elements; /** * Returns the starting timestamp of a transcribed audio sample. * * @return The starting timestamp of a transcribed audio sample. */ public Double getTs() { return ts; } /** * Sets the starting timestamp. * * @param ts The starting timestamp. */ public void setTs(Double ts) { this.ts = ts; } /** * Returns the ending timestamp of a transcribed audio sample. * * @return The ending timestamp of a transcribed audio sample. */ public Double getEndTs() { return endTs; } /** * Sets the ending timestamp. * * @param endTs The ending timestamp. */ public void setEndTs(Double endTs) { this.endTs = endTs; } /** * Returns a list of {@link Element} objects. * * @return A list of {@link Element} objects. * @see Element */ public Element[] getElements() { return elements; } /** * Sets elements to the list of {@link Element} objects provided. * * @param elements The list of {@link Element} objects to set as the elements. * @see Element */ public void setElements(Element[] elements) { this.elements = elements; } @Override public String toString() { return "{" + "type='" + getType() + '\'' + ", ts=" + ts + ", endTs=" + endTs + ", elements=" + Arrays.toString(elements) + '}'; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/streaming/SessionConfig.java
package ai.rev.speechtotext.models.streaming; /** The SessionConfig represents additional streaming options that can be provided. */ public class SessionConfig { private String metaData; private Boolean filterProfanity; private String customVocabularyId; private Boolean removeDisfluencies; private Integer deleteAfterSeconds; private Boolean detailedPartials; private Double startTs; private String transcriber; /** * Returns the metadata. * * @return The metadata. */ public String getMetaData() { return metaData; } /** * Specifies the metadata to be used in the submission request to /jobs. * * @param metaData The metadata to send with the request. */ public void setMetaData(String metaData) { this.metaData = metaData; } /** * Returns the value of the filter profanity option. * * @return The value of the filter profanity option. */ public Boolean getFilterProfanity() { return filterProfanity; } /** * Specifies whether or not the speech engine should filter profanity in the output. Setting the * profanity filter is optional. * * @param filterProfanity The option to filter profanity. * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Filter-Profanity">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Filter-Profanity</a> */ public void setFilterProfanity(Boolean filterProfanity) { this.filterProfanity = filterProfanity; } /** * Returns the custom vocabulary ID. * * @return The custom vocabulary ID. */ public String getCustomVocabularyId() { return customVocabularyId; } /** * Specifies the ID of the custom vocabulary the speech engine should use while processing audio * samples. Custom vocabularies are submitted prior to usage in the stream and assigned an Id. * * @param customVocabularyId The ID of the custom vocabulary. */ public void setCustomVocabularyId(String customVocabularyId) { this.customVocabularyId = customVocabularyId; } /** * Returns the value of the remove disfluencies option. * * @return The value of the remove disfluencies option. */ public Boolean getRemoveDisfluencies() { return removeDisfluencies; } /** * Specifies whether or not the speech engine should remove disfluencies in the output. Setting * the option to remove disfluencies is optional. * * @param removeDisfluencies The option to filter profanity. * @see <a href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Remove-Disfluencies"> * https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Remove-Disfluencies * </a> */ public void setRemoveDisfluencies(Boolean removeDisfluencies) { this.removeDisfluencies = removeDisfluencies; } /** * Returns the value of deleteAfterSeconds. * * @return The deleteAfterSeconds value. */ public Integer getDeleteAfterSeconds() { return deleteAfterSeconds; } /** * Specifies the number of seconds to be waited until the job is auto-deleted after its * completion. * * @param deleteAfterSeconds The number of seconds after job completion when job is auto-deleted. */ public void setDeleteAfterSeconds(Integer deleteAfterSeconds) { this.deleteAfterSeconds = deleteAfterSeconds; } /** * Returns the value of detailed partials option * * @return The value of the detailed partials option. */ public Boolean getDetailedPartials() { return detailedPartials; } /** * Specifies whether or not to return detailed partials. Setting the option is optional. * * @param detailedPartials The option to enable detailed partials. * @see <a href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Detailed-Partials"> * https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Detailed-Partials * </a> */ public void setDetailedPartials(Boolean detailedPartials) { this.detailedPartials = detailedPartials; } /** * Returns the value of startTs. * * @return The startTs value. */ public Double getStartTs() { return startTs; } /** * Specifies the number of seconds to offset all hypotheses timings. * * @param startTs The number of seconds to offset all hypotheses timings. */ public void setStartTs(Double startTs) { this.startTs = startTs; } /** * Returns the value of transcriber. * * @return The transcriber value. */ public String getTranscriber() { return transcriber; } /** * Specifies the type of transcriber to use to transcribe the media. * * @param transcriber The type of transcriber to use to transcribe the media. */ public void setTranscriber(String transcriber) { this.transcriber = transcriber; } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/streaming/StreamContentType.java
package ai.rev.speechtotext.models.streaming; import java.util.ArrayList; import java.util.List; /** * The StreamContentType describes the format of the audio being sent over the WebSocket. * * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type</a> */ public class StreamContentType { private String contentType; private String layout; private Integer rate; private String format; private Integer channels; public StreamContentType() {} /** * Returns the content type. * * @return The content type. */ public String getContentType() { return contentType; } /** * Specifies the content type of the audio. * * @param contentType The type of audio. * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type</a> */ public void setContentType(String contentType) { this.contentType = contentType; } /** * Returns the channel layout. * * @return The channel layout. */ public String getLayout() { return layout; } /** * Specifies the layout of channels within the buffer. * * @param layout The channel layout. * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type</a> */ public void setLayout(String layout) { this.layout = layout; } /** * Returns the audio sample rate. * * @return The audio sample rate. */ public Integer getRate() { return rate; } /** * Specifies the sample rate of the audio. * * @param rate The sample rate of the audio. * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type</a> */ public void setRate(Integer rate) { this.rate = rate; } /** * Returns the format of the audio samples. * * @return The format of the audio samples. */ public String getFormat() { return format; } /** * Specifies the format of the audio samples. * * @param format The format of the audio samples. * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type</a> * @see <a * href="https://gstreamer.freedesktop.org/documentation/additional/design/mediatype-audio-raw.html?gi-language=c#formats">Valid * formats</a> */ public void setFormat(String format) { this.format = format; } /** * Returns the number of channels. * * @return The number of channels. */ public Integer getChannels() { return channels; } /** * Specifies the number of audio channels that the audio samples contain. * * @param channels the number of audio channels in the audio. * @see <a * href="https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type">https://www.rev.ai/docs/streaming#section/WebSocket-Endpoint/Content-Type</a> */ public void setChannels(Integer channels) { this.channels = channels; } /** * Returns the content string compiled from the {@link StreamContentType} properties to be used in * the query parameter for the request to the /stream endpoint. * * @return The content string used as the query parameter. */ public String buildContentString() { List<String> content = getListFromContentType(); String empty = ""; if (content.size() == 0) { return empty; } else { return createContentTypeParameter(content); } } private List<String> getListFromContentType() { List<String> content = new ArrayList<>(); if (getContentType() != null) { content.add(getContentType()); } if (getLayout() != null) { content.add("layout" + "=" + getLayout()); } if (getRate() != null) { content.add("rate" + "=" + getRate()); } if (getFormat() != null) { content.add("format" + "=" + getFormat()); } if (getChannels() != null) { content.add("channels" + "=" + getChannels()); } return content; } private String createContentTypeParameter(List<String> content) { return String.join(";", content); } }
0
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models
java-sources/ai/rev/speechtotext/revai-java-sdk-speechtotext/1.4.0/ai/rev/speechtotext/models/vocabulary/CustomVocabularySubmission.java
package ai.rev.speechtotext.models.vocabulary; import com.google.gson.annotations.SerializedName; import java.util.List; public class CustomVocabularySubmission { /** Optional information that can be provided. */ @SerializedName("metadata") private String metadata; /** Optional callback url that Rev.ai will send a POST to when the job has finished. */ @SerializedName("callback_url") private String callbackUrl; /** Array of {@link CustomVocabulary} objects. */ @SerializedName("custom_vocabularies") private List<CustomVocabulary> customVocabularies; /** * Returns the metadata. * * @return A String that contains the metadata. */ public String getMetadata() { return metadata; } /** * Optional metadata that is provided during custom vocabulary submission limited to 512 * characters. * * @param metadata A String to set as the metadata. */ public void setMetadata(String metadata) { this.metadata = metadata; } /** * Returns the callback url. * * @return the callback url. */ public String getCallbackUrl() { return callbackUrl; } /** * Specifies the callback url that Rev.ai will POST to when custom vocabulary processing is * complete. This property is optional. * * @param callbackUrl The url to POST to when custom vocabulary processing is complete. */ public void setCallbackUrl(String callbackUrl) { this.callbackUrl = callbackUrl; } /** * Returns a list of {@link CustomVocabulary} objects. * * @return A list of {@link CustomVocabulary} objects. * @see CustomVocabulary */ public List<CustomVocabulary> getCustomVocabularies() { return customVocabularies; } /** * Provides the custom vocabularies to be used by the speech engine when processing the stream. * List size is limited to 50 items. * * @param customVocabularies A list of custom vocabularies. * @see CustomVocabulary */ public void setCustomVocabularies(List<CustomVocabulary> customVocabularies) { this.customVocabularies = customVocabularies; } @Override public String toString() { return "{" + "metadata='" + metadata + '\'' + ", callbackUrl='" + callbackUrl + '\'' + ", customVocabularies=" + customVocabularies + '}'; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/AppUpdateManagerLifecycleListener.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app; import android.app.Activity; import android.content.Intent; import android.content.IntentSender.SendIntentException; import com.google.android.play.core.appupdate.AppUpdateInfo; import com.google.android.play.core.appupdate.AppUpdateManager; import com.google.android.play.core.appupdate.AppUpdateManagerFactory; import com.google.android.play.core.install.model.AppUpdateType; import com.google.android.play.core.install.model.UpdateAvailability; import timber.log.Timber; /** * AppUpdateManagerLifecycleListener can listen to several activity lifecycle events to trigger app update mechanisms. * When the activity is created, it checks whether there is an update. When resumed, it checks if there is an update * in progress and resumes the update. * * Note that these update requests are best effort. If the user cancels or otherwise disables the update, we will still * allow the user to use the app for the rest of the session. However, every time the app is opened, this will re-trigger. */ public class AppUpdateManagerLifecycleListener { private static final int UPDATE_REQUEST_CODE = 3695; private AppUpdateManager appUpdateManager; public void onActivityCreated(final Activity activity) { appUpdateManager = AppUpdateManagerFactory.create(activity); appUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> { if (isUpdateAvailable(appUpdateInfo)) { requestUpdate(activity, appUpdateInfo); } else { Timber.d("Not requesting update. App is up to date"); } }); } public void onActivityResumed(final Activity activity) { appUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> { if (isUpdateInProgress(appUpdateInfo)) { requestUpdate(activity, appUpdateInfo); } else { Timber.d("Not requesting update. No update in progress."); } }); } public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if (requestCode == UPDATE_REQUEST_CODE) { if (resultCode != Activity.RESULT_OK) { Timber.e("Failed to update app: %d", resultCode); } } } private void requestUpdate(final Activity activity, final AppUpdateInfo appUpdateInfo) { try { appUpdateManager.startUpdateFlowForResult( appUpdateInfo, AppUpdateType.IMMEDIATE, activity, UPDATE_REQUEST_CODE ); } catch (final SendIntentException e) { Timber.e(e, "Unable to request update from the app store"); } } private static boolean isUpdateAvailable(final AppUpdateInfo appUpdateInfo) { return appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE); } private static boolean isUpdateInProgress(final AppUpdateInfo appUpdateInfo) { return appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/BaseApplication.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app; import ai.rideos.android.common.BuildConfig; import ai.rideos.android.common.reactive.ErrorHandlers; import android.app.Application; import io.reactivex.plugins.RxJavaPlugins; import timber.log.Timber; import timber.log.Timber.DebugTree; /** * Default application that sets up logging and Rx error handling. This can be used as the base to the rider or driver * applications. */ public abstract class BaseApplication extends Application { @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new DebugTree()); } else { // In production we should make sure uncaught rxJava exceptions should not crash the app // TODO report these exceptions RxJavaPlugins.setErrorHandler(ErrorHandlers.swallow()); } registerDependencies(); } protected abstract void registerDependencies(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/CommonMetadataKeys.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app; public class CommonMetadataKeys { public static final String DEFAULT_FLEET_ID = "default_fleet_id"; public static final String MAPBOX_TOKEN_KEY = "mapbox_token"; public static final String ENABLE_DEVELOPER_OPTIONS_KEY = "enable_developer_options"; public static final String ENABLE_PUSH_NOTIFICATIONS = "enable_push_notifications"; }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/MetadataReader.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import androidx.annotation.Nullable; public class MetadataReader { public static class MetadataResult<T> { private final String key; @Nullable private final T value; private MetadataResult(final String key, @Nullable final T value) { this.key = key; this.value = value; } public T getOrDefault(final T defaultValue) { if (value == null) { return defaultValue; } return value; } public T getOrThrow() { if (value == null) { throw new RuntimeException("Key not found: " + key); } return value; } } private final Context context; public MetadataReader(final Context context) { this.context = context; } public MetadataResult<String> getStringMetadata(final String key) { try { final Bundle metadata = getMetadataFromContext(); final String maybeValue = metadata.getString(key); return new MetadataResult<>(key, maybeValue); } catch (NameNotFoundException e) { return new MetadataResult<>(key, null); } } public MetadataResult<Boolean> getBooleanMetadata(final String key) { try { final Bundle metadata = getMetadataFromContext(); final Boolean maybeValue = metadata.getBoolean(key); return new MetadataResult<>(key, maybeValue); } catch (NameNotFoundException e) { return new MetadataResult<>(key, null); } } private Bundle getMetadataFromContext() throws NameNotFoundException { final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA ); return appInfo.metaData; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/dependency/CommonDependencyFactory.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.dependency; import ai.rideos.android.common.interactors.DeviceRegistryInteractor; import ai.rideos.android.common.interactors.FleetInteractor; import ai.rideos.android.common.interactors.RideOsRouteInteractor; import android.content.Context; public interface CommonDependencyFactory { FleetInteractor getFleetInteractor(final Context context); RideOsRouteInteractor getRouteInteractor(final Context context); DeviceRegistryInteractor getDeviceRegistryInteractor(final Context context); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/dependency/CommonDependencyRegistry.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.dependency; public class CommonDependencyRegistry { private static CommonDependencyFactory COMMON_DEPENDENCY_FACTORY; private static MapDependencyFactory MAP_DEPENDENCY_FACTORY; public static void init(final CommonDependencyFactory commonDependencyFactory, final MapDependencyFactory mapDependencyFactory) { COMMON_DEPENDENCY_FACTORY = commonDependencyFactory; MAP_DEPENDENCY_FACTORY = mapDependencyFactory; } public static CommonDependencyFactory commonDependencyFactory() { if (COMMON_DEPENDENCY_FACTORY == null) { throw new RuntimeException( "Common dependency factory not set. Call CommonDependencyRegistry.init() before accessing " + "commonDependencyFactory()" ); } return COMMON_DEPENDENCY_FACTORY; } public static MapDependencyFactory mapDependencyFactory() { if (MAP_DEPENDENCY_FACTORY == null) { throw new RuntimeException( "Map dependency factory not set. Call CommonDependencyRegistry.init() before accessing " + "mapDependencyFactory()" ); } return MAP_DEPENDENCY_FACTORY; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/dependency/DefaultCommonDependencyFactory.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.dependency; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.grpc.ChannelProvider; import ai.rideos.android.common.interactors.DefaultDeviceRegistryInteractor; import ai.rideos.android.common.interactors.DefaultFleetInteractor; import ai.rideos.android.common.interactors.DeviceRegistryInteractor; import ai.rideos.android.common.interactors.FleetInteractor; import ai.rideos.android.common.interactors.RideOsRouteInteractor; import android.content.Context; public class DefaultCommonDependencyFactory implements CommonDependencyFactory { public FleetInteractor getFleetInteractor(final Context context) { return new DefaultFleetInteractor(ChannelProvider.getChannelSupplierForContext(context), User.get(context)); } public RideOsRouteInteractor getRouteInteractor(final Context context) { return new RideOsRouteInteractor(ChannelProvider.getChannelSupplierForContext(context), User.get(context)); } @Override public DeviceRegistryInteractor getDeviceRegistryInteractor(final Context context) { return new DefaultDeviceRegistryInteractor( ChannelProvider.getChannelSupplierForContext(context), User.get(context) ); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/dependency/MapDependencyFactory.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.dependency; import ai.rideos.android.common.interactors.GeocodeInteractor; import ai.rideos.android.common.interactors.LocationAutocompleteInteractor; import android.content.Context; import androidx.fragment.app.Fragment; public interface MapDependencyFactory { Fragment getMapFragment(); LocationAutocompleteInteractor getAutocompleteInteractor(final Context context); GeocodeInteractor getGeocodeInteractor(final Context context); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/DefaultLaunchViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import io.reactivex.Observable; import io.reactivex.subjects.BehaviorSubject; import timber.log.Timber; public class DefaultLaunchViewModel implements LaunchViewModel { private final Runnable launchDoneListener; private final BehaviorSubject<Integer> stepSubject; private final int maxStep; private final SchedulerProvider schedulerProvider; public DefaultLaunchViewModel(final Runnable launchDoneListener, final int numSteps) { this(launchDoneListener, numSteps, new DefaultSchedulerProvider()); } public DefaultLaunchViewModel(final Runnable launchDoneListener, final int numSteps, final SchedulerProvider schedulerProvider) { this.launchDoneListener = launchDoneListener; maxStep = numSteps - 1; stepSubject = BehaviorSubject.createDefault(0); this.schedulerProvider = schedulerProvider; } @Override public void finishLaunchStep(final int stepNumber) { final int currentStep = stepSubject.getValue(); if (currentStep != stepNumber) { Timber.e("Cannot finish step %d because the current step is %d", stepNumber, currentStep); } else if (currentStep == maxStep) { launchDoneListener.run(); } else { stepSubject.onNext(currentStep + 1); } } @Override public Observable<Integer> getLaunchStepToDisplay() { return stepSubject; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/LaunchPresenter.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch; import ai.rideos.android.common.app.launch.permissions.PermissionRequestor; import ai.rideos.android.common.view.ParentPresenter; import ai.rideos.android.common.view.Presenter; import android.content.Context; import android.view.ViewGroup; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import java.util.List; public class LaunchPresenter extends ParentPresenter<ViewGroup> implements PermissionRequestor { private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final Context context; private final List<LaunchStep> launchSteps; private final LaunchViewModel launchViewModel; public LaunchPresenter(final Context context, final List<LaunchStep> launchSteps, final Runnable launchDone) { this.context = context; this.launchSteps = launchSteps; launchViewModel = new DefaultLaunchViewModel(launchDone, launchSteps.size()); } @Override public void attach(final ViewGroup container) { compositeDisposable.add( launchViewModel.getLaunchStepToDisplay().observeOn(AndroidSchedulers.mainThread()) .subscribe(step -> { final Presenter<ViewGroup> viewControllerToDisplay = launchSteps.get(step) .buildStep(context, () -> launchViewModel.finishLaunchStep(step)); replaceChildAndAttach(viewControllerToDisplay, container); }) ); } @Override public void detach() { super.detach(); compositeDisposable.dispose(); } @Override public void onRequestPermissionsResult(final int requestCode, final String[] permissions, final int[] grantResults) { final Presenter child = getChild(); if (child instanceof PermissionRequestor) { ((PermissionRequestor) child).onRequestPermissionsResult(requestCode, permissions, grantResults); } } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/LaunchStep.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch; import ai.rideos.android.common.view.Presenter; import android.content.Context; import android.view.ViewGroup; /** * LaunchStep represents a single step in a sequential set of launch steps. Each step creates a view controller to * display on the screen. When the step is done, it can call the LaunchStepListener to complete. */ public interface LaunchStep { interface LaunchStepListener { void done(); } Presenter<ViewGroup> buildStep(final Context context, final LaunchStepListener stepListener); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/LaunchViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch; import io.reactivex.Observable; /** * Represents a sequential set of steps to take during the app launch. The app can finish a launch step and move onto * the next. */ public interface LaunchViewModel { void finishLaunchStep(final int stepNumber); Observable<Integer> getLaunchStepToDisplay(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/login/DefaultLoginViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.login; import ai.rideos.android.common.app.launch.LaunchStep.LaunchStepListener; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.reactive.Notification; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import com.auth0.android.result.Credentials; import io.reactivex.Observable; import io.reactivex.subjects.BehaviorSubject; import timber.log.Timber; public class DefaultLoginViewModel implements LoginViewModel { private final LaunchStepListener launchStepListener; private final SchedulerProvider schedulerProvider; private final User user; private final BehaviorSubject<Notification> loginSubject = BehaviorSubject.createDefault(Notification.create()); public DefaultLoginViewModel(final User user, final LaunchStepListener launchStepListener) { this( user, launchStepListener, new DefaultSchedulerProvider() ); } public DefaultLoginViewModel(final User user, final LaunchStepListener launchStepListener, final SchedulerProvider schedulerProvider) { this.schedulerProvider = schedulerProvider; this.user = user; this.launchStepListener = launchStepListener; } @Override public void loginComplete(final Credentials credentials) { user.updateCredentials(credentials); launchStepListener.done(); } @Override public void loginFailure(final Exception exception) { Timber.e(exception, "Failed to login"); loginSubject.onNext(Notification.create()); } @Override public Observable<Notification> shouldLaunchLogin() { if (user.isLoggedIn()) { launchStepListener.done(); return Observable.empty(); } return loginSubject; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/login/LoginPresenter.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.login; import ai.rideos.android.common.R; import ai.rideos.android.common.app.launch.LaunchStep.LaunchStepListener; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.view.Presenter; import android.content.Context; import android.view.ViewGroup; import com.auth0.android.Auth0; import com.auth0.android.lock.AuthenticationCallback; import com.auth0.android.lock.Lock; import com.auth0.android.lock.LockCallback; import com.auth0.android.lock.utils.LockException; import com.auth0.android.result.Credentials; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import java.util.Arrays; public class LoginPresenter implements Presenter<ViewGroup> { private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final Context context; private final LoginViewModel loginViewModel; private final Lock lockScreen; public LoginPresenter(final Context context, final LaunchStepListener listener) { this.context = context; loginViewModel = new DefaultLoginViewModel(User.get(context), listener); final Auth0 account = new Auth0(context); account.setOIDCConformant(true); lockScreen = Lock.newBuilder(account, getLockCallback()) .allowedConnections(Arrays.asList(context.getString(R.string.com_auth0_connections).split(" "))) .withAudience(context.getString(R.string.com_auth0_audience)) .withScheme(context.getString(R.string.com_auth0_scheme)) .withScope(context.getString(R.string.com_auth0_scope)) .build(context); } @Override public void attach(final ViewGroup view) { compositeDisposable.add( loginViewModel.shouldLaunchLogin().observeOn(AndroidSchedulers.mainThread()) .subscribe(notification -> context.startActivity(lockScreen.newIntent(context))) ); } private LockCallback getLockCallback() { return new AuthenticationCallback() { @Override public void onAuthentication(final Credentials credentials) { loginViewModel.loginComplete(credentials); } @Override public void onCanceled() { } @Override public void onError(final LockException error) { loginViewModel.loginFailure(error); } }; } @Override public void detach() { compositeDisposable.dispose(); lockScreen.onDestroy(context); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/login/LoginViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.login; import ai.rideos.android.common.reactive.Notification; import com.auth0.android.result.Credentials; import io.reactivex.Observable; public interface LoginViewModel { void loginComplete(final Credentials credentials); void loginFailure(final Exception exception); /** * Emit a notification when the login experience should be launched. If the user is already logged in, this should * not emit anything. */ Observable<Notification> shouldLaunchLogin(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/permissions/DefaultPermissionsViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.permissions; import ai.rideos.android.common.app.launch.LaunchStep.LaunchStepListener; import ai.rideos.android.common.reactive.Notification; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import android.Manifest.permission; import io.reactivex.Observable; import io.reactivex.subjects.BehaviorSubject; import java.util.Collections; import java.util.List; public class DefaultPermissionsViewModel implements PermissionsViewModel { private final BehaviorSubject<Notification> permissionsRequired = BehaviorSubject.createDefault(Notification.create()); private final SchedulerProvider schedulerProvider; private final LaunchStepListener launchStepListener; public DefaultPermissionsViewModel(final LaunchStepListener launchStepListener) { this(launchStepListener, new DefaultSchedulerProvider()); } public DefaultPermissionsViewModel(final LaunchStepListener launchStepListener, final SchedulerProvider schedulerProvider) { this.schedulerProvider = schedulerProvider; this.launchStepListener = launchStepListener; } @Override public void permissionsEnabled(final boolean areEnabled) { if (areEnabled) { launchStepListener.done(); } else { permissionsRequired.onNext(Notification.create()); } } @Override public Observable<List<String>> getPermissionsToCheck() { return permissionsRequired .map(notification -> Collections.singletonList(permission.ACCESS_FINE_LOCATION)); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/permissions/PermissionRequestor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.permissions; /** * Represents a class that requests permissions for the user. The callback for the result of this request comes from the * top-level activity, so this interface can be used to propagate the request result to other objects. */ public interface PermissionRequestor { void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/permissions/PermissionsPresenter.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.permissions; import ai.rideos.android.common.R; import ai.rideos.android.common.app.launch.LaunchStep.LaunchStepListener; import ai.rideos.android.common.view.Presenter; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.pm.PackageManager; import androidx.core.app.ActivityCompat; import android.view.ViewGroup; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import java.util.List; public class PermissionsPresenter implements Presenter<ViewGroup>, PermissionRequestor { private static final int PERMISSION_REQUEST_ID = 58417; private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final Context context; private final PermissionsViewModel permissionsViewModel; public PermissionsPresenter(final Context context, final LaunchStepListener listener) { this.context = context; permissionsViewModel = new DefaultPermissionsViewModel(listener); } @Override public void attach(final ViewGroup view) { compositeDisposable.add( permissionsViewModel.getPermissionsToCheck().observeOn(AndroidSchedulers.mainThread()) .subscribe(this::checkPermissions) ); } private void checkPermissions(final List<String> permissionsToCheck) { final boolean permissionsEnabled = permissionsToCheck.stream() .allMatch(permission -> ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED ); if (permissionsEnabled) { permissionsViewModel.permissionsEnabled(true); return; } // TODO Change design from modal to view new Builder(context) .setTitle(context.getString(R.string.location_permission_explanation_title)) .setMessage(context.getString(R.string.location_permission_explanation_details)) .setPositiveButton(context.getString(R.string.location_permission_confirmation), (dialog, i) -> // When this completes, onRequestPermissionsResult is called ActivityCompat.requestPermissions( (Activity) context, permissionsToCheck.toArray(new String[0]), PERMISSION_REQUEST_ID ) ) .create() .show(); } @Override public void onRequestPermissionsResult(final int requestCode, final String permissions[], final int[] grantResults) { if (requestCode == PERMISSION_REQUEST_ID) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { permissionsViewModel.permissionsEnabled(true); } else { permissionsViewModel.permissionsEnabled(false); } } } @Override public void detach() { compositeDisposable.dispose(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/launch/permissions/PermissionsViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.launch.permissions; import io.reactivex.Observable; import java.util.List; public interface PermissionsViewModel { /** * Mark all notifications from `getPermissionsToCheck` as enabled or disabled. */ void permissionsEnabled(final boolean areEnabled); /** * Return a list of device permissions to check that they are enabled. */ Observable<List<String>> getPermissionsToCheck(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/map/MapInsetFragmentListener.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.map; import ai.rideos.android.common.view.ViewMarginProvider; import ai.rideos.android.common.view.ViewMargins; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentManager.FragmentLifecycleCallbacks; import android.view.View; public class MapInsetFragmentListener extends FragmentLifecycleCallbacks { private final MapStateReceiver mapStateReceiver; public MapInsetFragmentListener() { mapStateReceiver = MapRelay.get(); } @Override public void onFragmentViewCreated(@NonNull final FragmentManager fragmentManager, @NonNull final Fragment fragment, @NonNull final View view, @Nullable final Bundle savedInstanceState) { super.onFragmentViewCreated(fragmentManager, fragment, view, savedInstanceState); if (view instanceof ViewMarginProvider) { ((ViewMarginProvider) view).calculateViewMargins(mapStateReceiver::setMapMargins); } else { mapStateReceiver.setMapMargins(ViewMargins.newBuilder().build()); } } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/map/MapRelay.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.map; import ai.rideos.android.common.model.map.CameraUpdate; import ai.rideos.android.common.model.map.CenterPin; import ai.rideos.android.common.model.map.DrawableMarker; import ai.rideos.android.common.model.map.DrawablePath; import ai.rideos.android.common.model.map.MapSettings; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.view.ViewMargins; import ai.rideos.android.common.viewmodel.map.MapStateProvider; import androidx.annotation.VisibleForTesting; import androidx.core.util.Pair; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.subjects.BehaviorSubject; import java.util.List; import java.util.Map; /** * The MapRelay relays state from a MapStateProvider to a MapFragment by implementing both the MapViewModel and the * MapStateReceiver. The state provider sends information through the MapStateReceiver which is added to behavior subjects. * When the MapFragment is loaded, it can connect through the MapViewModel to receive state and update the map view. */ public class MapRelay implements MapViewModel, MapStateReceiver { private static volatile MapRelay INSTANCE; private final BehaviorSubject<Boolean> isMapCenteredSubject = BehaviorSubject.createDefault(true); private final BehaviorSubject<CameraUpdate> latestCameraUpdateSubject = BehaviorSubject.create(); private final BehaviorSubject<MapSettings> mapSettingsSubject = BehaviorSubject.create(); private final BehaviorSubject<Map<String, DrawableMarker>> markerSubject = BehaviorSubject.create(); private final BehaviorSubject<List<DrawablePath>> pathSubject = BehaviorSubject.create(); private final BehaviorSubject<ViewMargins> mapMarginSubject = BehaviorSubject.create(); private final BehaviorSubject<MapCenterListener> mapCenterListenerSubject = BehaviorSubject.create(); private final SchedulerProvider schedulerProvider; private MapRelay() { this(new DefaultSchedulerProvider()); } @VisibleForTesting MapRelay(final SchedulerProvider schedulerProvider) { this.schedulerProvider = schedulerProvider; } public static MapRelay get() { if (INSTANCE == null) { synchronized (MapRelay.class) { if (INSTANCE == null) { INSTANCE = new MapRelay(); } } } return INSTANCE; } /** * Connect a map state provider to the map relay and returns a disposable for all subscribed values * @param mapStateProvider - state provider, like a view model * @return disposable with all elements that have been subscribed */ public Disposable connectToProvider(final MapStateProvider mapStateProvider) { return connectToProvider(mapStateProvider, MapCenterListener.NOOP); } /** * Connect a map state provider and a map center listener to the map relay and returns a disposable for all * subscribed values * @param mapStateProvider - state provider, like a view model * @param mapCenterListener - listener that is called when the map view center changes * @return disposable with all elements that have been subscribed */ public Disposable connectToProvider(final MapStateProvider mapStateProvider, final MapCenterListener mapCenterListener) { final CompositeDisposable compositeDisposable = new CompositeDisposable(); compositeDisposable.addAll( mapStateProvider.getMapSettings() .subscribe(this::setMapSettings), // Forcefully move camera when a provider first connects to the map view mapStateProvider.getCameraUpdates() .firstElement() .subscribe(update -> moveCamera(update, true)), // Non-forcefully move camera for 2nd update and after mapStateProvider.getCameraUpdates() .skip(1) .subscribe(update -> moveCamera(update, false)), mapStateProvider.getMarkers() .subscribe(this::showMarkers), mapStateProvider.getPaths() .subscribe(this::showPaths) ); if (mapCenterListener != null) { this.setMapCenterListener(mapCenterListener); } // Between map providers, hide the center pin. This helps when the padding of the map changes and the center // pin moves around the map compositeDisposable.add(Disposables.fromAction(() -> setMapSettings(new MapSettings(false, CenterPin.hidden())) )); return compositeDisposable; } // MapViewModel - exposed to map fragment @Override public void mapWasDragged() { isMapCenteredSubject.onNext(false); } @Override public void reCenterMap() { isMapCenteredSubject.onNext(true); } @Override public Observable<CameraUpdate> getCameraUpdatesToPerform() { return Observable.combineLatest( latestCameraUpdateSubject.observeOn(schedulerProvider.computation()), isMapCenteredSubject.observeOn(schedulerProvider.computation()), Pair::create ) // Only return camera updates when map is centered .filter(updateAndCentered -> updateAndCentered.second) .map(updateAndCentered -> updateAndCentered.first); } @Override public Observable<Boolean> shouldAllowReCentering() { return isMapCenteredSubject.map(isCentered -> !isCentered); } @Override public Observable<MapSettings> getMapSettings() { return mapSettingsSubject; } @Override public Observable<Map<String, DrawableMarker>> getMarkers() { return markerSubject; } @Override public Observable<List<DrawablePath>> getPaths() { return pathSubject; } @Override public Observable<ViewMargins> getMapMargins() { return mapMarginSubject; } @Override public Observable<MapCenterListener> getMapCenterListener() { return mapCenterListenerSubject; } // MapStateReceiver - exposed to map state provider @Override public void setMapSettings(final MapSettings mapSettings) { mapSettingsSubject.onNext(mapSettings); } @Override public void moveCamera(final CameraUpdate cameraUpdate, final boolean force) { latestCameraUpdateSubject.onNext(cameraUpdate); if (force) { reCenterMap(); } } @Override public void showMarkers(final Map<String, DrawableMarker> markers) { markerSubject.onNext(markers); } @Override public void showPaths(final List<DrawablePath> paths) { pathSubject.onNext(paths); } @Override public void setMapCenterListener(final MapCenterListener listener) { mapCenterListenerSubject.onNext(listener); } @Override public void setMapMargins(final ViewMargins mapMargins) { mapMarginSubject.onNext(mapMargins); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/map/MapStateReceiver.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.map; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.model.map.CameraUpdate; import ai.rideos.android.common.model.map.DrawableMarker; import ai.rideos.android.common.model.map.DrawablePath; import ai.rideos.android.common.model.map.MapSettings; import ai.rideos.android.common.view.ViewMargins; import java.util.List; import java.util.Map; public interface MapStateReceiver { interface MapCenterListener { MapCenterListener NOOP = move -> {}; default void mapCenterStartedMoving() { } void mapCenterDidMove(final LatLng move); } /** * Set common map view settings like if current location is shown and if a center pin is shown * @param mapSettings */ void setMapSettings(final MapSettings mapSettings); /** * Move the camera to a new location. * @param cameraUpdate - how to update the camera (e.g. zoom to point, fit to bounds) * @param force - if true, forces the camera to move. If false, update is ignored when user is dragging */ void moveCamera(final CameraUpdate cameraUpdate, final boolean force); /** * Show markers on the map at given locations. To update markers, use the same id and call this method. To delete * markers, call this method and exclude the ids. * @param markers - markers to set on the map. New markers will be added, existing markers will be updated, and * missing markers will be deleted */ void showMarkers(final Map<String, DrawableMarker> markers); /** * Show paths on the map. When this is called, any shown path will be removed. * @param paths - paths to show */ void showPaths(final List<DrawablePath> paths); /** * Listen to the movement of the map after such events like a user dragging the screen * @param listener - called when movement finishes occurring */ void setMapCenterListener(final MapCenterListener listener); void setMapMargins(final ViewMargins mapMargins); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/map/MapViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.map; import ai.rideos.android.common.app.map.MapStateReceiver.MapCenterListener; import ai.rideos.android.common.model.map.CameraUpdate; import ai.rideos.android.common.model.map.DrawableMarker; import ai.rideos.android.common.model.map.DrawablePath; import ai.rideos.android.common.model.map.MapSettings; import ai.rideos.android.common.view.ViewMargins; import io.reactivex.Observable; import java.util.List; import java.util.Map; public interface MapViewModel { /** * Notify view model that the user started dragging the map to a different location. */ void mapWasDragged(); /** * Center the map back on the last requested camera update location. */ void reCenterMap(); /** * Get the camera updates that should actually be performed. This is a filtered set of the camera updates requested. */ Observable<CameraUpdate> getCameraUpdatesToPerform(); /** * Observe whether the re-center button should be overlayed on the map. */ Observable<Boolean> shouldAllowReCentering(); Observable<MapSettings> getMapSettings(); Observable<Map<String, DrawableMarker>> getMarkers(); Observable<List<DrawablePath>> getPaths(); Observable<ViewMargins> getMapMargins(); Observable<MapCenterListener> getMapCenterListener(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/DefaultMenuOptions.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator; /** * DefaultMenuOptions provides the common side-bar menu options we provide, including some home content, developer * options, and logging out. */ public enum DefaultMenuOptions { HOME(0), ACCOUNT_SETTINGS(1), DEVELOPER_OPTIONS(2); private final int id; DefaultMenuOptions(final int id) { this.id = id; } public int getId() { return id; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/LoggedOutListener.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator; public interface LoggedOutListener { void loggedOut(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/MenuOptionFragmentRegistry.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator; import ai.rideos.android.common.model.MenuOption; import androidx.fragment.app.Fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MenuOptionFragmentRegistry { public interface FragmentConstructor { Fragment construct(); } private final MenuOption homeOption; private final List<MenuOption> menuOptions = new ArrayList<>(); private final Map<Integer, FragmentConstructor> constructorsByOptionId = new HashMap<>(); public MenuOptionFragmentRegistry(final MenuOption homeOption, final FragmentConstructor homeFragmentConstructor) { this.homeOption = homeOption; registerOption(homeOption, homeFragmentConstructor); } public MenuOptionFragmentRegistry registerOption(final MenuOption menuOption, final FragmentConstructor fragmentConstructor) { menuOptions.add(menuOption); constructorsByOptionId.put(menuOption.getId(), fragmentConstructor); return this; } public MenuOption getHomeOption() { return homeOption; } public FragmentConstructor getConstructorForOption(final MenuOption menuOption) { return constructorsByOptionId.get(menuOption.getId()); } public List<MenuOption> getMenuOptions() { return menuOptions; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/OpenMenuListener.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator; public interface OpenMenuListener { void openMenu(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/account_settings/AccountSettingsFragment.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.account_settings; import ai.rideos.android.common.R; import ai.rideos.android.common.app.menu_navigator.OpenMenuListener; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.device.InputMethodManagerKeyboardManager; import ai.rideos.android.common.device.KeyboardManager; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageReader; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageWriter; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toolbar; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import java.util.function.Consumer; public class AccountSettingsFragment extends Fragment { private CompositeDisposable compositeDisposable; private AccountSettingsViewModel viewModel; private OpenMenuListener openMenuListener; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewModel = new DefaultAccountSettingsViewModel( User.get(getContext()), SharedPreferencesUserStorageReader.forContext(getContext()), SharedPreferencesUserStorageWriter.forContext(getContext()) ); openMenuListener = (OpenMenuListener) getActivity(); } @Override public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(R.layout.account_settings, container, false); } @Override public void onStart() { super.onStart(); compositeDisposable = new CompositeDisposable(); final View view = getView(); final KeyboardManager keyboardManager = new InputMethodManagerKeyboardManager(getContext(), view); final EditText preferredNameText = view.findViewById(R.id.preferred_name_edit_text); listenToEditText(preferredNameText, viewModel::editPreferredName); final EditText emailText = view.findViewById(R.id.email_edit_text); final Toolbar toolbar = view.findViewById(R.id.title_bar); toolbar.setNavigationOnClickListener(click -> { keyboardManager.hideKeyboard(); openMenuListener.openMenu(); }); final Button saveButton = view.findViewById(R.id.save_button); saveButton.setOnClickListener(click -> { viewModel.save(); preferredNameText.clearFocus(); keyboardManager.hideKeyboard(); }); compositeDisposable.addAll( viewModel.getPreferredName().observeOn(AndroidSchedulers.mainThread()).subscribe(preferredNameText::setText), viewModel.getEmail().observeOn(AndroidSchedulers.mainThread()).subscribe(emailText::setText), viewModel.isSavingEnabled().observeOn(AndroidSchedulers.mainThread()).subscribe(enabled -> { if (enabled) { saveButton.setVisibility(View.VISIBLE); } else { saveButton.setVisibility(View.GONE); } }) ); } private static void listenToEditText(final EditText editText, final Consumer<String> onChange) { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } @Override public void onTextChanged(final CharSequence s, final int start, final int before, final int count) { onChange.accept(s.toString()); } @Override public void afterTextChanged(final Editable s) { } }); } @Override public void onStop() { super.onStop(); compositeDisposable.dispose(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/account_settings/AccountSettingsViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.account_settings; import io.reactivex.Observable; public interface AccountSettingsViewModel { void save(); void editPreferredName(final String preferredName); Observable<String> getPreferredName(); Observable<String> getEmail(); Observable<Boolean> isSavingEnabled(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/account_settings/DefaultAccountSettingsViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.account_settings; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.user_storage.StorageKeys; import ai.rideos.android.common.user_storage.UserStorageReader; import ai.rideos.android.common.user_storage.UserStorageWriter; import com.auth0.android.result.UserProfile; import io.reactivex.Observable; import io.reactivex.subjects.BehaviorSubject; import timber.log.Timber; public class DefaultAccountSettingsViewModel implements AccountSettingsViewModel { private static final int RETRY_COUNT = 3; private final BehaviorSubject<String> editedPreferredNameSubject = BehaviorSubject.create(); private final BehaviorSubject<String> savedPreferredNameSubject; private final User user; private final UserStorageWriter userStorageWriter; private final SchedulerProvider schedulerProvider; public DefaultAccountSettingsViewModel(final User user, final UserStorageReader userStorageReader, final UserStorageWriter userStorageWriter) { this(user, userStorageReader, userStorageWriter, new DefaultSchedulerProvider()); } public DefaultAccountSettingsViewModel(final User user, final UserStorageReader userStorageReader, final UserStorageWriter userStorageWriter, final SchedulerProvider schedulerProvider) { this.user = user; this.userStorageWriter = userStorageWriter; this.schedulerProvider = schedulerProvider; savedPreferredNameSubject = BehaviorSubject.createDefault( userStorageReader.getStringPreference(StorageKeys.PREFERRED_NAME) ); } @Override public void save() { final String preferredName = editedPreferredNameSubject.getValue(); if (preferredName != null) { userStorageWriter.storeStringPreference(StorageKeys.PREFERRED_NAME, preferredName); savedPreferredNameSubject.onNext(preferredName); } } @Override public void editPreferredName(final String preferredName) { editedPreferredNameSubject.onNext(preferredName); } @Override public Observable<String> getPreferredName() { return Observable.just(savedPreferredNameSubject.getValue()); } @Override public Observable<String> getEmail() { return user.fetchUserProfile() .observeOn(schedulerProvider.computation()) .retry(RETRY_COUNT) .map(UserProfile::getEmail) .doOnError(e -> Timber.e(e, "Failed to fetch profile for user")) .onErrorReturnItem("") .toObservable(); } @Override public Observable<Boolean> isSavingEnabled() { return Observable.combineLatest( editedPreferredNameSubject, savedPreferredNameSubject, (edited, saved) -> !edited.equals(saved) ) .observeOn(schedulerProvider.computation()) .startWith(false) .distinctUntilChanged(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/developer_options/DefaultDeveloperOptionsViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.developer_options; import ai.rideos.android.common.R; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.fleets.FleetResolver; import ai.rideos.android.common.fleets.ResolvedFleet; import ai.rideos.android.common.interactors.FleetInteractor; import ai.rideos.android.common.model.FleetInfo; import ai.rideos.android.common.model.SingleSelectOptions; import ai.rideos.android.common.model.SingleSelectOptions.Option; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.user_storage.ApiEnvironment; import ai.rideos.android.common.user_storage.StorageKeys; import ai.rideos.android.common.user_storage.UserStorageReader; import ai.rideos.android.common.user_storage.UserStorageWriter; import ai.rideos.android.common.view.resources.ResourceProvider; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.subjects.BehaviorSubject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.OptionalInt; import java.util.stream.Collectors; import java.util.stream.IntStream; import timber.log.Timber; /** * DefaultDeveloperOptionsViewModel has a unique usage of interactors, because the interactor calls may change based * on the API env. Instead of supplying a interactor directly, an interactor supplier is required. The currently used * interactor is then updated whenever the API environment changes. */ public class DefaultDeveloperOptionsViewModel implements DeveloperOptionsViewModel { private static final int FLEET_RETRY_COUNT = 3; private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final BehaviorSubject<ApiEnvironment> currentEnv; private final FleetInteractor fleetInteractor; private final SchedulerProvider schedulerProvider; private final ResourceProvider resourceProvider; private final UserStorageReader userStorageReader; private final UserStorageWriter userStorageWriter; private final User user; private final ResolvedFleet resolvedFleet; public DefaultDeveloperOptionsViewModel(final FleetInteractor fleetInteractor, final UserStorageReader userStorageReader, final UserStorageWriter userStorageWriter, final ResourceProvider resourceProvider, final User user, final ResolvedFleet resolvedFleet) { this( fleetInteractor, userStorageReader, userStorageWriter, resourceProvider, user, resolvedFleet, new DefaultSchedulerProvider() ); } public DefaultDeveloperOptionsViewModel(final FleetInteractor fleetInteractor, final UserStorageReader userStorageReader, final UserStorageWriter userStorageWriter, final ResourceProvider resourceProvider, final User user, final ResolvedFleet resolvedFleet, final SchedulerProvider schedulerProvider) { this.userStorageReader = userStorageReader; this.userStorageWriter = userStorageWriter; this.resourceProvider = resourceProvider; this.schedulerProvider = schedulerProvider; this.user = user; this.resolvedFleet = resolvedFleet; this.fleetInteractor = fleetInteractor; currentEnv = BehaviorSubject.createDefault(getPreferredEnvironment()); } @Override public void selectFleetId(final Option<String> fleetId) { userStorageWriter.storeStringPreference(StorageKeys.FLEET_ID, fleetId.getValue()); } @Override public void selectEnvironment(final Option<ApiEnvironment> environment) { userStorageWriter.storeStringPreference(StorageKeys.RIDEOS_API_ENV, environment.getValue().getStoredName()); currentEnv.onNext(environment.getValue()); } @Override public Observable<String> getResolvedFleetId() { return resolvedFleet.observeFleetInfo() .map(fleetInfo -> { if (fleetInfo.getId().isEmpty()) { return resourceProvider.getString(R.string.default_fleet_id_option_display); } return fleetInfo.getId(); }); } @Override public Observable<String> getUserId() { return Observable.just(user.getId()); } @Override public Observable<SingleSelectOptions<String>> getFleetOptions() { // Update the values for the fleet id options if the environment changes return fleetInteractor.getFleets() .doOnError(e -> Timber.e(e, "Failed to retrieve fleet options")) .retry(FLEET_RETRY_COUNT) .onErrorReturnItem(Collections.emptyList()) .map(DefaultDeveloperOptionsViewModel::addAutomaticFleetOption) .map(availableFleets -> { // TODO use fleet resolver final OptionalInt fleetIndex = IntStream.range(0, availableFleets.size()) .filter(i -> availableFleets.get(i).getId().equals(getPreferredFleetId())) .findFirst(); if (fleetIndex.isPresent()) { return SingleSelectOptions.withSelection(getFleetIdOptions(availableFleets), fleetIndex.getAsInt()); } return SingleSelectOptions.withNoSelection(getFleetIdOptions(availableFleets)); }); } @Override public Observable<SingleSelectOptions<ApiEnvironment>> getEnvironmentOptions() { final List<ApiEnvironment> allowedEnvs = Arrays.asList(ApiEnvironment.values()); final int envIndex = getPreferredEnvironment().ordinal(); return Observable.just(SingleSelectOptions.withSelection(getEnvOptions(allowedEnvs), envIndex)); } private static List<FleetInfo> addAutomaticFleetOption(final List<FleetInfo> availableFleetIds) { // Default fleet id is an empty string. Add it if it doesn't exist final List<FleetInfo> fleetListCopy = new ArrayList<>(availableFleetIds); fleetListCopy.add(0, new FleetInfo(FleetResolver.AUTOMATIC_FLEET_ID)); return fleetListCopy; } private List<Option<String>> getFleetIdOptions(final List<FleetInfo> availableFleetIds) { return availableFleetIds.stream() .map(fleetInfo -> { if (fleetInfo.getId().isEmpty()) { return new Option<>(resourceProvider.getString(R.string.default_fleet_id_option_display), fleetInfo.getId()); } if (fleetInfo.getDisplayName().equals(fleetInfo.getId())) { return new Option<>(fleetInfo.getDisplayName(), fleetInfo.getId()); } return new Option<>( fleetInfo.getDisplayName() + " - " + fleetInfo.getId(), fleetInfo.getId() ); }) .collect(Collectors.toList()); } private List<Option<ApiEnvironment>> getEnvOptions(final List<ApiEnvironment> allowedEnvs) { return allowedEnvs.stream() .map(env -> { switch (env) { case DEVELOPMENT: return new Option<>(resourceProvider.getString(R.string.development_env_option), env); case STAGING: return new Option<>(resourceProvider.getString(R.string.staging_env_option), env); case PRODUCTION: return new Option<>(resourceProvider.getString(R.string.production_env_option), env); default: Timber.e("Unknown API env %s", env.getEndpoint()); return new Option<>(env.getEndpoint(), env); } }) .collect(Collectors.toList()); } private String getPreferredFleetId() { return userStorageReader.getStringPreference(StorageKeys.FLEET_ID); } private ApiEnvironment getPreferredEnvironment() { return ApiEnvironment.fromStoredNameOrThrow(userStorageReader.getStringPreference(StorageKeys.RIDEOS_API_ENV)); } @Override public void destroy() { compositeDisposable.dispose(); fleetInteractor.destroy(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/developer_options/DeveloperOptionsFragment.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.developer_options; import ai.rideos.android.common.R; import ai.rideos.android.common.app.dependency.CommonDependencyRegistry; import ai.rideos.android.common.app.menu_navigator.OpenMenuListener; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.fleets.ResolvedFleet; import ai.rideos.android.common.model.SingleSelectOptions; import ai.rideos.android.common.model.SingleSelectOptions.Option; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageReader; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageWriter; import ai.rideos.android.common.view.adapters.SingleSelectArrayAdapter; import ai.rideos.android.common.view.resources.AndroidResourceProvider; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toolbar; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import java.util.function.Consumer; import timber.log.Timber; public class DeveloperOptionsFragment extends Fragment { private CompositeDisposable compositeDisposable; private OpenMenuListener openMenuListener; private DeveloperOptionsViewModel viewModel; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final User user = User.get(getContext()); viewModel = new DefaultDeveloperOptionsViewModel( CommonDependencyRegistry.commonDependencyFactory().getFleetInteractor(getContext()), SharedPreferencesUserStorageReader.forContext(getContext()), SharedPreferencesUserStorageWriter.forContext(getContext()), AndroidResourceProvider.forContext(getContext()), user, ResolvedFleet.get() ); openMenuListener = (OpenMenuListener) getActivity(); } @Override public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return inflater.inflate(R.layout.developer_options, container, false); } @Override public void onStart() { super.onStart(); compositeDisposable = new CompositeDisposable(); final View optionsView = getView(); final Toolbar toolbar = optionsView.findViewById(R.id.title_bar); toolbar.setNavigationOnClickListener(click -> openMenuListener.openMenu()); final TextView fleetIdField = optionsView.findViewById(R.id.fleet_id_field); final TextView dispatchIdField = optionsView.findViewById(R.id.dispatch_id_field); final Spinner fleetSpinner = optionsView.findViewById(R.id.fleet_id_spinner); final Spinner envSpinner = optionsView.findViewById(R.id.rideos_env_spinner); compositeDisposable.addAll( viewModel.getFleetOptions() .observeOn(AndroidSchedulers.mainThread()) .subscribe(options -> setSpinnerOptions(options, viewModel::selectFleetId, fleetSpinner)), viewModel.getEnvironmentOptions() .observeOn(AndroidSchedulers.mainThread()) .subscribe(options -> setSpinnerOptions(options, viewModel::selectEnvironment, envSpinner)), viewModel.getResolvedFleetId() .observeOn(AndroidSchedulers.mainThread()) .subscribe(fleetIdField::setText), viewModel.getUserId() .observeOn(AndroidSchedulers.mainThread()) .subscribe(dispatchIdField::setText) ); setVersionName(optionsView); } private void setVersionName(final View view) { final TextView versionText = view.findViewById(R.id.version_name); final PackageManager manager = getContext().getPackageManager(); final PackageInfo info; try { info = manager.getPackageInfo( getContext().getPackageName(), 0); } catch (final NameNotFoundException e) { Timber.e(e, "Could not get package name"); return; } versionText.setText(getString(R.string.version_name_display, info.versionName)); } private <T> void setSpinnerOptions(final SingleSelectOptions<T> options, final Consumer<Option<T>> onSelect, final Spinner spinner) { final SingleSelectArrayAdapter<T> adapter = new SingleSelectArrayAdapter<>(getContext(), options); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(final AdapterView<?> parent, final View view, final int position, final long id) { onSelect.accept(adapter.getOptionAtPosition(position)); } @Override public void onNothingSelected(final AdapterView<?> parent) { } }); if (options.getSelectionIndex().isPresent()) { spinner.setSelection(options.getSelectionIndex().get()); } } @Override public void onStop() { super.onStop(); compositeDisposable.dispose(); } @Override public void onDestroy() { super.onDestroy(); viewModel.destroy(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/developer_options/DeveloperOptionsViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.developer_options; import ai.rideos.android.common.model.SingleSelectOptions; import ai.rideos.android.common.model.SingleSelectOptions.Option; import ai.rideos.android.common.user_storage.ApiEnvironment; import ai.rideos.android.common.viewmodel.ViewModel; import io.reactivex.Observable; public interface DeveloperOptionsViewModel extends ViewModel { void selectFleetId(final Option<String> fleetIdOption); void selectEnvironment(final Option<ApiEnvironment> environmentOption); Observable<String> getResolvedFleetId(); Observable<String> getUserId(); Observable<SingleSelectOptions<String>> getFleetOptions(); Observable<SingleSelectOptions<ApiEnvironment>> getEnvironmentOptions(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/DefaultMenuViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu; import ai.rideos.android.common.app.menu_navigator.LoggedOutListener; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.user_storage.UserStorageWriter; public class DefaultMenuViewModel implements MenuViewModel { private final User user; private final UserStorageWriter userStorageWriter; private final LoggedOutListener loggedOutListener; public DefaultMenuViewModel(final User user, final UserStorageWriter userStorageWriter, final LoggedOutListener loggedOutListener) { this.user = user; this.userStorageWriter = userStorageWriter; this.loggedOutListener = loggedOutListener; } @Override public void logout() { user.clearCredentials(); userStorageWriter.clearStorage(); loggedOutListener.loggedOut(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/MenuNavigator.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu; import ai.rideos.android.common.app.menu_navigator.MenuOptionFragmentRegistry; import ai.rideos.android.common.model.MenuOption; import ai.rideos.android.common.view.BackPropagator; import androidx.annotation.IdRes; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; public class MenuNavigator { private final MenuOptionFragmentRegistry registry; private final MenuPresenter menuViewController; private final FragmentManager fragmentManager; @IdRes private final int fragmentContainer; private MenuOption currentOption; public MenuNavigator(final MenuOptionFragmentRegistry registry, final MenuPresenter menuViewController, final FragmentManager fragmentManager, @IdRes final int fragmentContainer) { this.registry = registry; this.fragmentManager = fragmentManager; this.fragmentContainer = fragmentContainer; this.menuViewController = menuViewController; menuViewController.setSelectionListener(this::selectedMenuOption); menuViewController.setSelectedOption(registry.getHomeOption()); } /** * The back behavior implemented here does not use a simple back-stack. When a user navigates away from the home * option, the back button always goes back to the home option. For example, if the user navigates * home -> account settings -> developer settings -> account settings, then hits "back", they will just go home. * When back is clicked and the user is home, the system handles the back button. */ public void propagateBackSignal(final Runnable onBackNotHandled) { if (currentOption == null) { onBackNotHandled.run(); } if (currentOption.getId() == registry.getHomeOption().getId()) { final Fragment currentFragment = fragmentManager.findFragmentById(fragmentContainer); if (currentFragment instanceof BackPropagator) { ((BackPropagator) currentFragment).propagateBackSignal(); } else { onBackNotHandled.run(); } } else { menuViewController.setSelectedOption(registry.getHomeOption()); } } private void selectedMenuOption(final MenuOption menuOption) { if (currentOption != null && menuOption.getId() == currentOption.getId()) { return; } currentOption = menuOption; final Fragment fragmentToAdd = registry.getConstructorForOption(menuOption).construct(); fragmentManager.beginTransaction() .replace(fragmentContainer, fragmentToAdd) .commit(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/MenuPresenter.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu; import ai.rideos.android.common.R; import ai.rideos.android.common.app.menu_navigator.LoggedOutListener; import ai.rideos.android.common.app.menu_navigator.menu.navigation_header.NavigationHeaderPresenter; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.model.MenuOption; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageWriter; import ai.rideos.android.common.view.Presenter; import android.content.Context; import com.google.android.material.navigation.NavigationView; import androidx.drawerlayout.widget.DrawerLayout; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import java.util.List; // TODO we should probably rename this concept of "ViewController". Fragments are going to replace ViewControllers, but // Fragments create views of their own. We need some concept of a class that handles an already existing view. public class MenuPresenter implements Presenter<DrawerLayout> { private final NavigationHeaderPresenter headerViewController; private final MenuViewModel menuViewModel; private final List<MenuOption> menuOptions; private DrawerLayout drawerLayout; private MenuSelectionListener selectionListener = selection -> {}; public MenuPresenter(final Context context, final List<MenuOption> menuOptions, final LoggedOutListener loggedOutListener) { // For now the logic here does not require a view model, but if it becomes more complicated than this, one // should be made this.menuOptions = menuOptions; headerViewController = new NavigationHeaderPresenter(context); menuViewModel = new DefaultMenuViewModel( User.get(context), SharedPreferencesUserStorageWriter.forContext(context), loggedOutListener ); } /** * Slide the menu open. Should be called after the drawer layout is attached. */ public void openMenu() { if (drawerLayout != null) { setMenuVisibility(true, drawerLayout); } } /** * Slide the menu closed. Should be called after the drawer layout is attached. */ public void closeMenu() { if (drawerLayout != null) { setMenuVisibility(false, drawerLayout); } } public boolean isMenuOpen() { return drawerLayout.isDrawerOpen(Gravity.START); } public void setSelectedOption(final MenuOption optionToSelect) { final NavigationView navigationView = drawerLayout.findViewById(R.id.drawer_nav_view); navigationView.setCheckedItem(optionToSelect.getId()); navigationView.getMenu().performIdentifierAction(optionToSelect.getId(), 0); } public void setSelectionListener(final MenuSelectionListener selectionListener) { this.selectionListener = selectionListener; } @Override public void attach(final DrawerLayout drawerLayout) { this.drawerLayout = drawerLayout; final NavigationView navigationView = drawerLayout.findViewById(R.id.drawer_nav_view); final Menu menu = navigationView.getMenu(); setMenuOptions(menuOptions, menu); final Button signOutButton = navigationView.findViewById(R.id.sign_out_button); signOutButton.setOnClickListener(click -> menuViewModel.logout()); final View navigationHeaderView = navigationView.getHeaderView(0); headerViewController.attach(navigationHeaderView); } @Override public void detach() { headerViewController.detach(); } private void setMenuOptions(final List<MenuOption> menuOptions, final Menu menu) { menu.clear(); for (int i = 0; i < menuOptions.size(); i++) { final MenuOption option = menuOptions.get(i); final MenuItem viewItem = menu.add(0, option.getId(), i, option.getTitle()); viewItem.setCheckable(true); viewItem .setIcon(option.getDrawableIcon()) .setOnMenuItemClickListener(item -> { selectionListener.selectedMenuOption(option); closeMenu(); return true; }); } } private void setMenuVisibility(final boolean shouldShow, final DrawerLayout drawerLayout) { final boolean isDrawerAlreadyOpen = isMenuOpen(); if (shouldShow && !isDrawerAlreadyOpen) { drawerLayout.openDrawer(Gravity.START); } else if (!shouldShow && isDrawerAlreadyOpen) { drawerLayout.closeDrawers(); } } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/MenuSelectionListener.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu; import ai.rideos.android.common.model.MenuOption; public interface MenuSelectionListener { /** * Called when a menu item is selected. * @param menuOption - option selected */ void selectedMenuOption(final MenuOption menuOption); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/MenuViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu; public interface MenuViewModel { void logout(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/navigation_header/DefaultNavigationHeaderViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu.navigation_header; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.user_storage.StorageKeys; import ai.rideos.android.common.user_storage.UserStorageReader; import com.auth0.android.result.UserProfile; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.subjects.SingleSubject; import timber.log.Timber; public class DefaultNavigationHeaderViewModel implements NavigationHeaderViewModel { private static final int RETRY_COUNT = 3; private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final SingleSubject<UserProfile> userProfileSubject = SingleSubject.create(); private final SchedulerProvider schedulerProvider; private final UserStorageReader userStorageReader; public DefaultNavigationHeaderViewModel(final User user, final UserStorageReader userStorageReader) { this(user, userStorageReader, new DefaultSchedulerProvider()); } public DefaultNavigationHeaderViewModel(final User user, final UserStorageReader userStorageReader, final SchedulerProvider schedulerProvider) { this.userStorageReader = userStorageReader; this.schedulerProvider = schedulerProvider; compositeDisposable.add( user.fetchUserProfile() .observeOn(schedulerProvider.computation()) .retry(RETRY_COUNT) .subscribe(userProfileSubject::onSuccess, e -> Timber.e(e, "Failed to fetch user profile")) ); } @Override public Observable<String> getProfilePictureUrl() { return userProfileSubject.map(UserProfile::getPictureURL) .toObservable(); } @Override public Observable<String> getFullName() { return userStorageReader.observeStringPreference(StorageKeys.PREFERRED_NAME); } @Override public Observable<String> getEmail() { return userProfileSubject.map(UserProfile::getEmail) .toObservable(); } @Override public void destroy() { compositeDisposable.dispose(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/navigation_header/NavigationHeaderPresenter.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu.navigation_header; import ai.rideos.android.common.R; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageReader; import ai.rideos.android.common.view.Presenter; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; public class NavigationHeaderPresenter implements Presenter<View> { private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final NavigationHeaderViewModel viewModel; public NavigationHeaderPresenter(final Context context) { viewModel = new DefaultNavigationHeaderViewModel( User.get(context), SharedPreferencesUserStorageReader.forContext(context) ); } @Override public void attach(final View view) { final ImageView profileImage = view.findViewById(R.id.profile_image); final TextView fullNameText = view.findViewById(R.id.user_full_name); final TextView emailText = view.findViewById(R.id.user_email); compositeDisposable.addAll( viewModel.getFullName().observeOn(AndroidSchedulers.mainThread()).subscribe(fullNameText::setText), viewModel.getEmail().observeOn(AndroidSchedulers.mainThread()).subscribe(emailText::setText), viewModel.getProfilePictureUrl() .observeOn(AndroidSchedulers.mainThread()) .subscribe(url -> displayImageView(profileImage, url)) ); } private void displayImageView(final ImageView imageView, final String imageUrl) { Picasso.get() .load(imageUrl) .into(imageView); } @Override public void detach() { compositeDisposable.dispose(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/menu_navigator/menu/navigation_header/NavigationHeaderViewModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.menu_navigator.menu.navigation_header; import ai.rideos.android.common.viewmodel.ViewModel; import io.reactivex.Observable; public interface NavigationHeaderViewModel extends ViewModel { Observable<String> getProfilePictureUrl(); Observable<String> getFullName(); Observable<String> getEmail(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/progress/ProgressConnector.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.progress; import ai.rideos.android.common.view.errors.ErrorDialog; import ai.rideos.android.common.view.layout.LoadableDividerView; import ai.rideos.android.common.viewmodel.progress.ProgressSubject.ProgressState; import android.content.Context; import android.view.View; import android.widget.Button; import android.widget.Switch; import android.widget.TextView; import androidx.annotation.StringRes; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import java.util.ArrayList; import java.util.List; public class ProgressConnector { private final List<Runnable> onIdleActions; private final List<Runnable> onLoadingActions; private final List<Runnable> onSuccessActions; private final List<Runnable> onFailureActions; private ProgressConnector(final List<Runnable> onIdleActions, final List<Runnable> onLoadingActions, final List<Runnable> onSuccessActions, final List<Runnable> onFailureActions) { this.onIdleActions = onIdleActions; this.onLoadingActions = onLoadingActions; this.onSuccessActions = onSuccessActions; this.onFailureActions = onFailureActions; } public static Builder newBuilder() { return new Builder(); } public static class Builder { private final List<Runnable> idleActionsToBuild = new ArrayList<>(); private final List<Runnable> loadingActionsToBuild = new ArrayList<>(); private final List<Runnable> successActionsToBuild = new ArrayList<>(); private final List<Runnable> failureActionsToBuild = new ArrayList<>(); public ProgressConnector build() { return new ProgressConnector( idleActionsToBuild, loadingActionsToBuild, successActionsToBuild, failureActionsToBuild ); } public Builder showLoadableDividerWhenLoading(final LoadableDividerView loadableDividerView) { idleActionsToBuild.add(loadableDividerView::stopLoading); loadingActionsToBuild.add(loadableDividerView::startLoading); successActionsToBuild.add(loadableDividerView::stopLoading); failureActionsToBuild.add(loadableDividerView::stopLoading); return this; } public Builder disableButtonWhenLoading(final Button button) { idleActionsToBuild.add(() -> button.setEnabled(true)); loadingActionsToBuild.add(() -> button.setEnabled(false)); successActionsToBuild.add(() -> button.setEnabled(true)); failureActionsToBuild.add(() -> button.setEnabled(true)); return this; } public Builder disableButtonWhenLoadingOrSuccessful(final Button button) { idleActionsToBuild.add(() -> button.setEnabled(true)); loadingActionsToBuild.add(() -> button.setEnabled(false)); successActionsToBuild.add(() -> button.setEnabled(false)); failureActionsToBuild.add(() -> button.setEnabled(true)); return this; } public Builder toggleSwitchWhenLoading(final Switch switchToggle) { final boolean initialState = switchToggle.isChecked(); idleActionsToBuild.add(() -> switchToggle.setEnabled(true)); loadingActionsToBuild.add(() -> switchToggle.setEnabled(false)); successActionsToBuild.add(() -> switchToggle.setEnabled(false)); failureActionsToBuild.add(() -> { switchToggle.setChecked(initialState); switchToggle.setEnabled(true); }); return this; } public Builder showTextWhenLoading(final TextView textView, @StringRes final int loadingText) { idleActionsToBuild.add(() -> textView.setVisibility(View.GONE)); loadingActionsToBuild.add(() -> { textView.setVisibility(View.VISIBLE); textView.setText(loadingText); }); successActionsToBuild.add(() -> textView.setVisibility(View.GONE)); failureActionsToBuild.add(() -> textView.setVisibility(View.GONE)); return this; } public Builder alertOnFailure(final Context context, @StringRes final int failureMessage) { failureActionsToBuild.add(() -> new ErrorDialog(context).show(context.getString(failureMessage))); return this; } public Builder doOnSuccess(final Runnable onSuccess) { successActionsToBuild.add(onSuccess); return this; } } public Disposable connect(final Observable<ProgressState> progressState) { return progressState.subscribe(state -> { switch (state) { case IDLE: onIdleActions.forEach(Runnable::run); break; case LOADING: onLoadingActions.forEach(Runnable::run); break; case SUCCEEDED: onSuccessActions.forEach(Runnable::run); break; case FAILED: onFailureActions.forEach(Runnable::run); break; } }); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/app/push_notifications/PushNotificationManager.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.app.push_notifications; import ai.rideos.android.common.app.dependency.CommonDependencyRegistry; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.interactors.DeviceRegistryInteractor; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import android.content.Context; import androidx.annotation.VisibleForTesting; import com.google.firebase.iid.FirebaseInstanceId; import io.reactivex.Completable; import io.reactivex.Single; import java.io.IOException; import java.util.function.Supplier; /** * The PushNotificationManager handles initializing a user's device token with a backend device registry using * Firebase messaging. Note that a device token can be updated in the background if Firebase needs to invalidate * previous tokens. In this case, a service extending FirebaseMessagingService should listen for new tokens and * sync them with the backend accordingly. */ public class PushNotificationManager { private static final int DEFAULT_RETRY_COUNT = 3; private final User user; private final DeviceRegistryInteractor deviceRegistryInteractor; private final RegistrationMethod registrationMethod; private final Supplier<FirebaseInstanceId> firebaseInstanceSupplier; private final SchedulerProvider schedulerProvider; private final int retryCount; @VisibleForTesting interface RegistrationMethod { Completable register(final DeviceRegistryInteractor deviceRegistryInteractor, final String userId, final String deviceToken); } private PushNotificationManager(final User user, final DeviceRegistryInteractor deviceRegistryInteractor, final RegistrationMethod registrationMethod) { this( user, deviceRegistryInteractor, registrationMethod, FirebaseInstanceId::getInstance, new DefaultSchedulerProvider(), DEFAULT_RETRY_COUNT ); } @VisibleForTesting PushNotificationManager(final User user, final DeviceRegistryInteractor deviceRegistryInteractor, final RegistrationMethod registrationMethod, final Supplier<FirebaseInstanceId> firebaseInstanceSupplier, final SchedulerProvider schedulerProvider, final int retryCount) { this.user = user; this.deviceRegistryInteractor = deviceRegistryInteractor; this.registrationMethod = registrationMethod; this.firebaseInstanceSupplier = firebaseInstanceSupplier; this.schedulerProvider = schedulerProvider; this.retryCount = retryCount; } public static PushNotificationManager forRider(final Context context) { final User user = User.get(context); return new PushNotificationManager( user, CommonDependencyRegistry.commonDependencyFactory().getDeviceRegistryInteractor(context), DeviceRegistryInteractor::registerRiderDevice ); } public static PushNotificationManager forDriver(final Context context) { final User user = User.get(context); return new PushNotificationManager( user, CommonDependencyRegistry.commonDependencyFactory().getDeviceRegistryInteractor(context), DeviceRegistryInteractor::registerDriverDevice ); } public Completable requestTokenAndSync() { final String userId = user.getId(); if (userId.isEmpty()) { return Completable.error(new IllegalArgumentException("User is not logged in")); } return Single.<String>create( emitter -> firebaseInstanceSupplier.get().getInstanceId() .addOnCompleteListener(task -> { if (task.isSuccessful()) { emitter.onSuccess(task.getResult().getToken()); } else { emitter.onError(new IOException("Failed to get current device token")); } }) .addOnFailureListener(emitter::onError) ) .subscribeOn(schedulerProvider.io()) .flatMapCompletable(token -> registrationMethod.register(deviceRegistryInteractor, userId, token)) .retry(retryCount); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/Bundler.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import android.os.Bundle; import java.io.Serializable; /** * Helper class to create and read fragment bundles given args and a listener. */ public class Bundler<Args extends Serializable, Listener> { private static final String ARGUMENTS_KEY = "args"; private static final String LISTENER_KEY = "listener"; private final ViewController<Args, Listener> viewController; private ListenerRegistry listenerRegistry; public Bundler(final ViewController<Args, Listener> viewController, final ListenerRegistry listenerRegistry) { this.viewController = viewController; this.listenerRegistry = listenerRegistry; } /** * Write an argument and listener to a bundle. The argument is stored as a serializable object. The coordinator * is stored by its class name. */ public <I extends Listener> Bundle createBundle(final Args args, final I listenerInstance) { listenerRegistry.registerListenerForViewController(viewController, listenerInstance); final Bundle bundle = new Bundle(); bundle.putSerializable(ARGUMENTS_KEY, args); bundle.putString(LISTENER_KEY, listenerInstance.getClass().getName()); return bundle; } /** * Retrieve the listener from a bundle. The listener key is used to retrieve the class that will be listening * to the fragment. */ public Listener getListener(final Bundle bundle) { final String listener = bundle.getString(LISTENER_KEY); return listenerRegistry.getListenerForViewController(viewController, listener); } /** * Get the arguments from a bundle. */ public Args getArgs(final Bundle bundle) { return viewController.getTypes().getArgsType().cast(bundle.getSerializable(ARGUMENTS_KEY)); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/ControllerTypes.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import java.io.Serializable; public class ControllerTypes<Args extends Serializable, Listener> { private Class<Args> argsType; private Class<Listener> listenerType; public ControllerTypes(final Class<Args> argsType, final Class<Listener> listenerType) { this.argsType = argsType; this.listenerType = listenerType; } public Class<Args> getArgsType() { return argsType; } public Class<Listener> getListenerType() { return listenerType; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/Coordinator.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; /** * A coordinator is responsible for routing to child coordinators or view controllers. The coordinator is essentially * a composable state machine that takes in an input and produces an output when finished * @param <Input> input to state machine * // TODO @param <Output> output of state machine */ public interface Coordinator<Input> { /** * Initialize the coordinator by providing it an initial input and an output consumer. * @param input - input to state machine * // TODO @param onFinish - callback when state machine has finished */ void start(final Input input); /** * Stop the coordinator from running. */ void stop(); /** * Clean up any necessary resources like gRPC channels. */ void destroy(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/EmptyArg.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import java.io.Serializable; /** * EmptyArg can be used if a coordinator or view controller doesn't require an input argument. */ public class EmptyArg implements Serializable { public static EmptyArg create() { return new EmptyArg(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/FragmentNavigationController.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import android.os.Bundle; import androidx.annotation.IdRes; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import java.io.Serializable; public class FragmentNavigationController implements NavigationController { private final FragmentManager fragmentManager; @IdRes private final int fragmentContainer; private final ListenerRegistry listenerRegistry; public FragmentNavigationController(final FragmentManager fragmentManager, @IdRes final int fragmentContainer, final ListenerRegistry listenerRegistry) { this.fragmentManager = fragmentManager; this.fragmentContainer = fragmentContainer; this.listenerRegistry = listenerRegistry; } @Override public <Args extends Serializable, Listener, I extends Listener> void navigateTo( final ViewController<Args, Listener> viewController, final Args input, final I listenerInstance ) { if (!(viewController instanceof Fragment)) { throw new RuntimeException("Cannot display non-fragment"); } final Fragment fragmentToDisplay = (Fragment) viewController; final Bundler<Args, Listener> bundler = new Bundler<>(viewController, listenerRegistry); final Bundle args = bundler.createBundle(input, listenerInstance); fragmentToDisplay.setArguments(args); fragmentManager.beginTransaction() .replace(fragmentContainer, fragmentToDisplay) .commitAllowingStateLoss(); } @Override public ViewController getActiveViewController() { final Fragment fragment = fragmentManager.findFragmentById(fragmentContainer); if (fragment instanceof ViewController) { return (ViewController) fragment; } return null; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/FragmentViewController.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import android.os.Bundle; import androidx.fragment.app.Fragment; import java.io.Serializable; public abstract class FragmentViewController<Args extends Serializable, Listener> extends Fragment implements ViewController<Args, Listener> { private Args args; private Listener listener; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Bundle bundle = getArguments(); final Bundler<Args, Listener> bundler = getBundler(); args = bundler.getArgs(bundle); listener = bundler.getListener(bundle); } protected Args getArgs() { return args; } protected Listener getListener() { return listener; } private Bundler<Args, Listener> getBundler() { return new Bundler<>(this, ListenerRegistry.get()); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/ListenerRegistry.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import com.google.common.collect.MutableClassToInstanceMap; import java.util.HashMap; import java.util.Map; /** * ListenerRegistry registers global listeners by the parent class name. This is crucial for using Fragments because * they cannot take functions/listeners in as arguments. * * To use this, a Coordinator or View Model would register itself as a listener when the app first starts up. The listener is stored * and identified by the class name of the listener instance. When using Fragments, the navigation controller could then pass in the * class name identifier into the arguments of a Fragment. * * When the Fragment starts, it would then read the identifier of the listener and look it up in the registry. When a * Fragment is recycled, it would just re-read this identifier. Fragments can be re-used by different Coordinators by * passing in different identifiers of the listener. */ public class ListenerRegistry { private static final ListenerRegistry instance = new ListenerRegistry(); private Map<String, MutableClassToInstanceMap<Object>> listenerMap = new HashMap<>(); private ListenerRegistry() { } public static ListenerRegistry get() { return instance; } /** * Register a the listener for a view controller */ public <L, I extends L> void registerListenerForViewController(final ViewController<?, L> viewController, final I listenerInstance) { final MutableClassToInstanceMap<Object> classMap = getOrCreateClassMap(listenerInstance.getClass().getName()); classMap.put(viewController.getTypes().getListenerType(), listenerInstance); } /** * Get a listener for a particular view controller. */ public <L> L getListenerForViewController(final ViewController<?, L> viewController, final String id) { final MutableClassToInstanceMap<Object> classMap = getOrCreateClassMap(id); return classMap.getInstance(viewController.getTypes().getListenerType()); } private MutableClassToInstanceMap<Object> getOrCreateClassMap(final String id) { final MutableClassToInstanceMap<Object> classMap = listenerMap.get(id); if (classMap == null) { final MutableClassToInstanceMap<Object> createdMap = MutableClassToInstanceMap.create(); listenerMap.put(id, createdMap); return createdMap; } return classMap; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/NavigationController.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import java.io.Serializable; /** * NavigationController defines an interface for displaying view controllers. This can be used for Fragments or * view-based View Controllers. */ public interface NavigationController { <Args extends Serializable, Listener, I extends Listener> void navigateTo( final ViewController<Args, Listener> viewController, final Args input, final I listenerInstance); ViewController getActiveViewController(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/architecture/ViewController.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.architecture; import java.io.Serializable; /** * ViewController defines an object that takes in some arguments and calls the given listener as the user interacts * with a View. * @param <Args> - input to view controller * @param <Listener> - listener that is called after various UI events */ public interface ViewController<Args extends Serializable, Listener> { ControllerTypes<Args, Listener> getTypes(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/authentication/User.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.authentication; import static ai.rideos.android.common.user_storage.SharedPreferencesFileNames.USER_AUTH_FILE; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import android.content.Context; import android.content.SharedPreferences; import com.auth0.android.Auth0; import com.auth0.android.authentication.AuthenticationAPIClient; import com.auth0.android.authentication.storage.CredentialsManager; import com.auth0.android.authentication.storage.CredentialsManagerException; import com.auth0.android.authentication.storage.SharedPreferencesStorage; import com.auth0.android.callback.BaseCallback; import com.auth0.android.jwt.JWT; import com.auth0.android.result.Credentials; import com.auth0.android.result.UserProfile; import io.reactivex.Single; /** * User defines the app's current user. Currently the user can only be authenticated through Auth0 so this class * is not generalized with an interface. */ public class User { // Passenger ID is updated with JWT. It shouldn't be updated manually private static final String USER_ID_KEY = "user_id"; private final AuthenticationAPIClient apiClient; private final CredentialsManager credentialsManager; private final SharedPreferences sharedPreferences; private final SchedulerProvider schedulerProvider; private User(final Context context, final SchedulerProvider schedulerProvider) { this.schedulerProvider = schedulerProvider; final Auth0 auth0 = new Auth0(context); auth0.setOIDCConformant(true); apiClient = new AuthenticationAPIClient(auth0); // Shared preferences are used here to store login information (the user id) sharedPreferences = context.getSharedPreferences(USER_AUTH_FILE, Context.MODE_PRIVATE); credentialsManager = new CredentialsManager(apiClient, new SharedPreferencesStorage(context, USER_AUTH_FILE)); } /** * Retrieve the current user for this context. */ public static User get(final Context context) { return new User(context, new DefaultSchedulerProvider()); } /** * Update the auth0 authentication credentials for the user. */ public void updateCredentials(final Credentials credentials) { final JWT jwt = new JWT(credentials.getAccessToken()); credentialsManager.saveCredentials(credentials); // Store passenger for immediate lookup sharedPreferences.edit().putString(USER_ID_KEY, jwt.getSubject()).apply(); } /** * Check if the current user credentials are valid. */ public boolean isLoggedIn() { return credentialsManager.hasValidCredentials(); } /** * Get the user's id. */ public String getId() { return sharedPreferences.getString(USER_ID_KEY, ""); } /** * Fetch the user's token. This will refresh the current token if the old one has expired. */ public Single<String> fetchUserToken() { return Single.<String>create(emitter -> credentialsManager.getCredentials(new BaseCallback<Credentials, CredentialsManagerException>() { @Override public void onSuccess(final Credentials payload) { emitter.onSuccess(payload.getAccessToken()); } @Override public void onFailure(final CredentialsManagerException error) { emitter.onError(error); } }) ) .subscribeOn(schedulerProvider.io()); } /** * Fetch the user's profile. This will refresh the current token if the old one has expired. */ public Single<UserProfile> fetchUserProfile() { return fetchUserToken() .flatMap(token -> Single.<UserProfile>create(emitter -> { try { emitter.onSuccess(apiClient.userInfo(token).execute()); } catch (final Exception e) { emitter.onError(e); } }) .subscribeOn(schedulerProvider.io()) ); } /** * Clear the user's current credentials. */ public void clearCredentials() { credentialsManager.clearCredentials(); sharedPreferences.edit().clear().apply(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/connectivity/ConnectivityInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.connectivity; import io.reactivex.Observable; public interface ConnectivityInteractor { enum Status { CONNECTED, DISCONNECTED } Observable<Status> observeNetworkStatus(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/connectivity/ConnectivityMonitor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.connectivity; import ai.rideos.android.common.connectivity.ConnectivityInteractor.Status; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import android.view.View; import io.reactivex.disposables.CompositeDisposable; public class ConnectivityMonitor { private final ConnectivityInteractor connectivityInteractor; private final View banner; private final SchedulerProvider schedulerProvider; private CompositeDisposable compositeDisposable; public ConnectivityMonitor(final View banner) { this( new SocketConnectivityInteractor(), banner, new DefaultSchedulerProvider() ); } public ConnectivityMonitor(final ConnectivityInteractor connectivityInteractor, final View banner, final SchedulerProvider schedulerProvider) { this.connectivityInteractor = connectivityInteractor; this.banner = banner; this.schedulerProvider = schedulerProvider; } public void start() { compositeDisposable = new CompositeDisposable(); compositeDisposable.add( connectivityInteractor.observeNetworkStatus() .observeOn(schedulerProvider.mainThread()) .subscribe(status -> { if (status == Status.CONNECTED) { banner.setVisibility(View.GONE); } else { banner.setVisibility(View.VISIBLE); } }) ); } public void stop() { compositeDisposable.dispose(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/connectivity/SocketConnectivityInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.connectivity; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Single; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; public class SocketConnectivityInteractor implements ConnectivityInteractor { private static final Settings DEFAULT_SETTINGS = new Settings(2000, 1000, 3); public static class Settings { private final int checkIntervalMs; private final int connectivityTimeoutMs; private final int retryCount; public Settings(final int checkIntervalMs, final int connectivityTimeoutMs, final int retryCount) { this.checkIntervalMs = checkIntervalMs; this.connectivityTimeoutMs = connectivityTimeoutMs; this.retryCount = retryCount; } } private final SocketAddress socketAddress; private final Settings settings; private final SchedulerProvider schedulerProvider; private final Supplier<Socket> socketSupplier; public SocketConnectivityInteractor() { // By default check Google's public DNS this(new InetSocketAddress("8.8.8.8", 53), DEFAULT_SETTINGS, new DefaultSchedulerProvider(), Socket::new); } public SocketConnectivityInteractor(final SocketAddress socketAddress, final Settings settings, final SchedulerProvider schedulerProvider, final Supplier<Socket> socketSupplier) { this.socketAddress = socketAddress; this.schedulerProvider = schedulerProvider; this.settings = settings; this.socketSupplier = socketSupplier; } @Override public Observable<Status> observeNetworkStatus() { return Flowable.interval(settings.checkIntervalMs, TimeUnit.MILLISECONDS, schedulerProvider.io()) .startWith(0L) .onBackpressureDrop() .flatMap(i -> testConnection().toFlowable()) .toObservable(); } private Single<Status> testConnection() { return Single.<Status>create(emitter -> { final Socket socket = socketSupplier.get(); socket.connect(socketAddress, settings.connectivityTimeoutMs); socket.close(); emitter.onSuccess(Status.CONNECTED); }) .subscribeOn(schedulerProvider.io()) .retry(settings.retryCount) .onErrorReturnItem(Status.DISCONNECTED); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/AndroidPermissionsChecker.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; import android.Manifest.permission; import android.content.Context; import android.content.pm.PackageManager; import androidx.core.app.ActivityCompat; public class AndroidPermissionsChecker implements PermissionsChecker { private final Context context; public AndroidPermissionsChecker(final Context context) { this.context = context; } @Override public boolean areLocationPermissionsGranted() { return ActivityCompat.checkSelfPermission(context, permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/DeviceLocator.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; import ai.rideos.android.common.model.LocationAndHeading; import io.reactivex.Observable; import io.reactivex.Single; public interface DeviceLocator { Observable<LocationAndHeading> observeCurrentLocation(final int pollIntervalMillis); /** * Rather than polling, return the last recorded location of the device. * @return a single coordinate */ Single<LocationAndHeading> getLastKnownLocation(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/FusedLocationDeviceLocator.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.model.LocationAndHeading; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.utils.Locations; import android.annotation.SuppressLint; import android.content.Context; import android.location.Location; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Single; import io.reactivex.disposables.Disposables; import java.util.function.Supplier; /** * FusedLocationDeviceLocator uses the FusedLocationProviderClient built into Android to request updates about the * device's current location. To do this, it uses a custom observable. When this observable is subscribed to, it requests * location updates and emits them. When this subscription is disposed of, the updates stop. */ public class FusedLocationDeviceLocator implements DeviceLocator { private final Supplier<FusedLocationProviderClient> clientSupplier; private final PermissionsChecker permissionsChecker; private final SchedulerProvider schedulerProvider; public FusedLocationDeviceLocator(final Context context) { this( () -> LocationServices.getFusedLocationProviderClient(context), new AndroidPermissionsChecker(context), new DefaultSchedulerProvider() ); } public FusedLocationDeviceLocator(final Supplier<FusedLocationProviderClient> clientSupplier, final PermissionsChecker permissionsChecker, final SchedulerProvider schedulerProvider) { this.clientSupplier = clientSupplier; this.permissionsChecker = permissionsChecker; this.schedulerProvider = schedulerProvider; } @Override public Observable<LocationAndHeading> observeCurrentLocation(final int pollIntervalMillis) { final LocationRequest locationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(pollIntervalMillis); return Observable.create(new FusedLocationObservableOnSubscribe(locationRequest)) .subscribeOn(schedulerProvider.mainThread()) .observeOn(schedulerProvider.computation()) // Use the last known heading in the even that the current location contains no heading. // To do this, this Rx pipeline scans locations using an empty initial seed with no heading. Whenever it // receives a new location, it checks if the new location has a heading. If it does, it uses it. If it // doesn't, it uses the previous location's heading. The initial seed is discarded and ignored .scan( // Empty initial seed new LocationAndHeading(new LatLng(0, 0), 0f), (oldLocation, newLocation) -> new LocationAndHeading( Locations.getLatLngFromAndroidLocation(newLocation), Locations.getHeadingFromAndroidLocationOrDefault(newLocation, oldLocation.getHeading()) ) ) // Discard initial seed .skip(1); } @SuppressLint("MissingPermission") // This is checked in PermissionsChecker @Override public Single<LocationAndHeading> getLastKnownLocation() { if (!permissionsChecker.areLocationPermissionsGranted()) { return Single.error(new PermissionsNotGrantedException("Location permissions not granted")); } return Single.<Location>create( emitter -> clientSupplier.get().getLastLocation() .addOnSuccessListener(emitter::onSuccess) .addOnFailureListener(emitter::onError) ) .subscribeOn(schedulerProvider.mainThread()) .observeOn(schedulerProvider.computation()) .map(location -> new LocationAndHeading( Locations.getLatLngFromAndroidLocation(location), Locations.getHeadingFromAndroidLocationOrDefault(location, 0f) )); } /** * Create an ObservableOnSubscribe, which starts emitting items when subscribed to. In this case, when the observable * is subscribed to, location updates begin and when disposed, the locations stop. */ private class FusedLocationObservableOnSubscribe implements ObservableOnSubscribe<Location> { private final FusedLocationProviderClient locationClient; private final LocationRequest locationRequest; FusedLocationObservableOnSubscribe(final LocationRequest locationRequest) { this.locationClient = clientSupplier.get(); this.locationRequest = locationRequest; } @SuppressLint("MissingPermission") // This is checked in PermissionsChecker @Override public void subscribe(final ObservableEmitter<Location> emitter) { // Check for permissions and emit an error if location access is not permitted. Permissions should be granted // in the view. This should be checked only when subscribed so we can get the most updated information // about the device permissions. if (!permissionsChecker.areLocationPermissionsGranted()) { emitter.onError(new PermissionsNotGrantedException("Location permissions not granted")); } final LocationCallback callback = new DefaultLocationCallback(emitter); locationClient.requestLocationUpdates(locationRequest, callback, null); emitter.setDisposable(Disposables.fromAction(() -> dispose(callback))); } private void dispose(final LocationCallback listener) { locationClient.removeLocationUpdates(listener); } } /** * Callback that emits a LatLng coordinate whenever onLocationResult is called. */ private static class DefaultLocationCallback extends LocationCallback { private final ObservableEmitter<Location> emitter; DefaultLocationCallback(final ObservableEmitter<Location> emitter) { this.emitter = emitter; } @Override public void onLocationResult(final LocationResult result) { final Location lastLocation = result.getLastLocation(); if (lastLocation != null) { this.emitter.onNext(lastLocation); } } } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/InputMethodManagerKeyboardManager.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; public class InputMethodManagerKeyboardManager implements KeyboardManager { private final InputMethodManager methodManager; private final View viewInFocus; /** * Create a keyboard manager controlled by InputMethodManager. * @param context - Application context * @param viewInFocus - The view currently receiving input. This is important for showing the keyboard because * it must be in focus. Hiding the keyboard can take in any view. */ public InputMethodManagerKeyboardManager(final Context context, final View viewInFocus) { methodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); this.viewInFocus = viewInFocus; } @Override public void showKeyboard() { methodManager.showSoftInput(viewInFocus, InputMethodManager.SHOW_IMPLICIT); } @Override public void hideKeyboard() { methodManager.hideSoftInputFromWindow(viewInFocus.getWindowToken(), 0); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/KeyboardManager.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; public interface KeyboardManager { void hideKeyboard(); void showKeyboard(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/PermissionsChecker.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; /** * PermissionsChecker describes methods for checking device permissions at runtime. This is mostly useful for mocking * situations where permissions are or are not granted. */ public interface PermissionsChecker { boolean areLocationPermissionsGranted(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/device/PermissionsNotGrantedException.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.device; public class PermissionsNotGrantedException extends Exception { public PermissionsNotGrantedException(final String message) { super(message); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/fleets/DefaultFleetResolver.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.fleets; import ai.rideos.android.common.device.DeviceLocator; import ai.rideos.android.common.interactors.FleetInteractor; import ai.rideos.android.common.location.DistanceCalculator; import ai.rideos.android.common.location.HaversineDistanceCalculator; import ai.rideos.android.common.model.FleetInfo; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import androidx.core.util.Pair; import io.reactivex.Observable; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.stream.Collectors; import java.util.stream.IntStream; import timber.log.Timber; public class DefaultFleetResolver implements FleetResolver { private static final int RETRY_COUNT = 3; private final FleetInteractor fleetInteractor; private final DeviceLocator deviceLocator; private final FleetInfo defaultFleetInfo; private final DistanceCalculator distanceCalculator; private final SchedulerProvider schedulerProvider; public DefaultFleetResolver(final FleetInteractor fleetInteractor, final DeviceLocator deviceLocator, final String defaultFleetId) { this( fleetInteractor, deviceLocator, defaultFleetId, new HaversineDistanceCalculator(), new DefaultSchedulerProvider() ); } public DefaultFleetResolver(final FleetInteractor fleetInteractor, final DeviceLocator deviceLocator, final String defaultFleetId, final DistanceCalculator distanceCalculator, final SchedulerProvider schedulerProvider) { this.fleetInteractor = fleetInteractor; this.deviceLocator = deviceLocator; this.defaultFleetInfo = new FleetInfo(defaultFleetId); this.distanceCalculator = distanceCalculator; this.schedulerProvider = schedulerProvider; } @Override public Observable<FleetInfo> resolveFleet(final Observable<String> storedFleetId) { return storedFleetId.observeOn(schedulerProvider.computation()) .flatMap(fleetId -> { if (fleetId.equals(AUTOMATIC_FLEET_ID)) { return resolveAutomatic(); } else { return getAvailableFleets() .flatMap(fleets -> { final OptionalInt fleetIndex = IntStream.range(0, fleets.size()) .filter(i -> fleets.get(i).getId().equals(fleetId)) .findFirst(); if (fleetIndex.isPresent()) { return Observable.just(fleets.get(fleetIndex.getAsInt())); } return resolveAutomatic(); }); } }); } @Override public void shutDown() { fleetInteractor.destroy(); } private Observable<List<FleetInfo>> getAvailableFleets() { return fleetInteractor.getFleets() .observeOn(schedulerProvider.computation()) .retry(RETRY_COUNT) .doOnError(e -> Timber.e(e, "Failed to resolve fleets")) .onErrorReturnItem(Collections.singletonList(defaultFleetInfo)); } private Observable<FleetInfo> resolveAutomatic() { return Observable.combineLatest( getAvailableFleets(), deviceLocator.getLastKnownLocation().toObservable(), Pair::create ) .map(fleetsAndLocation -> { final List<FleetInfo> fleets = fleetsAndLocation.first; final LatLng location = fleetsAndLocation.second.getLatLng(); return findClosestFleet(fleets, location).orElse(defaultFleetInfo); }); } private Optional<FleetInfo> findClosestFleet(final List<FleetInfo> fleets, final LatLng currentLocation) { final List<FleetInfo> locatableFleets = fleets.stream() .filter(fleetInfo -> fleetInfo.getCenter().isPresent()) .collect(Collectors.toList()); final Comparator<FleetInfo> comparator = (fleet0, fleet1) -> Double.compare( distanceCalculator.getDistanceInMeters(currentLocation, fleet0.getCenter().get()), distanceCalculator.getDistanceInMeters(currentLocation, fleet1.getCenter().get()) ); // Try to find closest non-phantom fleets first final List<FleetInfo> nonPhantomFleets = locatableFleets.stream() .filter(fleet -> !fleet.isPhantom()) .sorted(comparator) .collect(Collectors.toList()); if (nonPhantomFleets.size() > 0) { return Optional.of(nonPhantomFleets.get(0)); } // If all fleets are phantom fleets, return the closest one. final List<FleetInfo> phantomFleets = locatableFleets.stream() .filter(FleetInfo::isPhantom) .sorted(comparator) .collect(Collectors.toList()); if (phantomFleets.size() > 0) { return Optional.of(phantomFleets.get(0)); } return Optional.empty(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/fleets/FleetResolver.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.fleets; import ai.rideos.android.common.model.FleetInfo; import io.reactivex.Observable; /** * FleetResolver reads the user's preferred fleet id and resolves the fleet information. */ public interface FleetResolver { String AUTOMATIC_FLEET_ID = "Automatic"; Observable<FleetInfo> resolveFleet(final Observable<String> storedFleetId); void shutDown(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/fleets/ResolvedFleet.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.fleets; import ai.rideos.android.common.model.FleetInfo; import io.reactivex.Observable; import io.reactivex.subjects.BehaviorSubject; /** * Singleton class that stores the resolved fleet information. */ public class ResolvedFleet { private static final ResolvedFleet INSTANCE = new ResolvedFleet(); private final BehaviorSubject<FleetInfo> resolvedFleetInfoSubject = BehaviorSubject.create(); private ResolvedFleet() { } public static ResolvedFleet get() { return INSTANCE; } public Observable<FleetInfo> observeFleetInfo() { return resolvedFleetInfoSubject.distinctUntilChanged(); } public void setFleetInfo(final FleetInfo fleetInfo) { resolvedFleetInfoSubject.onNext(fleetInfo); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/grpc/ChannelProvider.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.grpc; import ai.rideos.android.common.user_storage.ApiEnvironment; import ai.rideos.android.common.user_storage.SharedPreferencesUserStorageReader; import ai.rideos.android.common.user_storage.StorageKeys; import ai.rideos.android.common.user_storage.UserStorageReader; import android.content.Context; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.function.Supplier; public class ChannelProvider { public static Supplier<ManagedChannel> getChannelSupplierForContext(final Context context) { final UserStorageReader userStorage = SharedPreferencesUserStorageReader.forContext(context); return getChannelSupplierForUser(userStorage); } public static Supplier<ManagedChannel> getChannelSupplierForUser(final UserStorageReader userStorage) { final ApiEnvironment environment = ApiEnvironment.fromStoredNameOrThrow( userStorage.getStringPreference(StorageKeys.RIDEOS_API_ENV) ); return () -> ManagedChannelBuilder .forTarget(environment.getEndpoint()) .useTransportSecurity() .build(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/grpc/Stubs.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.grpc; import io.grpc.Metadata; import io.grpc.stub.AbstractStub; import io.grpc.stub.MetadataUtils; public class Stubs { private static final Metadata.Key<String> AUTHORIZATION_METADATA_KEY = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER); private static final String AUTHORIZATION_PREFIX = "Bearer "; public static <T extends AbstractStub<T>> T withAuthorization(final T stub, final String token) { final Metadata authHeaders = new Metadata(); authHeaders.put(AUTHORIZATION_METADATA_KEY, AUTHORIZATION_PREFIX + token); return MetadataUtils.attachHeaders(stub, authHeaders); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/DefaultDeviceRegistryInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.api.ride_hail_notification.v1.Device.SetDriverDeviceInfoRequest; import ai.rideos.api.ride_hail_notification.v1.Device.SetRiderDeviceInfoRequest; import ai.rideos.api.ride_hail_notification.v1.DeviceRegistryServiceGrpc; import ai.rideos.api.ride_hail_notification.v1.DeviceRegistryServiceGrpc.DeviceRegistryServiceFutureStub; import ai.rideos.api.ride_hail_notification.v1.NotificationCommon.DeviceInfo; import ai.rideos.api.ride_hail_notification.v1.NotificationCommon.DeviceInfo.AndroidDevice; import io.grpc.ManagedChannel; import io.reactivex.Completable; import java.util.function.Supplier; public class DefaultDeviceRegistryInteractor extends GrpcServerInteractor<DeviceRegistryServiceFutureStub> implements DeviceRegistryInteractor { public DefaultDeviceRegistryInteractor(final Supplier<ManagedChannel> channelSupplier, final User user) { super(DeviceRegistryServiceGrpc::newFutureStub, channelSupplier, user, new DefaultSchedulerProvider()); } public Completable registerRiderDevice(final String riderId, final String token) { return fetchAuthorizedStubAndExecute(stub -> stub.setRiderDeviceInfo( SetRiderDeviceInfoRequest.newBuilder() .setDeviceInfo( DeviceInfo.newBuilder() .setAndroidDevice(AndroidDevice.newBuilder().setToken(token)) ) .setRiderId(riderId) .build() )) .ignoreElements(); } public Completable registerDriverDevice(final String vehicleId, final String token) { return fetchAuthorizedStubAndExecute(stub -> stub.setDriverDeviceInfo( SetDriverDeviceInfoRequest.newBuilder() .setDeviceInfo( DeviceInfo.newBuilder() .setAndroidDevice(AndroidDevice.newBuilder().setToken(token)) ) .setVehicleId(vehicleId) .build() )) .ignoreElements(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/DefaultFleetInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.model.FleetInfo; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.api.ride_hail_operations.v1.RideHailOperations.GetFleetsRequest; import ai.rideos.api.ride_hail_operations.v1.RideHailOperations.GetFleetsResponse; import ai.rideos.api.ride_hail_operations.v1.RideHailOperationsServiceGrpc; import ai.rideos.api.ride_hail_operations.v1.RideHailOperationsServiceGrpc.RideHailOperationsServiceFutureStub; import io.grpc.ManagedChannel; import io.reactivex.Observable; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; public class DefaultFleetInteractor extends GrpcServerInteractor<RideHailOperationsServiceFutureStub> implements FleetInteractor { public DefaultFleetInteractor(final Supplier<ManagedChannel> channelSupplier, final User user) { super(RideHailOperationsServiceGrpc::newFutureStub, channelSupplier, user, new DefaultSchedulerProvider()); } @Override public Observable<List<FleetInfo>> getFleets() { return fetchAuthorizedStubAndExecute(stub -> stub.getFleets(GetFleetsRequest.getDefaultInstance())) .map(GetFleetsResponse::getFleetList) .map(fleetList -> fleetList.stream() .map(fleet -> new FleetInfo(fleet.getId())) .collect(Collectors.toList()) ); } public void destroy() { shutDown(); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/DeviceRegistryInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import io.reactivex.Completable; public interface DeviceRegistryInteractor { Completable registerRiderDevice(final String riderId, final String token); Completable registerDriverDevice(final String vehicleId, final String token); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/FleetInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.model.FleetInfo; import io.reactivex.Observable; import java.util.List; public interface FleetInteractor { Observable<List<FleetInfo>> getFleets(); void destroy(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/GeocodeInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.model.NamedTaskLocation; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.reactive.Result; import io.reactivex.Observable; import java.util.List; public interface GeocodeInteractor { /** * Given a lat/lng coordinate, return a list of possible locations nearest the coordinate. * @param latLng - coordinate to search for * @param maxResults - maximum locations to return (use 1 if you just want the nearest location) * @return list of possible locations */ Observable<List<NamedTaskLocation>> getReverseGeocodeResults(final LatLng latLng, final int maxResults); /** * Given a lat/lng coordinate, return the best matching location, containing the most displayable information. * @param latLng - coordinate to search for * @return best matching location, or Result.failure if none found */ Observable<Result<NamedTaskLocation>> getBestReverseGeocodeResult(final LatLng latLng); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/GrpcServerInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.grpc.Stubs; import ai.rideos.android.common.reactive.SchedulerProvider; import io.grpc.ManagedChannel; import io.grpc.stub.AbstractStub; import io.reactivex.Observable; import io.reactivex.Single; import java.util.concurrent.Future; import java.util.function.Supplier; /** * GrpcServerInteractor handles several common functions for interactors that require calling to a gRPC server * including authenticating calls and transforming futures to observables. * @param <T> Stub type */ public abstract class GrpcServerInteractor<T extends AbstractStub<T>> { // Supplies a new stub given a channel public interface StubSupplier<T> { T getStub(final ManagedChannel channel); } // Calls a method on a stub that returns a Future public interface FutureStubMethod<T, R> { Future<R> call(final T stub); } private final StubSupplier<T> stubSupplier; private final ManagedChannel channel; private final User user; private final SchedulerProvider schedulerProvider; protected GrpcServerInteractor(final StubSupplier<T> stubSupplier, final Supplier<ManagedChannel> channelSupplier, final User user, final SchedulerProvider schedulerProvider) { this.stubSupplier = stubSupplier; this.channel = channelSupplier.get(); this.user = user; this.schedulerProvider = schedulerProvider; } public void shutDown() { channel.shutdownNow(); } protected SchedulerProvider getSchedulerProvider() { return schedulerProvider; } protected Single<T> fetchAuthorizedStub() { return user.fetchUserToken() .map(userToken -> Stubs.withAuthorization( stubSupplier.getStub(channel), userToken )) // Stub will be fetched on io thread .subscribeOn(schedulerProvider.io()); } protected <R> Observable<R> fetchAuthorizedStubAndExecute(final FutureStubMethod<T, R> grpcMethod) { return fetchAuthorizedStub() // grpc method will be run on io thread because it is blocking .flatMapObservable(stub -> Observable.fromFuture(grpcMethod.call(stub), schedulerProvider.io())); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/LocationAutocompleteInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.model.LocationAutocompleteResult; import ai.rideos.android.common.model.NamedTaskLocation; import ai.rideos.android.common.model.map.LatLngBounds; import io.reactivex.Observable; import java.util.List; public interface LocationAutocompleteInteractor { /** * Given some incomplete text, e.g. "221 m" return suggestions based on the text and bounded proximity. * @param searchText - query to search for a location * @param bounds - bounds to bias the search towards * @return list of autocomplete results, or empty if there are no results */ Observable<List<LocationAutocompleteResult>> getAutocompleteResults(final String searchText, final LatLngBounds bounds); /** * Given an autocomplete result, return the geocoded location that includes a display name and coordinates. * @param result - autocomplete result returned from getAutocompleteResults * @return geocoded location model */ Observable<NamedTaskLocation> getLocationFromAutocompleteResult(final LocationAutocompleteResult result); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/RideOsRouteInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.authentication.User; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.model.LocationAndHeading; import ai.rideos.android.common.model.RouteInfoModel; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.utils.Locations; import ai.rideos.android.common.utils.Polylines.GMSPolylineDecoder; import ai.rideos.android.common.utils.Polylines.PolylineDecoder; import ai.rideos.api.path.v2.PathProto.Leg; import ai.rideos.api.path.v2.PathProto.PathRequest; import ai.rideos.api.path.v2.PathProto.PathRequest.GeometryFormat; import ai.rideos.api.path.v2.PathProto.PathResponse; import ai.rideos.api.path.v2.PathProto.Waypoint; import ai.rideos.api.path.v2.PathServiceGrpc; import ai.rideos.api.path.v2.PathServiceGrpc.PathServiceFutureStub; import com.google.protobuf.FloatValue; import io.grpc.ManagedChannel; import io.reactivex.Observable; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import timber.log.Timber; public class RideOsRouteInteractor extends GrpcServerInteractor<PathServiceFutureStub> implements RouteInteractor { private final PolylineDecoder polylineDecoder; public static class RouteException extends Exception { public RouteException(final String message) { super(message); } } public RideOsRouteInteractor(final Supplier<ManagedChannel> channelSupplier, final User user) { this(channelSupplier, user, new GMSPolylineDecoder()); } public RideOsRouteInteractor(final Supplier<ManagedChannel> channelSupplier, final User user, final PolylineDecoder polylineDecoder) { super(PathServiceGrpc::newFutureStub, channelSupplier, user, new DefaultSchedulerProvider()); this.polylineDecoder = polylineDecoder; } @Override public Observable<RouteInfoModel> getRoute(final LatLng origin, final LatLng destination) { return fetchAuthorizedStubAndExecute(pathServiceStub -> pathServiceStub.getPath( PathRequest.newBuilder() .addAllWaypoints(Arrays.asList( Waypoint.newBuilder() .setPosition(Locations.toRideOsPosition(origin)) .build(), Waypoint.newBuilder() .setPosition(Locations.toRideOsPosition(destination)) .build() )) .setGeometryFormat(GeometryFormat.POLYLINE) .build() )) .map(this::getRouteFromPathResponse); } @Override public Observable<RouteInfoModel> getRoute(final LocationAndHeading origin, final LocationAndHeading destination) { return fetchAuthorizedStubAndExecute(pathServiceStub -> pathServiceStub.getPath( PathRequest.newBuilder() .addAllWaypoints(Arrays.asList( Waypoint.newBuilder() .setHeading(FloatValue.newBuilder().setValue(origin.getHeading())) .setPosition(Locations.toRideOsPosition(origin.getLatLng())) .build(), Waypoint.newBuilder() .setHeading(FloatValue.newBuilder().setValue(destination.getHeading())) .setPosition(Locations.toRideOsPosition(destination.getLatLng())) .build() )) .setGeometryFormat(GeometryFormat.POLYLINE) .build() )) .map(this::getRouteFromPathResponse); } @Override public Observable<List<RouteInfoModel>> getRouteForWaypoints(final List<LatLng> waypoints) { return fetchAuthorizedStubAndExecute(pathServiceStub -> pathServiceStub.getPath( PathRequest.newBuilder() .addAllWaypoints( waypoints.stream() .map(latLng -> Waypoint.newBuilder() .setPosition(Locations.toRideOsPosition(latLng)) .build() ) .collect(Collectors.toList()) ) .setGeometryFormat(GeometryFormat.POLYLINE) .build() )) .map(pathResponse -> { if (pathResponse.getPathsCount() < 1 || pathResponse.getPaths(0).getLegsCount() != waypoints.size() - 1) { throw new RouteException("Route not found"); } return pathResponse.getPaths(0).getLegsList().stream() .map(this::getRouteFromLeg) .collect(Collectors.toList()); }); } private RouteInfoModel getRouteFromPathResponse(final PathResponse pathResponse) throws RouteException { if (pathResponse.getPathsCount() > 0 && pathResponse.getPaths(0).getLegsCount() > 0) { final Leg leg = pathResponse.getPaths(0).getLegs(0); return getRouteFromLeg(leg); } throw new RouteException("Route not found"); } private RouteInfoModel getRouteFromLeg(final Leg leg) { return new RouteInfoModel( polylineDecoder.decode(leg.getPolyline()), leg.getTravelTime().getSeconds() * 1000, leg.getDistance() ); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/RouteInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.model.LocationAndHeading; import ai.rideos.android.common.model.RouteInfoModel; import io.reactivex.Observable; import java.util.List; public interface RouteInteractor { Observable<RouteInfoModel> getRoute(final LatLng origin, final LatLng destination); Observable<RouteInfoModel> getRoute(final LocationAndHeading origin, final LocationAndHeading destination); Observable<List<RouteInfoModel>> getRouteForWaypoints(final List<LatLng> waypoints); /** * Used to clean up any channels or resources used when connecting to backend services. After this is called, * the interactor cannot operate */ void shutDown(); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/mapbox/MapboxApiInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors.mapbox; import ai.rideos.android.common.app.CommonMetadataKeys; import ai.rideos.android.common.app.MetadataReader; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import android.content.Context; import androidx.annotation.NonNull; import com.mapbox.api.directions.v5.DirectionsCriteria; import com.mapbox.api.directions.v5.models.DirectionsResponse; import com.mapbox.api.directions.v5.models.DirectionsRoute; import com.mapbox.api.matching.v5.MapboxMapMatching; import com.mapbox.api.matching.v5.models.MapMatchingResponse; import com.mapbox.geojson.Point; import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute; import io.reactivex.Observable; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * MapboxDirectionsInteractor can be used to call into Mapbox's APIs for map matching and directions. There is no need * generalizing this, since it needs to use Mapbox's internal objects. */ public class MapboxApiInteractor { private final Supplier<MapboxMapMatching.Builder> authenticatedMatchingBuilder; private final Supplier<NavigationRoute.Builder> authenticatedNavBuilder; private final SchedulerProvider schedulerProvider; public MapboxApiInteractor(final Context context) { // TODO this(context, new MetadataReader(context).getStringMetadata(CommonMetadataKeys.MAPBOX_TOKEN_KEY).getOrThrow()); } public MapboxApiInteractor(final Context context, final String mapBoxApiToken) { this( () -> MapboxMapMatching.builder().accessToken(mapBoxApiToken), () -> NavigationRoute.builder(context).accessToken(mapBoxApiToken), new DefaultSchedulerProvider() ); } /** * Mapbox doesn't supply a "client" object, so authentication needs to happen every time on the builder. For the sake * of dependency injection, suppliers of the builders that are pre-authenticated are given to this constructor. */ public MapboxApiInteractor(final Supplier<MapboxMapMatching.Builder> authenticatedMatchingBuilder, final Supplier<NavigationRoute.Builder> authenticatedNavBuilder, final SchedulerProvider schedulerProvider) { this.authenticatedMatchingBuilder = authenticatedMatchingBuilder; this.authenticatedNavBuilder = authenticatedNavBuilder; this.schedulerProvider = schedulerProvider; } public Observable<DirectionsRoute> matchCoordinatesToDirections(final List<Point> coordinates) { final MapboxMapMatching matching = authenticatedMatchingBuilder.get() .coordinates(coordinates) .waypointIndices(0, coordinates.size() - 1) .steps(true) .voiceInstructions(true) .bannerInstructions(true) .profile(DirectionsCriteria.PROFILE_DRIVING) .build(); return Observable.<DirectionsRoute>create(emitter -> matching.enqueueCall(new Callback<MapMatchingResponse>() { @Override public void onResponse(@NonNull final Call<MapMatchingResponse> call, @NonNull final Response<MapMatchingResponse> response) { if (response.isSuccessful() && response.body() != null && !response.body().matchings().isEmpty()) { final DirectionsRoute route = response.body().matchings().get(0).toDirectionRoute(); emitter.onNext(route); } else { emitter.onError(new MapboxException( "Received match response but was unsuccessful: " + response.toString() )); } } @Override public void onFailure(@NonNull final Call<MapMatchingResponse> call, @NonNull final Throwable t) { emitter.onError(t); } })) .subscribeOn(schedulerProvider.io()); } public Observable<DirectionsRoute> getDirectionsToDestination(final Point origin, final Point destination) { return getDirectionsToDestination(origin, destination, Collections.emptyList()); } public Observable<DirectionsRoute> getDirectionsToDestination(final Point origin, final Point destination, final List<Point> waypoints) { final NavigationRoute.Builder routeBuilder = authenticatedNavBuilder.get() .origin(origin) .destination(destination); for (final Point waypoint : waypoints) { routeBuilder.addWaypoint(waypoint); } final NavigationRoute route = routeBuilder.build(); return Observable.<DirectionsRoute>create(emitter -> route.getRoute(new Callback<DirectionsResponse>() { @Override public void onResponse(@NonNull final Call<DirectionsResponse> call, @NonNull final Response<DirectionsResponse> response) { if (response.isSuccessful() && response.body() != null && !response.body().routes().isEmpty()) { emitter.onNext(response.body().routes().get(0)); } else { emitter.onError(new MapboxException( "Received route response but was unsuccessful: " + response.toString() )); } } @Override public void onFailure(@NonNull final Call<DirectionsResponse> call, @NonNull final Throwable t) { emitter.onError(t); } })) .subscribeOn(schedulerProvider.io()); } public static class MapboxException extends Exception { public MapboxException(final String message) { super(message); } } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/interactors/mapbox/MapboxRouteInteractor.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.interactors.mapbox; import static com.mapbox.core.constants.Constants.PRECISION_6; import ai.rideos.android.common.interactors.RideOsRouteInteractor.RouteException; import ai.rideos.android.common.interactors.RouteInteractor; import ai.rideos.android.common.model.LatLng; import ai.rideos.android.common.model.LocationAndHeading; import ai.rideos.android.common.model.RouteInfoModel; import ai.rideos.android.common.reactive.SchedulerProvider; import ai.rideos.android.common.reactive.SchedulerProviders.DefaultSchedulerProvider; import ai.rideos.android.common.utils.Polylines.PolylineDecoder; import android.content.Context; import com.mapbox.api.directions.v5.models.DirectionsRoute; import com.mapbox.api.directions.v5.models.LegStep; import com.mapbox.api.directions.v5.models.RouteLeg; import com.mapbox.geojson.LineString; import com.mapbox.geojson.Point; import io.reactivex.Observable; import java.util.List; import java.util.stream.Collectors; public class MapboxRouteInteractor implements RouteInteractor { private final MapboxApiInteractor apiInteractor; private final SchedulerProvider schedulerProvider; private final PolylineDecoder polyLineDecoder; public MapboxRouteInteractor(final Context context) { this(new MapboxApiInteractor(context), new MapboxPolylineDecoder(), new DefaultSchedulerProvider()); } public MapboxRouteInteractor(final MapboxApiInteractor apiInteractor, final PolylineDecoder polyLineDecoder, final SchedulerProvider schedulerProvider) { this.apiInteractor = apiInteractor; this.polyLineDecoder = polyLineDecoder; this.schedulerProvider = schedulerProvider; } @Override public Observable<RouteInfoModel> getRoute(final LatLng origin, final LatLng destination) { return apiInteractor.getDirectionsToDestination( Point.fromLngLat(origin.getLongitude(), origin.getLatitude()), Point.fromLngLat(destination.getLongitude(), destination.getLatitude()) ) .observeOn(schedulerProvider.computation()) .map(directionsRoute -> { validateDirectionsRoute(directionsRoute); return new RouteInfoModel( polyLineDecoder.decode(directionsRoute.geometry()), (long) (directionsRoute.duration() * 1000), directionsRoute.distance() ); }); } @Override public Observable<RouteInfoModel> getRoute(final LocationAndHeading origin, final LocationAndHeading destination) { return getRoute(origin.getLatLng(), destination.getLatLng()); } @Override public Observable<List<RouteInfoModel>> getRouteForWaypoints(final List<LatLng> waypoints) { if (waypoints.size() < 2) { return Observable.error(new RouteException("There must be at least 2 waypoints to call this API")); } final LatLng origin = waypoints.get(0); final LatLng destination = waypoints.get(waypoints.size() - 1); final List<Point> intermediatePoints = waypoints.subList(1, waypoints.size() - 1).stream() .map(latLng -> Point.fromLngLat(latLng.getLongitude(), latLng.getLatitude())) .collect(Collectors.toList()); return apiInteractor.getDirectionsToDestination( Point.fromLngLat(origin.getLongitude(), origin.getLatitude()), Point.fromLngLat(destination.getLongitude(), destination.getLatitude()), intermediatePoints ) .observeOn(schedulerProvider.computation()) .map(directionsRoute -> { validateWaypointRoute(directionsRoute, waypoints); return directionsRoute.legs().stream() .map(leg -> { // Individual route legs don't have geometry, but the steps do. So, get the geometry from each // step, decode to waypoints, and flatten into a list. final List<LatLng> legRoute = leg.steps().stream() .map(LegStep::geometry) .map(polyLineDecoder::decode) .flatMap(List::stream) .collect(Collectors.toList()); return new RouteInfoModel( legRoute, (long) (leg.duration() * 1000), leg.distance() ); }) .collect(Collectors.toList()); }); } private static void validateDirectionsRoute(final DirectionsRoute directionsRoute) throws RouteException { if (directionsRoute.geometry() == null || directionsRoute.duration() == null || directionsRoute.distance() == null) { throw new RouteException("Invalid route"); } } private static void validateWaypointRoute(final DirectionsRoute directionsRoute, final List<LatLng> waypoints) throws RouteException { if (directionsRoute.legs() == null || directionsRoute.legs().size() != waypoints.size() - 1) { throw new RouteException("# legs returned by Mapbox doesn't match the number of waypoints"); } for (final RouteLeg leg : directionsRoute.legs()) { validateLeg(leg); } } private static void validateLeg(final RouteLeg leg) throws RouteException { if (leg.steps() == null || leg.steps().size() == 0 || leg.duration() == null || leg.distance() == null) { throw new RouteException("Invalid leg"); } } @Override public void shutDown() { } /** * Mapbox orders its coordinates lng,lat so use their decoder for polylines. */ private static class MapboxPolylineDecoder implements PolylineDecoder { @Override public List<LatLng> decode(final String polyline) { // Mapbox returns the geometry in lng,lat order so we have to use their polyline decoder return LineString.fromPolyline(polyline, PRECISION_6).coordinates().stream() .map(point -> new LatLng(point.latitude(), point.longitude())) .collect(Collectors.toList()); } } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/location/Distance.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.location; import ai.rideos.android.common.model.LatLng; import android.location.Location; public class Distance { private static double MILES_IN_METER = 0.000621371192; public static double metersToMiles(final double meters) { return meters * MILES_IN_METER; } public static double milesToMeters(final double miles) { return miles / MILES_IN_METER; } public static double haversineDistanceMeters(final LatLng latLng0, final LatLng latLng1) { // We can use Android Location to easily calculate distances Location location0 = new Location(""); Location location1 = new Location(""); location0.setLatitude(latLng0.getLatitude()); location0.setLongitude(latLng0.getLongitude()); location1.setLatitude(latLng1.getLatitude()); location1.setLongitude(latLng1.getLongitude()); return location0.distanceTo(location1); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/location/DistanceCalculator.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.location; import ai.rideos.android.common.model.LatLng; public interface DistanceCalculator { double getDistanceInMeters(final LatLng origin, final LatLng destination); }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/location/HaversineDistanceCalculator.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.location; import ai.rideos.android.common.model.LatLng; import android.location.Location; public class HaversineDistanceCalculator implements DistanceCalculator { @Override public double getDistanceInMeters(final LatLng origin, final LatLng destination) { Location originLocation = new Location(""); Location destinationLocation = new Location(""); originLocation.setLatitude(origin.getLatitude()); originLocation.setLongitude(origin.getLongitude()); destinationLocation.setLatitude(destination.getLatitude()); destinationLocation.setLongitude(destination.getLongitude()); return originLocation.distanceTo(destinationLocation); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/FleetInfo.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; import androidx.annotation.Nullable; import java.util.Objects; import java.util.Optional; public class FleetInfo { private final String id; private final String displayName; @Nullable private final LatLng center; private final boolean isPhantom; public FleetInfo(final String id) { this(id, id, null, false); } public FleetInfo(final String id, final String displayName, @Nullable final LatLng center, final boolean isPhantom) { this.id = id; this.displayName = displayName; this.center = center; this.isPhantom = isPhantom; } public String getId() { return id; } public String getDisplayName() { return displayName; } public Optional<LatLng> getCenter() { return Optional.ofNullable(center); } public boolean isPhantom() { return isPhantom; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof FleetInfo)) { return false; } final FleetInfo otherModel = (FleetInfo) other; return id.equals(otherModel.id) && displayName.equals(otherModel.displayName) && Objects.equals(center, otherModel.center) && isPhantom == otherModel.isPhantom; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/LatLng.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; import java.io.Serializable; public class LatLng implements Serializable { private final double latitude; private final double longitude; public LatLng(final double latitude, final double longitude) { this.latitude = latitude; this.longitude = longitude; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof LatLng)) { return false; } final LatLng otherModel = (LatLng) other; return Double.compare(latitude, otherModel.latitude) == 0 && Double.compare(longitude, otherModel.longitude) == 0; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/LocationAndHeading.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; public class LocationAndHeading { private final LatLng latLng; // Defined as degrees clock-wise from true north private final float heading; public LocationAndHeading(final LatLng latLng, final float heading) { this.latLng = latLng; this.heading = heading; } public LatLng getLatLng() { return latLng; } public float getHeading() { return heading; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof LocationAndHeading)) { return false; } final LocationAndHeading otherModel = (LocationAndHeading) other; return latLng.equals(otherModel.latLng) && heading == otherModel.heading; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/LocationAutocompleteResult.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; public class LocationAutocompleteResult { private final String primaryName; private final String secondaryName; private final String id; public LocationAutocompleteResult(final String primaryName, final String id) { this(primaryName, "", id); } public LocationAutocompleteResult(final String primaryName, final String secondaryName, final String id) { this.primaryName = primaryName; this.secondaryName = secondaryName; this.id = id; } public String getPrimaryName() { return primaryName; } public String getSecondaryName() { return secondaryName; } public String getId() { return id; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof LocationAutocompleteResult)) { return false; } final LocationAutocompleteResult otherModel = (LocationAutocompleteResult) other; return primaryName.equals(otherModel.primaryName) && secondaryName.equals(otherModel.secondaryName) && id.equals(otherModel.id); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/LoginAction.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; public enum LoginAction { DISPLAY_LOGIN, REQUEST_PERMISSIONS, DISPLAY_NEXT_SCREEN }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/MenuOption.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; /** * MenuOption is a model representing a row in a menu. The row can have title text and a displayable icon. It also * needs to be tagged with some sort of ID to identify a row when it's selected. */ public class MenuOption { private final int id; private final String title; private final int drawableIcon; public MenuOption(final int id, final String title, final int drawableIcon) { this.id = id; this.title = title; this.drawableIcon = drawableIcon; } public int getId() { return id; } public String getTitle() { return title; } public int getDrawableIcon() { return drawableIcon; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof MenuOption)) { return false; } final MenuOption otherModel = (MenuOption) other; return id == otherModel.id && title.equals(otherModel.title) && drawableIcon == otherModel.drawableIcon; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/NamedTaskLocation.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; import java.io.Serializable; /** * NamedTaskLocation wraps TaskLocation with a displayable name that could come from reverse geocoding or another source. */ public class NamedTaskLocation implements Serializable { private final String displayName; private final TaskLocation location; // Helper constructor for the common case that the task location is just a lat/lng coordinate public NamedTaskLocation(final String displayName, final LatLng latLng) { this(displayName, new TaskLocation(latLng)); } public NamedTaskLocation(final String displayName, final TaskLocation location) { this.displayName = displayName; this.location = location; } public String getDisplayName() { return displayName; } public TaskLocation getLocation() { return location; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof NamedTaskLocation)) { return false; } final NamedTaskLocation otherModel = (NamedTaskLocation) other; return displayName.equals(otherModel.getDisplayName()) && location.equals(otherModel.getLocation()); } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/RouteInfoModel.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; import java.util.List; public class RouteInfoModel { private final List<LatLng> route; private final long travelTimeMillis; private final double travelDistanceMeters; public RouteInfoModel(final List<LatLng> route, final long travelTimeMillis, final double travelDistanceMeters) { this.route = route; this.travelTimeMillis = travelTimeMillis; this.travelDistanceMeters = travelDistanceMeters; } public List<LatLng> getRoute() { return route; } public long getTravelTimeMillis() { return travelTimeMillis; } public double getTravelDistanceMeters() { return travelDistanceMeters; } @Override public boolean equals(final Object other) { if (other == this) { return true; } if (!(other instanceof RouteInfoModel)) { return false; } final RouteInfoModel otherModel = (RouteInfoModel) other; return route.equals(otherModel.getRoute()) && travelTimeMillis == otherModel.travelTimeMillis && travelDistanceMeters == otherModel.travelDistanceMeters; } }
0
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common
java-sources/ai/rideos/sdk/sdk-android-common/1.0.2/ai/rideos/android/common/model/SingleSelectOptions.java
/** * Copyright 2018-2019 rideOS, 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. */ package ai.rideos.android.common.model; import java.util.List; import java.util.Optional; import timber.log.Timber; /** * SingleSelectOptions models the state of a dropdown menu, where one option can be chosen at a time. * It has a list of options with values and display names, and the index of the selected option (if it exists). * @param <T> Type of value stored in an option */ public class SingleSelectOptions<T> { private final static int NO_SELECTION_INDEX = -1; public static class Option<T> { private final String displayText; private final T value; public Option(final String displayText, final T value) { this.displayText = displayText; this.value = value; } public String getDisplayText() { return displayText; } public T getValue() { return value; } } private final List<Option<T>> options; private final int selectedOptionIndex; /** * Create a SingleSelectOptions with one option selected. This method will log an error if the index is out of range. */ public static <T> SingleSelectOptions<T> withSelection(final List<Option<T>> options, final int selectedOptionIndex) { if (selectedOptionIndex < 0 || selectedOptionIndex >= options.size()) { Timber.e("Invalid selection index %d for options size %d", selectedOptionIndex, options.size()); return SingleSelectOptions.withNoSelection(options); } return new SingleSelectOptions<>(options, selectedOptionIndex); } /** * Create a SingleSelectOptions with no options selected. */ public static <T> SingleSelectOptions<T> withNoSelection(final List<Option<T>> options) { return new SingleSelectOptions<>(options, NO_SELECTION_INDEX); } private SingleSelectOptions(final List<Option<T>> options, final int selectedOptionIndex) { this.options = options; this.selectedOptionIndex = selectedOptionIndex; } public List<Option<T>> getOptions() { return options; } /** * Return the selected index, if it exists. */ public Optional<Integer> getSelectionIndex() { if (selectedOptionIndex == NO_SELECTION_INDEX) { return Optional.empty(); } return Optional.of(selectedOptionIndex); } }