Skip to content
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
27 changes: 26 additions & 1 deletion core/src/main/golang/native/config/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
Expand All @@ -13,6 +14,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"

"cfa/native/app"

Expand All @@ -31,11 +33,13 @@ type Status struct {
SubTotal *int64 `json:"subTotal,omitempty"`
SubExpire *int64 `json:"subExpire,omitempty"`
SubUpdateInterval *int64 `json:"subUpdateInterval,omitempty"`
SubAnnounce string `json:"subAnnounce,omitempty"`
}

type fetchHeader struct {
SubscriptionUserInfo string
ProfileUpdateInterval string
Announce string
}

func openUrl(ctx context.Context, url string) (io.ReadCloser, fetchHeader, error) {
Expand All @@ -48,6 +52,7 @@ func openUrl(ctx context.Context, url string) (io.ReadCloser, fetchHeader, error
return response.Body, fetchHeader{
SubscriptionUserInfo: response.Header.Get("subscription-userinfo"),
ProfileUpdateInterval: response.Header.Get("profile-update-interval"),
Announce: response.Header.Get("Announce"),
}, nil
}

Expand Down Expand Up @@ -117,10 +122,29 @@ func parseProfileUpdateInterval(value string) (int64, bool) {
return int64(interval / time.Millisecond), true
}

func parseAnnounce(value string) string {
value = strings.TrimSpace(value)
if encoded, ok := strings.CutPrefix(value, "base64:"); ok {
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return ""
}
value = strings.TrimSpace(string(decoded))
}

// Profile metadata is sent to the UI over Binder.
const maxAnnounceBytes = 4096
if len(value) > maxAnnounceBytes || !utf8.ValidString(value) {
return ""
}
return value
}

func reportSubscriptionInfo(header fetchHeader, reportStatus func(string)) {
userinfo := header.SubscriptionUserInfo
updateIntervalHeader := header.ProfileUpdateInterval
if userinfo == "" && updateIntervalHeader == "" {
announce := parseAnnounce(header.Announce)
if userinfo == "" && updateIntervalHeader == "" && announce == "" {
return
}

Expand All @@ -129,6 +153,7 @@ func reportSubscriptionInfo(header fetchHeader, reportStatus func(string)) {
Args: []string{},
Progress: -1,
MaxProgress: -1,
SubAnnounce: announce,
}

if userinfo != "" {
Expand Down
68 changes: 68 additions & 0 deletions core/src/main/golang/native/config/fetch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package config

import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
)

func TestFetchSubscriptionAnnouncement(t *testing.T) {
tests := []struct {
name string
header string
userInfo string
want string
}{
{name: "plain text", header: "Scheduled maintenance", want: "Scheduled maintenance"},
{name: "base64 UTF-8", header: "base64:0JLQtdGA0YHQuNGPINC/0L7QtNC/0LjRgdC60Lg6IHYxLjEuMQ==", want: "Версия подписки: v1.1.1"},
{name: "missing"},
{name: "blank", header: "base64:ICA="},
{name: "malformed base64", header: "base64:???", userInfo: "upload=7; download=12; total=100; expire=0"},
{name: "invalid UTF-8", header: "base64:/w=="},
{name: "too large", header: strings.Repeat("a", 4097)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tt.header != "" {
w.Header().Set("Announce", tt.header)
}
if tt.userInfo != "" {
w.Header().Set("Subscription-Userinfo", tt.userInfo)
}
_, _ = io.WriteString(w, "proxies: []\n")
}))
defer server.Close()

source, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
header, err := fetch(source, filepath.Join(t.TempDir(), "config.yaml"))
if err != nil {
t.Fatal(err)
}

var status struct {
Announce string `json:"subAnnounce"`
Upload int64 `json:"subUpload"`
}
reportSubscriptionInfo(header, func(payload string) {
if err := json.Unmarshal([]byte(payload), &status); err != nil {
t.Fatal(err)
}
})
if status.Announce != tt.want {
t.Errorf("announcement = %q, want %q", status.Announce, tt.want)
}
if tt.userInfo != "" && status.Upload != 7 {
t.Errorf("upload = %d, want 7", status.Upload)
}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ data class FetchStatus(
val subTotal: Long? = null,
val subExpire: Long? = null,
val subUpdateInterval: Long? = null,
val subAnnounce: String? = null,
) : Parcelable {
enum class Action {
FetchConfiguration,
Expand Down
9 changes: 9 additions & 0 deletions design/src/main/res/layout/adapter_profile.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@
android:layout_marginTop="@dimen/item_text_margin"
android:text="@{profile.pending ? @string/format_type_unsaved(I18nKt.toString(profile.type, context)) : I18nKt.toString(profile.type, context)}"
android:textAppearance="@style/TextAppearance.MaterialComponents.Body2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/item_text_margin"
android:text="@{profile.announce}"
android:textAppearance="@style/TextAppearance.MaterialComponents.Body2"
android:visibility="@{profile.announce == null ? View.GONE : View.VISIBLE}" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ class ProfileManager(private val context: Context) : IProfileManager,
imported = imported != null,
pending = pending != null,
ageSecretKey = if (pending != null) pending.ageSecretKey else imported?.ageSecretKey,
announce = imported?.announce,
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ object ProfileProcessor {
subscriptionInfo?.subTotal ?: 0,
subscriptionInfo?.subExpire ?: 0,
old?.createdAt ?: System.currentTimeMillis(),
ageSecretKey = snapshot.ageSecretKey
ageSecretKey = snapshot.ageSecretKey,
announce = subscriptionInfo?.subAnnounce,
)
if (old != null) {
ImportedDao().update(new)
Expand Down Expand Up @@ -116,13 +117,15 @@ object ProfileProcessor {
context.processingDir.copyRecursively(context.importedDir.resolve(snapshot.uuid.toString()))

val upload = subscriptionInfo?.subUpload
if (upload != null) {
val announce = subscriptionInfo?.subAnnounce
if (upload != null || announce != imported.announce) {
ImportedDao().update(
imported.copy(
upload = upload,
download = subscriptionInfo.subDownload ?: 0,
total = subscriptionInfo.subTotal ?: 0,
expire = subscriptionInfo.subExpire ?: 0,
upload = upload ?: imported.upload,
download = subscriptionInfo?.subDownload ?: imported.download,
total = subscriptionInfo?.subTotal ?: imported.total,
expire = subscriptionInfo?.subExpire ?: imported.expire,
announce = announce,
)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import java.lang.ref.SoftReference
import androidx.room.Database as DB

@DB(
version = 2,
version = 3,
entities = [Imported::class, Pending::class, Selection::class],
exportSchema = false,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ data class Imported(
@ColumnInfo(name = "expire") val expire: Long,
@ColumnInfo(name = "createdAt") val createdAt: Long,
@ColumnInfo(name = "ageSecretKey") val ageSecretKey: String? = null,
@ColumnInfo(name = "announce") val announce: String? = null,
)
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@ private val MIGRATION_1_2 = object : Migration(1, 2) {
}
}

private val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE imported ADD COLUMN announce TEXT")
}
}

val MIGRATIONS: Array<Migration> = arrayOf(
MIGRATION_1_2,
MIGRATION_2_3,
)

val LEGACY_MIGRATION = ::migrationFromLegacy
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ data class Profile(
val imported: Boolean,
val pending: Boolean,
val ageSecretKey: String? = null,
val announce: String? = null,
) : Parcelable {
enum class Type {
File, Url, External
Expand Down