Skip to content

Commit

Permalink
Merge pull request #21 from djkovrik/fix/new_auth
Browse files Browse the repository at this point in the history
Authorization fix
  • Loading branch information
djkovrik authored Nov 6, 2019
2 parents f2b7480 + 5cf0284 commit 58b9fc2
Show file tree
Hide file tree
Showing 19 changed files with 267 additions and 38 deletions.
3 changes: 2 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ dependencies {
implementation presentationDependencies.retrofitJspoonConverter
implementation presentationDependencies.okhttp
implementation presentationDependencies.okhttpInterceptor
implementation presentationDependencies.cookies
implementation presentationDependencies.picasso
implementation presentationDependencies.glide
implementation presentationDependencies.glideOkHttp3
Expand Down Expand Up @@ -156,4 +157,4 @@ configurations.all() {
resolutionStrategy.force "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.gms.google-services'
32 changes: 32 additions & 0 deletions app/src/main/java/com/sedsoftware/yaptalker/YapTalkerApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.provider.Settings
import android.widget.ImageView
import com.facebook.stetho.Stetho
import com.mikepenz.community_material_typeface_library.CommunityMaterial
Expand All @@ -22,15 +23,44 @@ import dagger.android.HasActivityInjector
import ru.noties.markwon.SpannableConfiguration
import ru.noties.markwon.spans.SpannableTheme
import timber.log.Timber
import java.security.MessageDigest
import javax.inject.Inject

@Suppress("ConstantConditionIf")
class YapTalkerApp : Application(), HasActivityInjector {

companion object {
private const val NAV_DRAWER_AVATAR_PADDING = 16
private const val YAP_API_KEY = "JanW23Sh"

private lateinit var appContext: Context

fun getMd5(): String =
md5(String.format("%s:%s", YAP_API_KEY, getUdid()))

fun getUdid(): String =
Settings.System.getString(appContext.contentResolver, "android_id")

fun getAppVersion(): String = "0.998"

private fun md5(str: String): String {
val digest = MessageDigest.getInstance("MD5")
digest.update(str.toByteArray())
val messageDigest = digest.digest()
val hexString = StringBuffer()

for (i in 0 until messageDigest.size) {
var hex = Integer.toHexString(0xFF and messageDigest[i].toInt())
while (hex.length < 2)
hex = "0$hex"
hexString.append(hex)
}
return hexString.toString()
}
}



@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

Expand All @@ -41,6 +71,8 @@ class YapTalkerApp : Application(), HasActivityInjector {
return
}

appContext = this

LeakCanary.install(this)

DaggerAppComponent.builder().create(this).inject(this)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.sedsoftware.yaptalker.common.converter.HashSearchConverterFactory
import com.sedsoftware.yaptalker.common.converter.VideoTokenConverterFactory
import com.sedsoftware.yaptalker.data.network.external.AppUpdatesChecker
import com.sedsoftware.yaptalker.data.network.external.GitHubLoader
import com.sedsoftware.yaptalker.data.network.site.YapApi
import com.sedsoftware.yaptalker.data.network.site.YapLoader
import com.sedsoftware.yaptalker.data.network.site.YapSearchIdLoader
import com.sedsoftware.yaptalker.data.network.site.YapVideoTokenLoader
Expand Down Expand Up @@ -37,6 +38,7 @@ class NetworkModule {
private const val YAP_FILES_BASE_URL = "http://www.yapfiles.ru/"
private const val YAP_API_BASE_URL = "http://api.yapfiles.ru/"
private const val VK_API_BASE_URL = "https://api.vk.com/"
private const val YAP_API_BASE_URL_NEW = "https://api.yaplakal.com/"

// Misc
private const val YAP_FILE_HASH_MARKER = "md5="
Expand Down Expand Up @@ -65,6 +67,18 @@ class NetworkModule {
.build()
.create(YapLoader::class.java)

@Singleton
@Provides
fun provideYapApi(@Named("apiClient") okHttpClient: OkHttpClient): YapApi =
Retrofit.Builder()
.baseUrl(YAP_API_BASE_URL_NEW)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.build()
.create(YapApi::class.java)

@Singleton
@Provides
fun provideYapSearchIdLoader(@Named("siteClient") okHttpClient: OkHttpClient): YapSearchIdLoader =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.sedsoftware.yaptalker.di.module.network

import android.content.Context
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.sedsoftware.yaptalker.BuildConfig
import com.sedsoftware.yaptalker.di.module.network.interceptors.CustomHeadersInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.HeaderAndParamManipulationInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.HtmlFixerInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.SaveReceivedCookiesInterceptor
import com.sedsoftware.yaptalker.di.module.network.interceptors.SendSavedCookiesInterceptor
Expand All @@ -26,18 +30,48 @@ class HttpClientsModule {
HttpLoggingInterceptor().setLevel(loggingLevel)
}

@Provides
@Singleton
fun provideSetCookieCache(): SetCookieCache =
SetCookieCache()

@Provides
@Singleton
fun provideSharedPrefsCookiePersistor(context: Context): SharedPrefsCookiePersistor =
SharedPrefsCookiePersistor(context)

@Provides
@Singleton
fun providePersistentCookieJar(
cache: SetCookieCache,
persistor: SharedPrefsCookiePersistor
): PersistentCookieJar =
PersistentCookieJar(cache, persistor)

@Singleton
@Provides
@Named("siteClient")
fun provideSiteClient(cookieStorage: CookieStorage): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(HtmlFixerInterceptor())
.addInterceptor(CustomHeadersInterceptor())
.addInterceptor(HeaderAndParamManipulationInterceptor())
.addInterceptor(SaveReceivedCookiesInterceptor(cookieStorage))
.addInterceptor(SendSavedCookiesInterceptor(cookieStorage))
.addInterceptor(loggingInterceptor)
.build()

@Singleton
@Provides
@Named("apiClient")
fun provideApiClient(jar: PersistentCookieJar): OkHttpClient {
val builder = OkHttpClient.Builder()
builder.addInterceptor(HeaderAndParamManipulationInterceptor())
builder.addInterceptor(loggingInterceptor)
builder.cookieJar(jar)
builder.cache(null)
return builder.build()
}

@Singleton
@Provides
@Named("fileClient")
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.sedsoftware.yaptalker.di.module.network.interceptors

import android.os.Build
import android.os.Build.VERSION
import com.sedsoftware.yaptalker.YapTalkerApp
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Request
import okhttp3.Response
import java.io.IOException


class HeaderAndParamManipulationInterceptor : Interceptor {

@Throws(IOException::class)
override fun intercept(chain: Chain): Response {
var request: Request
val request2 = chain.request()
val newBuilder = request2.url().newBuilder()
val str = "md5"
if (request2.url().queryParameter(str) == null) {
newBuilder.addQueryParameter(str, YapTalkerApp.getMd5())
}
val str2 = "appVersion"
if (request2.url().queryParameter(str2) == null) {
newBuilder.addQueryParameter(str2, YapTalkerApp.getAppVersion())
}
val str3 = "type"
if (request2.url().queryParameter(str3) == null) {
newBuilder.addQueryParameter(str3, "json")
}
val str4 = "Connection"
if (request2.header(str4) == null) {
request = request2.newBuilder().addHeader(str4, "keep-alive").url(newBuilder.build()).build()
} else {
request = request2.newBuilder().url(newBuilder.build()).build()
}
val str5 = "User-Agent"
if (request.header(str5) == null) {
val sb = StringBuilder()
sb.append("Yaplakal/0.998 (Android ")
sb.append(VERSION.RELEASE)
sb.append("; ")
sb.append(Build.MANUFACTURER)
val str6 = ","
sb.append(str6)
sb.append(Build.MODEL)
sb.append(str6)
sb.append(VERSION.SDK_INT)
sb.append(")")
request = request.newBuilder().addHeader(str5, sb.toString()).url(newBuilder.build()).build()
}
val str7 = "http-udid"
return if (request.header(str7) != null) {
chain.proceed(request)
} else chain.proceed(request.newBuilder().header(str7, YapTalkerApp.getUdid()).build())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,9 @@ class AuthorizationFragment : BaseFragment(), AuthorizationView {
RxView.clicks(button_sign_in)
.autoDisposable(event(FragmentLifecycle.DESTROY))
.subscribe({
presenter.performLoginAttempt(
presenter.performLoginAttemptNew(
authorization_login.text.toString(),
authorization_password.text.toString(),
authorization_anonymous.isChecked
authorization_password.text.toString()
)
}, { e: Throwable ->
e.message?.let { showErrorMessage(it) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,21 @@ class AuthorizationPresenter @Inject constructor(
})
}

fun performLoginAttemptNew(userLogin: String, userPassword: String) {
authorizationInteractor
.sendSignInRequestNew(login = userLogin, password = userPassword)
.observeOn(schedulers.ui())
.autoDisposable(event(PresenterLifecycle.DESTROY))
.subscribe({
viewState.showLoginSuccessMessage()
Timber.i("Sign In request completed, start site preferences loading...")
loadSitePreferences()
}, { e: Throwable ->
Timber.e("Error: ${e.message}")
viewState.showLoginErrorMessage()
})
}

private fun loadSitePreferences() {
authorizationInteractor
.getSiteUserPreferences()
Expand Down
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ apply from: 'buildsystem/dependencies.gradle'

// Versioning convention from ribot:
// Major -> Millions, Minor -> Thousands, Bugfix -> Hundreds. E.g 1.3.72 == 1,003,072
// Current: 1.0.4 (001,000,004)
// Current: 1.0.5 (001,000,005)
def versionMajor = 1
def versionMinor = 0
def versionPatch = 4
def versionPatch = 5

allprojects {
ext {
Expand Down Expand Up @@ -74,4 +74,4 @@ detekt {
output = "$projectDir/build/reports/detekt.xml"
baseline = "$projectDir/build/reports/baseline.xml"
}
}
}
3 changes: 3 additions & 0 deletions buildsystem/dependencies.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ ext {
final JSPOON_VERSION = "1.3.2"
final OKHTTP_VERSION = "3.13.1"
final GSON_VERSION = "2.8.5"
final COOKIE_JAR_VERSION = "v1.0.1"

// UI
final MATERIAL_VALUES_VERSION = "1.1.1"
Expand Down Expand Up @@ -120,6 +121,8 @@ ext {
recyclerView : "androidx.recyclerview:recyclerview:$RECYCLERVIEW_VERSION",
constraintLayout : "androidx.constraintlayout:constraintlayout:$CONSTRAINT_LAYOUT_VERSION",

cookies : "com.github.franmontiel:PersistentCookieJar:$COOKIE_JAR_VERSION",

dagger : "com.google.dagger:dagger:$DAGGER_VERSION",
daggerCompiler : "com.google.dagger:dagger-compiler:$DAGGER_VERSION",
daggerAndroid : "com.google.dagger:dagger-android:$DAGGER_VERSION",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.sedsoftware.yaptalker.data.network.site

import com.sedsoftware.yaptalker.data.network.site.model.FeedResult
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query

interface YapApi {

@GET("action/login")
fun authUser(
@Query("name") name: String,
@Query("password") password: String
): Single<FeedResult>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sedsoftware.yaptalker.data.network.site.model

import com.google.gson.annotations.SerializedName

data class FeedResult(
@SerializedName("code")
var code: Int? = null,
@SerializedName("global")
var global: GlobalParam? = null,
@SerializedName("offset")
var offset: String? = null,
@SerializedName("user")
var user: UserSmall? = null
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sedsoftware.yaptalker.data.network.site.model

import com.google.gson.annotations.SerializedName

data class GlobalParam(
@SerializedName("api_version")
var apiVersion: String? = null,
@SerializedName("app_version")
var appVersion: String? = null,
@SerializedName("generation_time")
var generationTime: Double? = null,
@SerializedName("server_time")
var serverTime: String? = null
)
Loading

0 comments on commit 58b9fc2

Please sign in to comment.