Initial commit

This commit is contained in:
2026-01-17 02:34:23 +03:00
commit 9f433105a4
66 changed files with 2177 additions and 0 deletions

9
.gitignore vendored Normal file
View File

@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
/.idea

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 VK Chat Manager Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

30
README.md Normal file
View File

@@ -0,0 +1,30 @@
# VK Chat Manager
Android-приложение для управления групповыми чатами VK (ВКонтакте).
## Возможности
* **Аутентификация:** Безопасный вход в систему с использованием токена VK.
* **Организация чатов:** Автоматическая категоризация чатов по группам:
* Офис
* Розница
* Склад
* Кофейни
* Другое
* **Управление пользователями:**
* Добавление или удаление пользователей из выбранных чатов.
* Обработка профилей пользователей по ссылкам для добавления их в список на обработку.
* Просмотр пользователей в очереди на обработку.
* **Управление чатами:**
* Выбор/снятие выбора со всех чатов в категории.
* Обновление списка чатов.
* **Управление токеном:**
* Просмотр статуса истечения срока действия токена.
* Выход из системы и очистка токена.
## Используемые технологии
* Android SDK
* Java
* Material Components for Android
* ViewPager2 и TabLayout для навигации

1
app/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

41
app/build.gradle Normal file
View File

@@ -0,0 +1,41 @@
plugins {
alias(libs.plugins.android.application)
}
android {
namespace 'com.anabasis.vkchatmanager'
compileSdk {
version = release(36)
}
defaultConfig {
applicationId "com.anabasis.vkchatmanager"
minSdk 26
targetSdk 36
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.2'
implementation 'androidx.viewpager2:viewpager2:1.1.0'
implementation "com.google.android.material:material:1.12.0"
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'org.json:json:20240303'
}

21
app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:usesCleartextTraffic="true"
android:theme="@style/Theme.VKChatManager"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round">
<activity android:name=".AuthActivity"/>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

View File

@@ -0,0 +1,57 @@
package com.anabasis.vkchatmanager;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
import com.anabasis.vkchatmanager.util.TokenManager;
public class AuthActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_auth);
WebView w = findViewById(R.id.webView);
w.getSettings().setJavaScriptEnabled(true);
w.getSettings().setDomStorageEnabled(true);
w.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView v, WebResourceRequest r) {
String url = r.getUrl().toString();
if (url.contains("access_token")) {
Uri u = Uri.parse(url.replace("#", "?"));
String token = u.getQueryParameter("access_token");
String exp = u.getQueryParameter("expires_in");
TokenManager.save(
AuthActivity.this,
token,
exp == null ? 0 : Long.parseLong(exp)
);
setResult(RESULT_OK);
finish();
return true;
}
return false;
}
});
w.loadUrl(
"https://oauth.vk.com/authorize" +
"?client_id=2685278" +
"&display=page" +
"&redirect_uri=https://oauth.vk.com/blank.html" +
"&scope=1073737727" +
"&response_type=token" +
"&v=5.131"
);
}
}

View File

@@ -0,0 +1,100 @@
package com.anabasis.vkchatmanager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anabasis.vkchatmanager.adapters.ChatListAdapter;
import com.anabasis.vkchatmanager.model.VkChat;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
public class ChatListFragment extends Fragment {
private static final String ARG_CHATS = "chats";
private ArrayList<VkChat> chats;
private ChatListAdapter adapter;
private View view;
public static ChatListFragment newInstance(List<VkChat> chats) {
ChatListFragment f = new ChatListFragment();
Bundle b = new Bundle();
b.putSerializable(
"chats",
new ArrayList<>(chats) // КЛЮЧЕВО
);
f.setArguments(b);
return f;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chats = (ArrayList<VkChat>)
getArguments().getSerializable(ARG_CHATS);
if (chats == null) chats = new ArrayList<>();
}
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
RecyclerView rv = new RecyclerView(requireContext());
rv.setLayoutManager(new LinearLayoutManager(requireContext()));
adapter = new ChatListAdapter(chats);
rv.setAdapter(adapter);
view = rv;
return view;
}
public void showSnackbar(String message, List<String> details) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG)
.setAction("Подробнее", v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle("Детали")
.setItems(details.toArray(new String[0]), null)
.setPositiveButton("OK", null);
builder.create().show();
})
.show();
}
/* ===== API ДЛЯ MainActivity ===== */
public void setAll(boolean value) {
adapter.setAll(value);
}
public List<VkChat> getSelected() {
List<VkChat> res = new ArrayList<>();
for (VkChat c : chats)
if (c.selected) res.add(c);
return res;
}
public void updateChats() {
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
}

