Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for custom headers #320

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"formatVersion": 1,
"database": {
"version": 10,
"identityHash": "58cb958cdb09f054c27673d1de7f26d0",
"identityHash": "2b970b61706696dcd6c142bf22c89d37",
"entities": [
{
"tableName": "queue",
Expand Down Expand Up @@ -230,7 +230,7 @@
},
{
"tableName": "server",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `server_name` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `address` TEXT NOT NULL, `local_address` TEXT, `timestamp` INTEGER NOT NULL, `low_security` INTEGER NOT NULL DEFAULT false, PRIMARY KEY(`id`))",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `server_name` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `address` TEXT NOT NULL, `local_address` TEXT, `timestamp` INTEGER NOT NULL, `low_security` INTEGER NOT NULL DEFAULT false, `custom_headers` TEXT, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "serverId",
Expand Down Expand Up @@ -280,6 +280,12 @@
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "false"
},
{
"fieldPath": "customHeaders",
"columnName": "custom_headers",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
Expand Down Expand Up @@ -1059,7 +1065,7 @@
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '58cb958cdb09f054c27673d1de7f26d0')"
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2b970b61706696dcd6c142bf22c89d37')"
]
}
}
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,4 @@
android:value="true" />
</service>
</application>
</manifest>
</manifest>
4 changes: 4 additions & 0 deletions app/src/main/java/com/cappielloantonio/tempo/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import com.cappielloantonio.tempo.subsonic.SubsonicPreferences;
import com.cappielloantonio.tempo.util.Preferences;

import java.util.Map;

