You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

268 line
7.6 KiB

3 年之前
  1. import { EventEmitter, Uri } from 'vscode';
  2. import { GravatarDefaultStyle } from './config';
  3. import { configuration } from './configuration';
  4. import { Container } from './container';
  5. import type { GitRevisionReference } from './git/models/reference';
  6. import { getGitHubNoReplyAddressParts } from './git/remotes/github';
  7. import type { StoredAvatar } from './storage';
  8. import { debounce } from './system/function';
  9. import { filterMap } from './system/iterable';
  10. import { base64, equalsIgnoreCase, md5 } from './system/string';
  11. import type { ContactPresenceStatus } from './vsls/vsls';
  12. const maxSmallIntegerV8 = 2 ** 30; // Max number that can be stored in V8's smis (small integers)
  13. const _onDidFetchAvatar = new EventEmitter<{ email: string }>();
  14. _onDidFetchAvatar.event(
  15. debounce(() => {
  16. const avatars =
  17. avatarCache != null
  18. ? [
  19. ...filterMap(avatarCache, ([key, avatar]) =>
  20. avatar.uri != null
  21. ? ([
  22. key,
  23. {
  24. uri: avatar.uri.toString(),
  25. timestamp: avatar.timestamp,
  26. },
  27. ] as [string, StoredAvatar])
  28. : undefined,
  29. ),
  30. ]
  31. : undefined;
  32. void Container.instance.storage.store('avatars', avatars);
  33. }, 1000),
  34. );
  35. export namespace Avatars {
  36. export const onDidFetch = _onDidFetchAvatar.event;
  37. }
  38. interface Avatar {
  39. uri?: Uri;
  40. fallback?: Uri;
  41. timestamp: number;
  42. retries: number;
  43. }
  44. let avatarCache: Map<string, Avatar> | undefined;
  45. const avatarQueue = new Map<string, Promise<Uri>>();
  46. const missingGravatarHash = '00000000000000000000000000000000';
  47. const presenceCache = new Map<ContactPresenceStatus, string>();
  48. const millisecondsPerMinute = 60 * 1000;
  49. const millisecondsPerHour = 60 * 60 * 1000;
  50. const millisecondsPerDay = 24 * 60 * 60 * 1000;
  51. const retryDecay = [
  52. millisecondsPerDay * 7, // First item is cache expiration (since retries will be 0)
  53. millisecondsPerMinute,
  54. millisecondsPerMinute * 5,
  55. millisecondsPerMinute * 10,
  56. millisecondsPerHour,
  57. millisecondsPerDay,
  58. millisecondsPerDay * 7,
  59. ];
  60. export function getAvatarUri(
  61. email: string | undefined,
  62. repoPathOrCommit: string | GitRevisionReference | undefined,
  63. { defaultStyle, size = 16 }: { defaultStyle?: GravatarDefaultStyle; size?: number } = {},
  64. ): Uri | Promise<Uri> {
  65. ensureAvatarCache(avatarCache);
  66. // Double the size to avoid blurring on the retina screen
  67. size *= 2;
  68. if (!email) {
  69. const avatar = createOrUpdateAvatar(
  70. `${missingGravatarHash}:${size}`,
  71. undefined,
  72. size,
  73. missingGravatarHash,
  74. defaultStyle,
  75. );
  76. return avatar.uri ?? avatar.fallback!;
  77. }
  78. const hash = md5(email.trim().toLowerCase(), 'hex');
  79. const key = `${hash}:${size}`;
  80. const avatar = createOrUpdateAvatar(key, email, size, hash, defaultStyle);
  81. if (avatar.uri != null) return avatar.uri;
  82. let query = avatarQueue.get(key);
  83. if (query == null && repoPathOrCommit != null && hasAvatarExpired(avatar)) {
  84. query = getAvatarUriFromRemoteProvider(avatar, key, email, repoPathOrCommit, { size: size }).then(
  85. uri => uri ?? avatar.uri ?? avatar.fallback!,
  86. );
  87. avatarQueue.set(
  88. key,
  89. query.finally(() => avatarQueue.delete(key)),
  90. );
  91. }
  92. if (query != null) return query;
  93. return avatar.uri ?? avatar.fallback!;
  94. }
  95. function createOrUpdateAvatar(
  96. key: string,
  97. email: string | undefined,
  98. size: number,
  99. hash: string,
  100. defaultStyle?: GravatarDefaultStyle,
  101. ): Avatar {
  102. let avatar = avatarCache!.get(key);
  103. if (avatar == null) {
  104. avatar = {
  105. uri: email != null && email.length !== 0 ? getAvatarUriFromGitHubNoReplyAddress(email, size) : undefined,
  106. fallback: getAvatarUriFromGravatar(hash, size, defaultStyle),
  107. timestamp: 0,
  108. retries: 0,
  109. };
  110. avatarCache!.set(key, avatar);
  111. } else if (avatar.fallback == null) {
  112. avatar.fallback = getAvatarUriFromGravatar(hash, size, defaultStyle);
  113. }
  114. return avatar;
  115. }
  116. function ensureAvatarCache(cache: Map<string, Avatar> | undefined): asserts cache is Map<string, Avatar> {
  117. if (cache == null) {
  118. const avatars: [string, Avatar][] | undefined = Container.instance.storage
  119. .get('avatars')
  120. ?.map<[string, Avatar]>(([key, avatar]) => [
  121. key,
  122. {
  123. uri: Uri.parse(avatar.uri),
  124. timestamp: avatar.timestamp,
  125. retries: 0,
  126. },
  127. ]);
  128. avatarCache = new Map<string, Avatar>(avatars);
  129. }
  130. }
  131. function hasAvatarExpired(avatar: Avatar) {
  132. return Date.now() >= avatar.timestamp + retryDecay[Math.min(avatar.retries, retryDecay.length - 1)];
  133. }
  134. function getAvatarUriFromGravatar(
  135. hash: string,
  136. size: number,
  137. defaultStyle: GravatarDefaultStyle = GravatarDefaultStyle.Robot,
  138. ): Uri {
  139. return Uri.parse(`https://www.gravatar.com/avatar/${hash}?s=${size}&d=${defaultStyle}`);
  140. }
  141. function getAvatarUriFromGitHubNoReplyAddress(email: string, size: number = 16): Uri | undefined {
  142. const parts = getGitHubNoReplyAddressParts(email);
  143. if (parts == null || !equalsIgnoreCase(parts.authority, 'github.com')) return undefined;
  144. return Uri.parse(
  145. `https://avatars.githubusercontent.com/${parts.userId ? `u/${parts.userId}` : parts.login}?size=${size}`,
  146. );
  147. }
  148. async function getAvatarUriFromRemoteProvider(
  149. avatar: Avatar,
  150. key: string,
  151. email: string,
  152. repoPathOrCommit: string | GitRevisionReference,
  153. { size = 16 }: { size?: number } = {},
  154. ) {
  155. ensureAvatarCache(avatarCache);
  156. try {
  157. let account;
  158. if (configuration.get('integrations.enabled')) {
  159. // if (typeof repoPathOrCommit === 'string') {
  160. // const remote = await Container.instance.git.getRichRemoteProvider(repoPathOrCommit);
  161. // account = await remote?.provider.getAccountForEmail(email, { avatarSize: size });
  162. // } else {
  163. if (typeof repoPathOrCommit !== 'string') {
  164. const remote = await Container.instance.git.getBestRemoteWithRichProvider(repoPathOrCommit.repoPath);
  165. account = await remote?.provider.getAccountForCommit(repoPathOrCommit.ref, { avatarSize: size });
  166. }
  167. }
  168. if (account?.avatarUrl == null) {
  169. // If we have no account assume that won't change (without a reset), so set the timestamp to "never expire"
  170. avatar.uri = undefined;
  171. avatar.timestamp = maxSmallIntegerV8;
  172. avatar.retries = 0;
  173. return undefined;
  174. }
  175. avatar.uri = Uri.parse(account.avatarUrl);
  176. avatar.timestamp = Date.now();
  177. avatar.retries = 0;
  178. if (account.email != null && equalsIgnoreCase(email, account.email)) {
  179. avatarCache.set(`${md5(account.email.trim().toLowerCase(), 'hex')}:${size}`, { ...avatar });
  180. }
  181. _onDidFetchAvatar.fire({ email: email });
  182. return avatar.uri;
  183. } catch {
  184. avatar.uri = undefined;
  185. avatar.timestamp = Date.now();
  186. avatar.retries++;
  187. return undefined;
  188. }
  189. }
  190. const presenceStatusColorMap = new Map<ContactPresenceStatus, string>([
  191. ['online', '#28ca42'],
  192. ['away', '#cecece'],
  193. ['busy', '#ca5628'],
  194. ['dnd', '#ca5628'],
  195. ['offline', '#cecece'],
  196. ]);
  197. export function getPresenceDataUri(status: ContactPresenceStatus) {
  198. let dataUri = presenceCache.get(status);
  199. if (dataUri == null) {
  200. const contents = base64(`<?xml version="1.0" encoding="utf-8"?>
  201. <svg xmlns="http://www.w3.org/2000/svg" width="4" height="16" viewBox="0 0 4 16">
  202. <circle cx="2" cy="14" r="2" fill="${presenceStatusColorMap.get(status)!}"/>
  203. </svg>`);
  204. dataUri = encodeURI(`data:image/svg+xml;base64,${contents}`);
  205. presenceCache.set(status, dataUri);
  206. }
  207. return dataUri;
  208. }
  209. export function resetAvatarCache(reset: 'all' | 'failed' | 'fallback') {
  210. switch (reset) {
  211. case 'all':
  212. void Container.instance.storage.delete('avatars');
  213. avatarCache?.clear();
  214. avatarQueue.clear();
  215. break;
  216. case 'failed':
  217. for (const avatar of avatarCache?.values() ?? []) {
  218. // Reset failed requests
  219. if (avatar.uri == null) {
  220. avatar.timestamp = 0;
  221. avatar.retries = 0;
  222. }
  223. }
  224. break;
  225. case 'fallback':
  226. for (const avatar of avatarCache?.values() ?? []) {
  227. avatar.fallback = undefined;
  228. }
  229. break;
  230. }
  231. }