View File

@@ -0,0 +1,514 @@
package com.anabasis.vkchatmanager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.viewpager2.widget.ViewPager2;
import com.anabasis.vkchatmanager.adapters.ChatTabAdapter;
import com.anabasis.vkchatmanager.dialogs.MultiLinkDialog;
import com.anabasis.vkchatmanager.model.VkChat;
import com.anabasis.vkchatmanager.network.TokenExpiredException;
import com.anabasis.vkchatmanager.network.VkApiClient;
import com.anabasis.vkchatmanager.util.TokenManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.textfield.TextInputEditText;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private VkApiClient api;
private final List<VkChat> office = new ArrayList<>();
private final List<VkChat> retail = new ArrayList<>();
private final List<VkChat> warehouse = new ArrayList<>();
private final List<VkChat> coffee = new ArrayList<>();
private final List<VkChat> other = new ArrayList<>();
private final List<Integer> userIdsToProcess = new ArrayList<>();
private final List<String> userNamesToProcess = new ArrayList<>();
private LinearProgressIndicator progressBar;
private androidx.swiperefreshlayout.widget.SwipeRefreshLayout swipeRefresh;
private ViewPager2 pager;
private ChatTabAdapter adapter;
private MaterialButton listBtn, addBtn, removeBtn, showUsersBtn;
private TextInputEditText singleInput;
private final Handler handler = new Handler(Looper.getMainLooper());
private Runnable delayedProcessing;
private final ActivityResultLauncher<Intent> authLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
recreate();
}
}
);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
setContentView(R.layout.activity_main);
setSupportActionBar(findViewById(R.id.toolbar));
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.appBar), (v, windowInsets) -> {
Insets systemBarInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBarInsets.left, systemBarInsets.top, systemBarInsets.right, 0);
return windowInsets;
});
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.content_container), (v, windowInsets) -> {
Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.ime() | WindowInsetsCompat.Type.systemBars());
v.setPadding(0, 0, 0, insets.bottom);
return windowInsets;
});
String token = TokenManager.load(this);
if (token == null) {
authLauncher.launch(new Intent(this, AuthActivity.class));
return;
}
api = new VkApiClient(token);
pager = findViewById(R.id.pager);
swipeRefresh = findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(this::refreshChats);
TabLayout tabs = findViewById(R.id.tabs);
listBtn = findViewById(R.id.multiLinkBtn);
addBtn = findViewById(R.id.addBtn);
removeBtn = findViewById(R.id.removeBtn);
showUsersBtn = findViewById(R.id.showUsersBtn);
singleInput = findViewById(R.id.singleLinkInput);
progressBar = findViewById(R.id.progressBar);
setupTabs(tabs);
refreshChats();
listBtn.setOnClickListener(v ->
MultiLinkDialog
.newInstance(this::processLinksList)
.show(getSupportFragmentManager(), "links")
);
singleInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (delayedProcessing != null) {
handler.removeCallbacks(delayedProcessing);
}
}
@Override
public void afterTextChanged(Editable s) {
String link = s.toString().trim();
if (!link.isEmpty()) {
delayedProcessing = () -> {
processLinksList(List.of(link));
s.clear();
};
handler.postDelayed(delayedProcessing, 1000);
}
}
});
addBtn.setOnClickListener(v -> processUsers(true));
removeBtn.setOnClickListener(v -> processUsers(false));
showUsersBtn.setOnClickListener(v -> showUsers());
}
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
ChatListFragment f = getCurrentFragment();
int id = item.getItemId();
if (id == R.id.action_refresh) {
refreshChats();
return true;
}
if (id == R.id.action_select_all) {
if (f != null) f.setAll(true);
return true;
}
if (id == R.id.action_deselect_all) {
if (f != null) f.setAll(false);
return true;
}
if (id == R.id.action_token_status) {
showTokenStatus();
return true;
}
if (id == R.id.action_sign_out) {
TokenManager.clear(this);
recreate();
return true;
}
return super.onOptionsItemSelected(item);
}
/* ===================== TOKEN ===================== */
private void handleTokenExpired() {
Toast.makeText(this, getString(R.string.token_expired_message), Toast.LENGTH_SHORT).show();
TokenManager.clear(this);
recreate();
}
/* ===================== UI ===================== */
private void showTokenStatus() {
long exp = TokenManager.expiration(this);
String message;
if (exp == 0) {
message = getString(R.string.token_status_perpetual);
} else {
long now = System.currentTimeMillis();
if (exp > now) {
long diff = (exp - now) / 1000;
long hours = diff / 3600;
long minutes = (diff % 3600) / 60;
message = getString(R.string.token_status_expires_in, hours, minutes);
} else {
message = getString(R.string.token_status_expired);
}
}
new MaterialAlertDialogBuilder(this)
.setTitle(R.string.token_status_title)
.setMessage(message)
.setPositiveButton(R.string.ok_button, null)
.show();
}
private void setUiEnabled(boolean enabled) {
listBtn.setEnabled(enabled);
addBtn.setEnabled(enabled);
removeBtn.setEnabled(enabled);
showUsersBtn.setEnabled(enabled);
singleInput.setEnabled(enabled);
swipeRefresh.setEnabled(enabled);
}
private void setupTabs(TabLayout tabs) {
List<List<VkChat>> pages = List.of(
office, retail, warehouse, coffee, other
);
adapter = new ChatTabAdapter(this, pages);
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(5);
new TabLayoutMediator(tabs, pager, (tab, pos) -> {
switch (pos) {
case 0: tab.setText(getString(R.string.office_tab)); break;
case 1: tab.setText(getString(R.string.retail_tab)); break;
case 2: tab.setText(getString(R.string.warehouse_tab)); break;
case 3: tab.setText(getString(R.string.coffee_tab)); break;
case 4: tab.setText(getString(R.string.other_tab)); break;
}
}).attach();
}
private ChatListFragment getCurrentFragment() {
int pos = pager.getCurrentItem();
long itemId = adapter.getItemId(pos);
return (ChatListFragment)
getSupportFragmentManager()
.findFragmentByTag("f" + itemId);
}
/* ===================== REFRESH ===================== */
private void refreshChats() {
setUiEnabled(false);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
new Thread(() -> {
try {
JSONArray items = api.getChats();
office.clear();
retail.clear();
warehouse.clear();
coffee.clear();
other.clear();
for (int i = 0; i < items.length(); i++) {
JSONObject conv = items.getJSONObject(i)
.getJSONObject("conversation");
if (!"chat".equals(
conv.getJSONObject("peer").getString("type")))
continue;
int chatId = conv.getJSONObject("peer").getInt("local_id");
String title = conv
.getJSONObject("chat_settings")
.getString("title");
addChat(chatId, title);
}
runOnUiThread(() -> {
setUiEnabled(true);
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.GONE);
swipeRefresh.setRefreshing(false);
adapter.notifyDataChanged();
Toast.makeText(
this,
getString(R.string.chats_updated_message),
Toast.LENGTH_SHORT
).show();
});
} catch (TokenExpiredException e) {
runOnUiThread(this::handleTokenExpired);
} catch (Exception e) {
runOnUiThread(() -> {
setUiEnabled(true);
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.GONE);
swipeRefresh.setRefreshing(false);
Toast.makeText(
this,
getString(R.string.api_error, e.getMessage()),
Toast.LENGTH_LONG
).show();
});
}
}).start();
}
private void addChat(int id, String title) {
String t = title.toLowerCase();
if (t.startsWith("ag ")) t = t.substring(3);
VkChat c = new VkChat(id, title);
if (t.contains("офис")) office.add(c);
else if (t.contains("розница")) retail.add(c);
else if (t.contains("склад")) warehouse.add(c);
else if (t.contains("кофейни")) coffee.add(c);
else other.add(c);
}
/* ===================== LINKS ===================== */
private void processLinksList(List<String> links) {
userIdsToProcess.clear();
userNamesToProcess.clear();
setUiEnabled(false);
new Thread(() -> {
for (String link : links) {
try {
String screen = extractScreenName(link);
int uid = api.resolveUserId(screen);
if (uid > 0) {
userIdsToProcess.add(uid);
userNamesToProcess.add(api.getUserName(uid));
}
} catch (TokenExpiredException e) {
runOnUiThread(this::handleTokenExpired);
} catch (Exception ignored) {}
}
runOnUiThread(() -> {
setUiEnabled(true);
Toast.makeText(
this,
getString(R.string.users_loaded_message, userIdsToProcess.size()),
Toast.LENGTH_SHORT
).show();
});
}).start();
}
private String extractScreenName(String link) {
link = link.trim();
if (link.startsWith("@"))
return link.substring(1);
link = link.replace("https://", "")
.replace("http://", "");
if (link.startsWith("vk.com/"))
return link.substring(7);
if (link.startsWith("m.vk.com/"))
return link.substring(8);
return link;
}
/* ===================== ADD / REMOVE ===================== */
private void showUsers() {
if (userNamesToProcess.isEmpty()) {
Toast.makeText(this, getString(R.string.user_list_empty), Toast.LENGTH_SHORT).show();
return;
}
StringBuilder msg = new StringBuilder();
for (String name : userNamesToProcess) {
msg.append("").append(name).append("\n");
}
new MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.users_dialog_title))
.setMessage(msg.toString())
.setPositiveButton(getString(R.string.ok_button), null)
.show();
}
private void processUsers(boolean add) {
List<VkChat> chats = getCurrentFragment().getSelected();
if (chats.isEmpty() || userIdsToProcess.isEmpty()) {
Toast.makeText(this,
getString(R.string.no_chats_or_users_selected_message),
Toast.LENGTH_SHORT).show();
return;
}
StringBuilder msg = new StringBuilder();
msg.append(add ? getString(R.string.add_users_dialog_message) : getString(R.string.remove_users_dialog_message));
msg.append("\n\n");
for (String name : userNamesToProcess) {
msg.append("").append(name).append("\n");
}
msg.append("\n");
msg.append(getString(R.string.in_chats_dialog_message));
msg.append("\n");
for (VkChat c : chats) {
msg.append("").append(c.title).append("\n");
}
new MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.confirmation_dialog_title))
.setMessage(msg.toString())
.setPositiveButton(getString(R.string.confirm_button), (d, w) ->
executeUsers(add, chats))
.setNegativeButton(getString(R.string.cancel_button), null)
.show();
}
private void executeUsers(boolean add, List<VkChat> chats) {
setUiEnabled(false);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
progressBar.setProgress(0, true);
int totalOps = chats.size() * userIdsToProcess.size();
progressBar.setMax(totalOps);
new Thread(() -> {
final List<String> details = new ArrayList<>();
int done = 0;
for (VkChat c : chats) {
for (int i = 0; i < userIdsToProcess.size(); i++) {
int uid = userIdsToProcess.get(i);
String userName = userNamesToProcess.get(i);
String resultMessage;
try {
if (add) {
api.addUser(c.id, uid, true);
resultMessage = getString(R.string.op_success_add_format, userName, c.title);
} else {
api.removeUser(c.id, uid);
resultMessage = getString(R.string.op_success_remove_format, userName, c.title);
}
} catch (TokenExpiredException e) {
runOnUiThread(this::handleTokenExpired);
return;
} catch (Exception e) {
String error = e.getMessage() != null && !e.getMessage().isEmpty() ? e.getMessage() : getString(R.string.op_unknown_error);
resultMessage = getString(R.string.op_failure_format, userName, c.title, error);
}
details.add(resultMessage);
done++;
int progress = done;
runOnUiThread(() -> progressBar.setProgress(progress, true));
}
}
runOnUiThread(() -> {
setUiEnabled(true);
progressBar.setVisibility(View.GONE);
ChatListFragment f = getCurrentFragment();
if (f != null) {
f.showSnackbar(getString(R.string.operation_complete_message), details);
} else {
Toast.makeText(
this,
getString(R.string.operation_complete_message),
Toast.LENGTH_LONG
).show();
}
});
}).start();
}
}

