Initial commit
This commit is contained in:
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
514
app/src/main/java/com/anabasis/vkchatmanager/MainActivity.java
Normal file
514
app/src/main/java/com/anabasis/vkchatmanager/MainActivity.java
Normal 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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.anabasis.vkchatmanager.network;
|
||||
|
||||
public class TokenExpiredException extends Exception {
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user