1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
/*
* mygram-droid: Android TV client for Foldergram.
* Copyright (C) 2026 Danilo M. <danix@danix.xyz>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package mygram.droid;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.OptIn;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
/**
* Fullscreen player over a blurred backdrop. Up/Down: post. Left/Right: slide,
* or seek on a single video. OK: pause. Double OK: like.
*/
public final class ViewerActivity extends Activity {
private static final long SEEK_MS = 10_000, TICK_MS = 100;
/** Frame grabs block on the network; keep them off the API pool. */
private static final ExecutorService FRAMES = Executors.newSingleThreadExecutor();
private static final ViewGroup.LayoutParams FILL = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
private final Handler handler = new Handler(Looper.getMainLooper());
private final Runnable ticker = this::tick;
private final DoubleOk doubleOk = new DoubleOk();
private ExoPlayer player;
private PlayerView video;
private ImageView backdrop, photo, pauseIcon, heart, bigHeart;
private ProgressBar progress;
private TextView message;
private int index, slide;
/** Bumped on every slide change; late callbacks for older slides are dropped. */
private volatile int generation;
private boolean paused, failed, loadingMore;
private long photoElapsed;
@Override
@OptIn(markerClass = UnstableApi.class)
protected void onCreate(Bundle state) {
super.onCreate(state);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
FrameLayout root = new FrameLayout(this);
root.setBackgroundColor(Color.BLACK);
backdrop = new ImageView(this);
backdrop.setScaleType(ImageView.ScaleType.CENTER_CROP);
Ui.blur(backdrop, 40);
root.addView(backdrop, FILL);
View dim = new View(this);
dim.setBackgroundColor(0x66000000);
root.addView(dim, FILL);
photo = new ImageView(this);
photo.setScaleType(ImageView.ScaleType.FIT_CENTER);
root.addView(photo, FILL);
player = new ExoPlayer.Builder(this).build();
player.addListener(new Player.Listener() {
@Override
public void onPlaybackStateChanged(int s) {
if (s == Player.STATE_ENDED)
advance();
}
@Override
public void onPlayerError(PlaybackException e) {
fail();
}
});
video = new PlayerView(this);
video.setUseController(false);
video.setShutterBackgroundColor(Color.TRANSPARENT);
video.setPlayer(player);
root.addView(video, FILL);
message = Ui.text(this, "", 20);
message.setGravity(Gravity.CENTER);
root.addView(message, FILL);
progress = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
progress.setMax(1000);
root.addView(progress, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ui.dp(this, 4), Gravity.BOTTOM));
pauseIcon = overlay(root, R.drawable.ic_pause, "Paused", 32, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
heart = overlay(root, R.drawable.ic_favorite, "Liked", 32, Gravity.BOTTOM | Gravity.END);
bigHeart = overlay(root, R.drawable.ic_favorite, "Liked", 160, Gravity.CENTER);
heart.setColorFilter(Ui.RED);
bigHeart.setColorFilter(Ui.RED);
setContentView(root);
if (!Playlist.posts.isEmpty()) {
show(Playlist.start);
} else if (Playlist.reelsSeed != 0) {
message.setText("Loading…");
maybeLoadMore();
} else {
finish(); // process restarted; the list is gone
}
}
private ImageView overlay(FrameLayout root, int icon, String description, int sizeDp, int gravity) {
ImageView v = new ImageView(this);
v.setImageResource(icon);
v.setContentDescription(description);
v.setVisibility(View.GONE);
int s = Ui.dp(this, sizeDp), m = Ui.dp(this, 24);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(s, s, gravity);
lp.setMargins(m, m, m, m);
root.addView(v, lp);
return v;
}
private Post post() {
return Playlist.posts.get(index);
}
private Post.Media media() {
return post().media.get(slide);
}
private void show(int i) {
index = i;
slide = 0;
maybeLoadMore();
showSlide();
}
private void showSlide() {
Post.Media m = media();
int gen = ++generation;
paused = false;
failed = false;
photoElapsed = 0;
message.setText("");
pauseIcon.setVisibility(View.GONE);
heart.setVisibility(Likes.has(post().id) ? View.VISIBLE : View.GONE);
Glide.with(this).load(m.video ? m.thumbnailUrl : m.previewUrl).override(200).into(backdrop);
if (m.video) {
Glide.with(this).clear(photo);
video.setVisibility(View.VISIBLE);
player.setMediaItem(MediaItem.fromUri(m.previewUrl));
player.prepare();
player.play();
randomFrame(m, gen);
} else {
player.stop();
video.setVisibility(View.GONE);
Glide.with(this).load(m.previewUrl).listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(GlideException e, Object model, Target<Drawable> target, boolean first) {
if (gen == generation)
fail();
return false;
}
@Override
public boolean onResourceReady(Drawable d, Object model, Target<Drawable> target, DataSource source,
boolean first) {
return false;
}
}).into(photo);
}
tick();
}
/** Swaps the video backdrop for a frame from 20-80 % of the clip; ends are often black. */
private void randomFrame(Post.Media m, int gen) {
if (m.durationMs <= 0)
return;
long us = (long) (m.durationMs * 1000 * (0.2 + 0.6 * ThreadLocalRandom.current().nextDouble()));
Api.async(FRAMES, () -> {
if (gen != generation)
return null;
try (MediaMetadataRetriever r = new MediaMetadataRetriever()) {
r.setDataSource(m.previewUrl, new HashMap<>(Api.cookieHeaders(m.previewUrl)));
return r.getScaledFrameAtTime(us, MediaMetadataRetriever.OPTION_CLOSEST_SYNC, 320, 180);
}
}, frame -> {
if (frame != null && gen == generation) {
Glide.with(this).clear(backdrop);
backdrop.setImageBitmap(frame);
}
}, e -> {
// keep the blurred server thumbnail
});
}
/** Drives the progress bar and the photo timer. */
private void tick() {
handler.removeCallbacks(ticker);
if (media().video && !failed) {
long d = player.getDuration();
progress.setProgress(d > 0 ? (int) (1000 * player.getCurrentPosition() / d) : 0);
} else {
if (!paused)
photoElapsed += TICK_MS;
long total = Prefs.photoSeconds() * 1000L;
progress.setProgress((int) (1000 * Math.min(photoElapsed, total) / total));
if (photoElapsed >= total) {
advance();
return;
}
}
handler.postDelayed(ticker, TICK_MS);
}
private void advance() {
if (slide < post().media.size() - 1) {
slide++;
showSlide();
} else if (index < Playlist.posts.size() - 1) {
show(index + 1);
} else {
setPaused(true); // end of the list
}
}
private void fail() {
failed = true;
photoElapsed = 0;
message.setText("Cannot load this post");
if (media().video)
player.stop();
}
private void setPaused(boolean p) {
paused = p;
pauseIcon.setVisibility(p ? View.VISIBLE : View.GONE);
if (media().video && !failed) {
if (p)
player.pause();
else
player.play();
}
}
private void step(int dir) {
if (post().media.size() > 1) {
int s = slide + dir;
if (s >= 0 && s < post().media.size()) {
slide = s;
showSlide();
}
} else if (media().video && !failed) {
player.seekTo(Math.max(0, player.getCurrentPosition() + dir * SEEK_MS));
}
}
private void toggleLike() {
Post p = post();
boolean on = !Likes.has(p.id);
Likes.set(p.id, on);
heart.setVisibility(on ? View.VISIBLE : View.GONE);
if (on) {
bigHeart.setAlpha(1f);
bigHeart.setVisibility(View.VISIBLE);
bigHeart.animate().alpha(0f).setDuration(700).withEndAction(() -> bigHeart.setVisibility(View.GONE)).start();
}
Api.async(() -> {
Api.setLike(p.id, on);
return true;
}, ok -> {
}, e -> {
Likes.set(p.id, !on);
if (!Playlist.posts.isEmpty() && post() == p)
heart.setVisibility(on ? View.GONE : View.VISIBLE);
Toast.makeText(this, "Like failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
/** Reels only: fetches the next page when three posts remain. */
private void maybeLoadMore() {
if (Playlist.reelsSeed == 0 || loadingMore || index < Playlist.posts.size() - 3)
return;
loadingMore = true;
int page = Playlist.reelsPage + 1;
Api.async(() -> Api.reels(Playlist.reelsSeed, page), o -> {
loadingMore = false;
Playlist.reelsPage = page;
boolean first = Playlist.posts.isEmpty();
Playlist.posts.addAll(Post.list(o, Prefs.server()));
if (!o.optBoolean("hasMore"))
Playlist.reelsSeed = 0;
if (first && !Playlist.posts.isEmpty())
show(0);
}, e -> {
loadingMore = false;
if (Playlist.posts.isEmpty())
message.setText("Cannot load reels. Press Down to retry.");
else
Toast.makeText(this, "Cannot load more: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
@Override
public boolean onKeyDown(int code, KeyEvent e) {
if (Playlist.posts.isEmpty()) {
if (code == KeyEvent.KEYCODE_DPAD_DOWN)
maybeLoadMore();
return super.onKeyDown(code, e);
}
switch (code) {
case KeyEvent.KEYCODE_DPAD_UP:
if (index > 0)
show(index - 1);
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (index < Playlist.posts.size() - 1)
show(index + 1);
else
maybeLoadMore(); // retry a failed page
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
step(-1);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
step(1);
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (e.getRepeatCount() > 0)
return true;
// Pause at once; a second press undoes it and likes instead.
setPaused(!paused);
if (doubleOk.press(e.getEventTime()))
toggleLike();
return true;
default:
return super.onKeyDown(code, e);
}
}
@Override
protected void onPause() {
super.onPause();
if (!Playlist.posts.isEmpty() && !paused)
setPaused(true);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
generation++;
player.release();
}
}
|