View File

@@ -0,0 +1,67 @@
package com.anabasis.vkchatmanager.adapters;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anabasis.vkchatmanager.R;
import com.anabasis.vkchatmanager.model.VkChat;
import com.google.android.material.checkbox.MaterialCheckBox;
import java.util.List;
public class ChatListAdapter
extends RecyclerView.Adapter<ChatListAdapter.Holder> {
private final List<VkChat> chats;
public ChatListAdapter(List<VkChat> chats) {
this.chats = chats;
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_chat, parent, false);
return new Holder(v);
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
VkChat chat = chats.get(position);
holder.chatCheck.setOnCheckedChangeListener(null);
holder.chatCheck.setText(chat.title);
holder.chatCheck.setChecked(chat.selected);
holder.chatCheck.setOnCheckedChangeListener(
(buttonView, isChecked) -> chat.selected = isChecked
);
}
@Override
public int getItemCount() {
return chats.size();
}
public void setAll(boolean value) {
for (VkChat c : chats) {
c.selected = value;
}
notifyItemRangeChanged(0, getItemCount());
}
static class Holder extends RecyclerView.ViewHolder {
MaterialCheckBox chatCheck;
Holder(@NonNull View itemView) {
super(itemView);
chatCheck = itemView.findViewById(R.id.chatCheck);
}
}
}

