Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import java.io.IOException;
import java.net.URL;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

Expand All @@ -14,6 +16,7 @@
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
Expand All @@ -32,8 +35,10 @@
*/
public class AvatarService {
private static final String AVATAR_URL = "https://avatars.githubusercontent.com/%s?s=24&v=4";
private static final Duration RETRY_DELAY = Duration.ofMinutes(5);
private Map<String, Image> avatarCache = new ConcurrentHashMap<>();
private Map<String, Job> jobs = new ConcurrentHashMap<>();
private Map<String, Instant> retryTimes = new ConcurrentHashMap<>();

private Image defaultGithubAvatar;
private Image defaultUserAvatar;
Expand Down Expand Up @@ -100,33 +105,34 @@ public synchronized Image getAvatar(Display display, String user) {
if (image != null) {
return image;
} else {
if (!jobs.containsKey(user)) {
Instant retryTime = retryTimes.get(user);
if (!jobs.containsKey(user) && (retryTime == null || !Instant.now().isBefore(retryTime))) {
Job downloadJob = new Job("Download avatar for " + user) {
@Override
protected IStatus run(IProgressMonitor monitor) {
Image downloadedImage = null;
try {
URL url = new URL(String.format(AVATAR_URL, user));
Image downloadedImage;
try (var stream = url.openStream()) {
downloadedImage = new Image(display, stream);
}
} catch (IOException e) {
CopilotCore.LOGGER.error(e);
}
if (downloadedImage != null) {
Image result = downloadedImage;
// as the image is not always 24x24 even we set it in parameters, resize here if not
if (result.getBounds().width != 24 || result.getBounds().height != 24) {
result = UiUtils.resizeImage(display, downloadedImage, 24, 24);
downloadedImage.dispose();
}
avatarCache.put(user, result);
} catch (IOException | SWTException e) {
CopilotCore.LOGGER.error(e);
} finally {
jobs.remove(user);
}
return Status.OK_STATUS;
}
};
jobs.put(user, downloadJob);
retryTimes.put(user, Instant.now().plus(RETRY_DELAY));
downloadJob.schedule();
}
return defaultUserAvatar;
Expand Down