public class App extends Application {
private static App instance;
private static Context context;
Expand Down Expand Up @@ -98,11 +100,13 @@ private static SubsonicPreferences getSubsonicPreferences() {
String token = Preferences.getToken();
String salt = Preferences.getSalt();
boolean isLowSecurity = Preferences.isLowScurity();
Map<String, String> customHeaders = Preferences.getCustomHeaders();

SubsonicPreferences preferences = new SubsonicPreferences();
preferences.setServerUrl(server);
preferences.setUsername(username);
preferences.setAuthentication(password, token, salt, isLowSecurity);
preferences.setCustomHeaders(customHeaders);

return preferences;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import com.cappielloantonio.tempo.App;
import com.cappielloantonio.tempo.database.converter.DateConverters;
import com.cappielloantonio.tempo.database.converter.MapTypeConverter;
import com.cappielloantonio.tempo.database.dao.ChronologyDao;
import com.cappielloantonio.tempo.database.dao.DownloadDao;
import com.cappielloantonio.tempo.database.dao.FavoriteDao;
Expand All @@ -32,7 +33,7 @@
entities = {Queue.class, Server.class, RecentSearch.class, Download.class, Chronology.class, Favorite.class, SessionMediaItem.class, Playlist.class},
autoMigrations = {@AutoMigration(from = 9, to = 10)}
)
@TypeConverters({DateConverters.class})
@TypeConverters({DateConverters.class, MapTypeConverter.class})
public abstract class AppDatabase extends RoomDatabase {
private final static String DB_NAME = "tempo_db";
private static AppDatabase instance;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.cappielloantonio.tempo.database.converter

import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

object MapTypeConverter {

@TypeConverter
@JvmStatic
fun stringToMap(value: String?): Map<String, String> {
return if (value.isNullOrEmpty()) {
emptyMap()
} else {
try {
Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)
?: emptyMap()
} catch (e: Exception) {
emptyMap()
}
}
}


@TypeConverter
@JvmStatic
fun mapToString(value: Map<String, String>?): String {
return value?.let { Gson().toJson(it) } ?: ""
}
}

5 changes: 4 additions & 1 deletion app/src/main/java/com/cappielloantonio/tempo/model/Server.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,8 @@ data class Server(
val timestamp: Long,

@ColumnInfo(name = "low_security", defaultValue = "false")
val isLowSecurity: Boolean
val isLowSecurity: Boolean,

@ColumnInfo(name = "custom_headers")
var customHeaders: Map<String, String>? = null,
) : Parcelable
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.cappielloantonio.tempo.App
import com.cappielloantonio.tempo.subsonic.utils.CacheUtil
import com.google.gson.GsonBuilder
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
Expand All @@ -12,14 +13,15 @@ import java.util.concurrent.TimeUnit

class RetrofitClient(subsonic: Subsonic) {
var retrofit: Retrofit
var customHeaders: Map<String, String> = subsonic.customHeaders;

init {
retrofit = Retrofit.Builder()
.baseUrl(subsonic.url)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create()))
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
.client(getOkHttpClient())
.build()
init {;
retrofit = Retrofit.Builder().baseUrl(subsonic.url).addConverterFactory(
GsonConverterFactory.create(
GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create()
)
).addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
.client(getOkHttpClient()).build()
}

private fun getOkHttpClient(): OkHttpClient {
Expand All @@ -35,16 +37,18 @@ class RetrofitClient(subsonic: Subsonic) {
// SystemClient 60
// AlbumSongListClient 60

return OkHttpClient.Builder()
.callTimeout(2, TimeUnit.MINUTES)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.addInterceptor(getHttpLoggingInterceptor())
val builder = OkHttpClient.Builder().callTimeout(2, TimeUnit.MINUTES)
.connectTimeout(20, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS).addInterceptor(getHttpLoggingInterceptor())
.addInterceptor(cacheUtil.offlineInterceptor)
// .addNetworkInterceptor(cacheUtil.onlineInterceptor)
.cache(getCache())
.build()

if (customHeaders.isNotEmpty()) {
builder.addNetworkInterceptor(getCustomHeadersInterceptor())
}

return builder.build()
}

private fun getHttpLoggingInterceptor(): HttpLoggingInterceptor {
Expand All @@ -53,6 +57,21 @@ class RetrofitClient(subsonic: Subsonic) {
return loggingInterceptor
}

private fun getCustomHeadersInterceptor(): Interceptor {
return Interceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()

customHeaders.forEach { (key, value) ->
requestBuilder.addHeader(key, value)
}

val request = requestBuilder.build()
chain.proceed(request)
}
}


private fun getCache(): Cache {
val cacheSize = 10 * 1024 * 1024
return Cache(App.getContext().cacheDir, cacheSize.toLong())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ public String getUrl() {
return url.replace("//rest", "/rest");
}

public Map<String, String> getCustomHeaders() {
return preferences.getCustomHeaders();
}

public Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("u", preferences.getUsername());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

import com.cappielloantonio.tempo.subsonic.utils.StringUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SubsonicPreferences {
private String serverUrl;
private String username;
private String clientName = "Tempo";
private SubsonicAuthentication authentication;
private Map<String, String> customHeaders;

public String getServerUrl() {
return serverUrl;
Expand Down Expand Up @@ -48,6 +51,19 @@ public void setAuthentication(String password, String token, String salt, boolea
}
}

public void setCustomHeaders(Map<String, String> headers) {
if (headers != null && !headers.isEmpty()) {
this.customHeaders = headers;
}
}

public Map<String, String> getCustomHeaders() {
if (this.customHeaders != null) {
return this.customHeaders;
}
return new HashMap<>();
}

public static class SubsonicAuthentication {
private String password;
private String salt;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.cappielloantonio.tempo.ui.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.cappielloantonio.tempo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomHeadersAdapter extends RecyclerView.Adapter<CustomHeadersAdapter.ViewHolder> {
private final List<Map.Entry<String, String>> localCustomHeaders;
private final OnDeleteListener onDeleteListener;

public interface OnDeleteListener {
void onDelete(String key);
}

// ViewHolder class
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView headerDetailsView;
private final Button deleteButton;

public ViewHolder(View view) {
super(view);
headerDetailsView = view.findViewById(R.id.custom_header_value_text_view);
deleteButton = view.findViewById(R.id.delete_icon);
}

public TextView getTextView() {
return headerDetailsView;
}
}

public CustomHeadersAdapter(Map<String, String> data, OnDeleteListener listener) {
this.localCustomHeaders = new ArrayList<>(data.entrySet());
this.onDeleteListener = listener;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row_custom_header_value, parent, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Map.Entry<String, String> entry = localCustomHeaders.get(position);
String key = entry.getKey();
String value = entry.getValue();

holder.getTextView().setText(String.format("%s: %s", key, value));

holder.deleteButton.setOnClickListener(v -> {
if (onDeleteListener != null) {
this.onDeleteListener.onDelete(key);
}
});
}

@Override
public int getItemCount() {
return localCustomHeaders.size();
}

@SuppressLint("NotifyDataSetChanged")
public void updateData(Map<String, String> newData) {
localCustomHeaders.clear();
localCustomHeaders.addAll(newData.entrySet());

notifyDataSetChanged();
}
}
Loading