View File

@@ -0,0 +1,54 @@
package com.anabasis.vkchatmanager.adapters;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.anabasis.vkchatmanager.ChatListFragment;
import com.anabasis.vkchatmanager.model.VkChat;
import java.util.List;
public class ChatTabAdapter extends FragmentStateAdapter {
private final List<List<VkChat>> pages;
// version увеличиваем при обновлении данных
private long dataVersion = 0;
public ChatTabAdapter(@NonNull FragmentActivity fa,
List<List<VkChat>> pages) {
super(fa);
this.pages = pages;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return ChatListFragment.newInstance(pages.get(position));
}
@Override
public int getItemCount() {
return pages.size();
}
// КЛЮЧЕВОЕ МЕСТО
@Override
public long getItemId(int position) {
return position + dataVersion;
}
@Override
public boolean containsItem(long itemId) {
return itemId >= dataVersion &&
itemId < dataVersion + pages.size();
}
// вызывается при обновлении чатов
public void notifyDataChanged() {
dataVersion += pages.size();
notifyDataSetChanged();
}
}

View File

@@ -0,0 +1,53 @@
package com.anabasis.vkchatmanager.dialogs;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import com.anabasis.vkchatmanager.R;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.util.ArrayList;
import java.util.List;
public class MultiLinkDialog extends DialogFragment {
public interface Callback {
void onLinksEntered(List<String> links);
}
private Callback callback;
public static MultiLinkDialog newInstance(Callback cb) {
MultiLinkDialog d = new MultiLinkDialog();
d.callback = cb;
return d;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_multilink, null);
EditText input = view.findViewById(R.id.linksInput);
return new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.multilink_dialog_title)
.setView(view)
.setPositiveButton(R.string.multilink_dialog_positive_button, (d, which) -> {
List<String> result = new ArrayList<>();
for (String line : input.getText().toString().split("\n")) {
line = line.trim();
if (!line.isEmpty()) result.add(line);
}
if (callback != null) callback.onLinksEntered(result);
})
.setNegativeButton(R.string.multilink_dialog_negative_button, null)
.create();
}
}

View File

@@ -0,0 +1,16 @@
package com.anabasis.vkchatmanager.model;
import java.io.Serializable;
public class VkChat implements Serializable {
public final int id;
public final String title;
public boolean selected = false;
public VkChat(int id, String title) {
this.id = id;
this.title = title;
}
}

View File

@@ -0,0 +1,4 @@
package com.anabasis.vkchatmanager.network;
public class TokenExpiredException extends Exception {
}

View File

@@ -0,0 +1,86 @@
package com.anabasis.vkchatmanager.network;
import org.json.JSONArray;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class VkApiClient {
private final OkHttpClient client = new OkHttpClient();
private final String token;
public VkApiClient(String token) {
this.token = token;
}
private JSONObject call(String method, String params) throws Exception {
String url = "https://api.vk.com/method/" + method +
"?" + params +
"&access_token=" + token +
"&v=5.131";
Request r = new Request.Builder().url(url).build();
Response res = client.newCall(r).execute();
String body = res.body().string();
JSONObject json = new JSONObject(body);
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
if (error.getInt("error_code") == 5) {
throw new TokenExpiredException();
}
throw new Exception(error.getString("error_msg"));
}
return json;
}
public JSONArray getChats() throws Exception {
return call("messages.getConversations", "count=200&filter=all")
.getJSONObject("response")
.getJSONArray("items");
}
public void addUser(int chatId, int userId, boolean visible) throws Exception {
call("messages.addChatUser",
"chat_id=" + chatId +
"&user_id=" + userId +
(visible ? "&visible_messages_count=250" : ""));
}
public void removeUser(int chatId, int userId) throws Exception {
call("messages.removeChatUser",
"chat_id=" + chatId +
"&member_id=" + userId);
}
public int resolveUserId(String screenName) throws Exception {
JSONObject resp = call(
"utils.resolveScreenName",
"screen_name=" + screenName
);
JSONObject obj = resp.optJSONObject("response");
if (obj == null) return -1;
String type = obj.getString("type");
if (!"user".equals(type)) return -1;
return obj.getInt("object_id");
}
public String getUserName(int userId) throws Exception {
JSONObject r = call(
"users.get",
"user_ids=" + userId
);
JSONObject u = r.getJSONArray("response").getJSONObject(0);
return u.getString("first_name") + " " + u.getString("last_name");
}
}

View File

@@ -0,0 +1,44 @@
package com.anabasis.vkchatmanager.util;
import android.content.Context;
import android.content.SharedPreferences;
public class TokenManager {
private static final String PREF = "vk_token";
public static void save(Context ctx, String token, long expiresIn) {
long exp = expiresIn == 0 ? 0 :
System.currentTimeMillis() + expiresIn * 1000;
ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE)
.edit()
.putString("token", token)
.putLong("exp", exp)
.apply();
}
public static String load(Context ctx) {
SharedPreferences p = ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE);
long exp = p.getLong("exp", -1);
if (exp == -1) return null;
if (exp == 0 || exp > System.currentTimeMillis())
return p.getString("token", null);
p.edit().clear().apply();
return null;
}
public static void clear(Context ctx) {
ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE)
.edit()
.clear()
.apply();
}
public static long expiration(Context ctx) {
return ctx.getSharedPreferences(PREF, Context.MODE_PRIVATE)
.getLong("exp", 0);
}
}

View File

@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@@ -0,0 +1,17 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="50"
android:viewportHeight="50">
<group android:scaleX="0.5557895"
android:scaleY="0.5557895"
android:translateX="11.105263"
android:translateY="11.105263">
<path
android:pathData="M42.5,7.5L16.09,7.5L7.5,16.037L33.963,16.037L33.963,42.5L42.5,33.91L42.5,7.5Z"
android:fillColor="#FFFFFF"/>
<path
android:pathData="M7.5,35.43L7.5,42.5L14.64,42.5L14.57,42.5L23.164,33.906L23.157,26.848L16.083,26.847L7.5,35.43Z"
android:fillColor="#FFFFFF"/>
</group>
</vector>

View File

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="?attr/colorOnSurface"
android:pathData="M17.65,6.35C16.2,4.9 14.21,4 12,4c-4.42,0 -7.99,3.58 -7.99,8s3.57,8 7.99,8c3.73,0 6.84,-2.55 7.73,-6h-2.08c-0.82,2.33 -3.04,4 -5.65,4 -3.31,0 -6,-2.69 -6,-6s2.69,-6 6,-6c1.66,0 3.14,0.69 4.22,1.78L13,11h7V4l-2.35,2.35z"/>
</vector>

View File

@@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="50dp"
android:height="50dp"
android:viewportWidth="50"
android:viewportHeight="50">
<path
android:pathData="M42.5,7.5L16.09,7.5L7.5,16.037L33.963,16.037L33.963,42.5L42.5,33.91L42.5,7.5Z"
android:fillColor="#FFFFFF"/>
<path
android:pathData="M7.5,35.43L7.5,42.5L14.64,42.5L14.57,42.5L23.164,33.906L23.157,26.848L16.083,26.847L7.5,35.43Z"
android:fillColor="#FFFFFF"/>
</vector>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>

View File

@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TOP APP BAR -->
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="@string/app_name"/>
</com.google.android.material.appbar.AppBarLayout>
<RelativeLayout
android:id="@+id/content_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<!-- Progress bar -->
<com.google.android.material.progressindicator.LinearProgressIndicator
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="4dp"
android:visibility="gone" />
<!-- BOTTOM ACTION BAR -->
<LinearLayout
android:id="@+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?colorSurface"
android:orientation="vertical"
android:padding="12dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/user_link_hint">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/singleLinkInput"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/multiLinkBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@string/list_button" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/add_button" />
<com.google.android.material.button.MaterialButton
android:id="@+id/showUsersBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="8dp"
android:text="@string/show_button" />
<com.google.android.material.button.MaterialButton
android:id="@+id/removeBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="@string/remove_button" />
</LinearLayout>
</LinearLayout>
<!-- CONTENT -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottomBar"
android:layout_below="@id/progressBar"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipeRefresh"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:paddingTop="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/multilink_dialog_hint">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/linksInput"
android:layout_width="match_parent"
android:layout_height="200dp"
android:gravity="top"
android:inputType="textMultiLine" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/chatRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.checkbox.MaterialCheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/chatCheck"
style="?attr/checkboxStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:textSize="16sp"/>

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_refresh"
android:icon="@drawable/ic_refresh"
android:title="@string/action_refresh"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_select_all"
android:title="@string/action_select_all" />
<item
android:id="@+id/action_deselect_all"
android:title="@string/action_deselect_all" />
<item
android:id="@+id/action_token_status"
android:title="@string/action_token_status" />
<item
android:id="@+id/action_sign_out"
android:title="@string/action_sign_out" />
</menu>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 804 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 316 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 355 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 574 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 834 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.VKChatManager" parent="Theme.Material3.DynamicColors.DayNight.NoActionBar">
<!-- Status bar -->
<item name="android:statusBarColor">?attr/colorSurface</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowOptOutEdgeToEdgeEnforcement">true</item>
</style>
</resources>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
</resources>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.VKChatManager"
parent="Theme.Material3.DynamicColors.DayNight.NoActionBar">
<!-- Status bar -->
<item name="android:statusBarColor">?attr/colorSurface</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
</style>
</resources>

View File

@@ -0,0 +1,46 @@
<resources>
<string name="app_name">VK Chat Manager</string>
<string name="user_link_hint">Ссылка на пользователя</string>
<string name="list_button">Список</string>
<string name="add_button">Добавить</string>
<string name="show_button">Показать</string>
<string name="remove_button">Удалить</string>
<string name="office_tab">AG Офис</string>
<string name="retail_tab">AG Розница</string>
<string name="warehouse_tab">AG Склад</string>
<string name="coffee_tab">AG Кофейни</string>
<string name="other_tab">Другое</string>
<string name="chats_updated_message">Список чатов обновлен</string>
<string name="chats_update_error_message">Ошибка обновления чатов</string>
<string name="users_loaded_message">Пользователей: %d</string>
<string name="user_list_empty">Список пользователей пуст</string>
<string name="users_dialog_title">Пользователи</string>
<string name="ok_button">OK</string>
<string name="no_chats_or_users_selected_message">Не выбраны чаты или пользователи</string>
<string name="add_users_dialog_message">Добавить пользователей:</string>
<string name="remove_users_dialog_message">Удалить пользователей:</string>
<string name="in_chats_dialog_message">В чаты:</string>
<string name="confirmation_dialog_title">Подтверждение</string>
<string name="confirm_button">Подтвердить</string>
<string name="cancel_button">Отмена</string>
<string name="operation_complete_message">Операция завершена</string>
<string name="action_refresh">Обновить</string>
<string name="action_select_all">Выбрать все</string>
<string name="action_deselect_all">Снять выбор</string>
<string name="action_token_status">Статус токена</string>
<string name="token_status_title">Статус токена</string>
<string name="token_status_perpetual">Токен бессрочный</string>
<string name="token_status_expires_in">Токен истекает через: %1$dч %2$dм</string>
<string name="token_status_expired">Токен истек</string>
<string name="multilink_dialog_title">Вставьте ссылки на страницы VK, каждую с новой строки:</string>
<string name="multilink_dialog_hint">https://vk.com/id1</string>
<string name="multilink_dialog_positive_button">ОК</string>
<string name="multilink_dialog_negative_button">Отмена</string>
<string name="op_unknown_error">неизвестная ошибка</string>
<string name="op_success_add_format">✅ %1$s в %2$s: Успешно</string>
<string name="op_success_remove_format">✅ %1$s из %2$s: Успешно</string>
<string name="op_failure_format">❌ %1$s в %2$s: %3$s</string>
<string name="action_sign_out">Выйти</string>
<string name="api_error">Ошибка API: %s</string>
<string name="token_expired_message">Ваша сессия истекла. Пожалуйста, войдите снова.</string>
</resources>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.VKChatManager" parent="Theme.Material3.DynamicColors.DayNight.NoActionBar">
<!-- Status bar -->
<item name="android:statusBarColor">?attr/colorSurface</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowOptOutEdgeToEdgeEnforcement">true</item>
</style>
</resources>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
</resources>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#4D64DA</color>
</resources>

View File

@@ -0,0 +1,46 @@
<resources>
<string name="app_name">VK Chat Manager</string>
<string name="user_link_hint">User link</string>
<string name="list_button">List</string>
<string name="add_button">Add</string>
<string name="show_button">Show</string>
<string name="remove_button">Remove</string>
<string name="office_tab">AG Office</string>
<string name="retail_tab">AG Retail</string>
<string name="warehouse_tab">AG Warehouse</string>
<string name="coffee_tab">AG Coffee</string>
<string name="other_tab">Other</string>
<string name="chats_updated_message">Chat list updated</string>
<string name="chats_update_error_message">Error updating chats</string>
<string name="users_loaded_message">Users: %d</string>
<string name="user_list_empty">User list is empty</string>
<string name="users_dialog_title">Users</string>
<string name="ok_button">OK</string>
<string name="no_chats_or_users_selected_message">No chats or users selected</string>
<string name="add_users_dialog_message">Add users:</string>
<string name="remove_users_dialog_message">Remove users:</string>
<string name="in_chats_dialog_message">In chats:</string>
<string name="confirmation_dialog_title">Confirmation</string>
<string name="confirm_button">Confirm</string>
<string name="cancel_button">Cancel</string>
<string name="operation_complete_message">Operation complete</string>
<string name="action_refresh">Refresh</string>
<string name="action_select_all">Select All</string>
<string name="action_deselect_all">Deselect All</string>
<string name="action_token_status">Token Status</string>
<string name="token_status_title">Token Status</string>
<string name="token_status_perpetual">Token is perpetual</string>
<string name="token_status_expires_in">Token expires in: %1$dh %2$dm</string>
<string name="token_status_expired">Token has expired</string>
<string name="multilink_dialog_title">Paste links to VK pages, each on a new line:</string>
<string name="multilink_dialog_hint">https://vk.com/id1</string>
<string name="multilink_dialog_positive_button">OK</string>
<string name="multilink_dialog_negative_button">Cancel</string>
<string name="op_unknown_error">unknown error</string>
<string name="op_success_add_format">✅ %1$s in %2$s: Success</string>
<string name="op_success_remove_format">✅ %1$s from %2$s: Success</string>
<string name="op_failure_format">❌ %1$s in %2$s: %3$s</string>
<string name="action_sign_out">Sign Out</string>
<string name="api_error">API error: %s</string>
<string name="token_expired_message">Your session has expired. Please log in again.</string>
</resources>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Widget.VKChat.Button"
parent="Widget.Material3.Button">
<item name="cornerRadius">12dp</item>
<item name="android:textAllCaps">false</item>
</style>
</resources>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.VKChatManager"
parent="Theme.Material3.DynamicColors.DayNight.NoActionBar">
<!-- Status bar -->
<item name="android:statusBarColor">?attr/colorSurface</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
</style>
</resources>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>

4
build.gradle Normal file
View File

@@ -0,0 +1,4 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
}

23
gradle.properties Normal file
View File

@@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true

20
gradle/libs.versions.toml Normal file
View File

@@ -0,0 +1,20 @@
[versions]
agp = "9.0.0"
coreKtx = "1.17.0"
junit = "4.13.2"
junitVersion = "1.3.0"
espressoCore = "3.7.0"
appcompat = "1.7.1"
material = "1.13.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,9 @@
#Fri Jan 16 20:47:48 GMT+03:00 2026
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=a17ddd85a26b6a7f5ddb71ff8b05fc5104c0202c6e64782429790c933686c806
distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

23
settings.gradle Normal file
View File

@@ -0,0 +1,23 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "VK Chat Manager"
include ':app'