您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

301 行
9.0 KiB

  1. import { EventEmitter, Uri } from 'vscode';
  2. import { GravatarDefaultStyle } from './config';
  3. import { ContextKeys } from './constants';
  4. import { Container } from './container';
  5. import { getContext } from './context';
  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?: undefined,
  63. options?: { defaultStyle?: GravatarDefaultStyle; size?: number },
  64. ): Uri;
  65. export function getAvatarUri(
  66. email: string | undefined,
  67. repoPathOrCommit: string | { ref: string; repoPath: string },
  68. options?: { defaultStyle?: GravatarDefaultStyle; size?: number },
  69. ): Uri | Promise<Uri>;
  70. export function getAvatarUri(
  71. email: string | undefined,
  72. repoPathOrCommit: string | { ref: string; repoPath: string } | undefined,
  73. options?: { defaultStyle?: GravatarDefaultStyle; size?: number },
  74. ): Uri | Promise<Uri> {
  75. return getAvatarUriCore(email, repoPathOrCommit, options);
  76. }
  77. export function getCachedAvatarUri(email: string | undefined, options?: { size?: number }): Uri | undefined {
  78. return getAvatarUriCore(email, undefined, { ...options, cached: true });
  79. }
  80. function getAvatarUriCore(
  81. email: string | undefined,
  82. repoPathOrCommit: string | { ref: string; repoPath: string } | undefined,
  83. options?: { cached: true; defaultStyle?: GravatarDefaultStyle; size?: number },
  84. ): Uri | undefined;
  85. function getAvatarUriCore(
  86. email: string | undefined,
  87. repoPathOrCommit: string | { ref: string; repoPath: string } | undefined,
  88. options?: { defaultStyle?: GravatarDefaultStyle; size?: number },
  89. ): Uri | Promise<Uri>;
  90. function getAvatarUriCore(
  91. email: string | undefined,
  92. repoPathOrCommit: string | { ref: string; repoPath: string } | undefined,
  93. options?: { cached?: boolean; defaultStyle?: GravatarDefaultStyle; size?: number },
  94. ): Uri | Promise<Uri> | undefined {
  95. ensureAvatarCache(avatarCache);
  96. // Double the size to avoid blurring on the retina screen
  97. const size = (options?.size ?? 16) * 2;
  98. if (!email) {
  99. const avatar = createOrUpdateAvatar(
  100. `${missingGravatarHash}:${size}`,
  101. undefined,
  102. size,
  103. missingGravatarHash,
  104. options?.defaultStyle,
  105. );
  106. return avatar.uri ?? avatar.fallback!;
  107. }
  108. const hash = md5(email.trim().toLowerCase(), 'hex');
  109. const key = `${hash}:${size}`;
  110. const avatar = createOrUpdateAvatar(key, email, size, hash, options?.defaultStyle);
  111. if (avatar.uri != null) return avatar.uri;
  112. if (!options?.cached && repoPathOrCommit != null && getContext(ContextKeys.HasConnectedRemotes)) {
  113. let query = avatarQueue.get(key);
  114. if (query == null && hasAvatarExpired(avatar)) {
  115. query = getAvatarUriFromRemoteProvider(avatar, key, email, repoPathOrCommit, { size: size }).then(
  116. uri => uri ?? avatar.uri ?? avatar.fallback!,
  117. );
  118. avatarQueue.set(
  119. key,
  120. query.finally(() => avatarQueue.delete(key)),
  121. );
  122. }
  123. return query ?? avatar.fallback!;
  124. }
  125. return options?.cached ? avatar.uri : avatar.uri ?? avatar.fallback!;
  126. }
  127. function createOrUpdateAvatar(
  128. key: string,
  129. email: string | undefined,
  130. size: number,
  131. hash: string,
  132. defaultStyle?: GravatarDefaultStyle,
  133. ): Avatar {
  134. let avatar = avatarCache!.get(key);
  135. if (avatar == null) {
  136. avatar = {
  137. uri: email != null && email.length !== 0 ? getAvatarUriFromGitHubNoReplyAddress(email, size) : undefined,
  138. fallback: getAvatarUriFromGravatar(hash, size, defaultStyle),
  139. timestamp: 0,
  140. retries: 0,
  141. };
  142. avatarCache!.set(key, avatar);
  143. } else if (avatar.fallback == null) {
  144. avatar.fallback = getAvatarUriFromGravatar(hash, size, defaultStyle);
  145. }
  146. return avatar;
  147. }
  148. function ensureAvatarCache(cache: Map<string, Avatar> | undefined): asserts cache is Map<string, Avatar> {
  149. if (cache == null) {
  150. const avatars: [string, Avatar][] | undefined = Container.instance.storage
  151. .get('avatars')
  152. ?.map<[string, Avatar]>(([key, avatar]) => [
  153. key,
  154. {
  155. uri: Uri.parse(avatar.uri),
  156. timestamp: avatar.timestamp,
  157. retries: 0,
  158. },
  159. ]);
  160. avatarCache = new Map<string, Avatar>(avatars);
  161. }
  162. }
  163. function hasAvatarExpired(avatar: Avatar) {
  164. return Date.now() >= avatar.timestamp + retryDecay[Math.min(avatar.retries, retryDecay.length - 1)];
  165. }
  166. function getAvatarUriFromGravatar(
  167. hash: string,
  168. size: number,
  169. defaultStyle: GravatarDefaultStyle = GravatarDefaultStyle.Robot,
  170. ): Uri {
  171. return Uri.parse(`https://www.gravatar.com/avatar/${hash}?s=${size}&d=${defaultStyle}`);
  172. }
  173. function getAvatarUriFromGitHubNoReplyAddress(email: string, size: number = 16): Uri | undefined {
  174. const parts = getGitHubNoReplyAddressParts(email);
  175. if (parts == null || !equalsIgnoreCase(parts.authority, 'github.com')) return undefined;
  176. return Uri.parse(
  177. `https://avatars.githubusercontent.com/${parts.userId ? `u/${parts.userId}` : parts.login}?size=${size}`,
  178. );
  179. }
  180. async function getAvatarUriFromRemoteProvider(
  181. avatar: Avatar,
  182. key: string,
  183. email: string,
  184. repoPathOrCommit: string | { ref: string; repoPath: string },
  185. { size = 16 }: { size?: number } = {},
  186. ) {
  187. ensureAvatarCache(avatarCache);
  188. try {
  189. let account;
  190. // if (typeof repoPathOrCommit === 'string') {
  191. // const remote = await Container.instance.git.getRichRemoteProvider(repoPathOrCommit);
  192. // account = await remote?.provider.getAccountForEmail(email, { avatarSize: size });
  193. // } else {
  194. if (typeof repoPathOrCommit !== 'string') {
  195. const remote = await Container.instance.git.getBestRemoteWithRichProvider(repoPathOrCommit.repoPath);
  196. account = await remote?.provider.getAccountForCommit(repoPathOrCommit.ref, { avatarSize: size });
  197. }
  198. if (account?.avatarUrl == null) {
  199. // If we have no account assume that won't change (without a reset), so set the timestamp to "never expire"
  200. avatar.uri = undefined;
  201. avatar.timestamp = maxSmallIntegerV8;
  202. avatar.retries = 0;
  203. return undefined;
  204. }
  205. avatar.uri = Uri.parse(account.avatarUrl);
  206. avatar.timestamp = Date.now();
  207. avatar.retries = 0;
  208. if (account.email != null && equalsIgnoreCase(email, account.email)) {
  209. avatarCache.set(`${md5(account.email.trim().toLowerCase(), 'hex')}:${size}`, { ...avatar });
  210. }
  211. _onDidFetchAvatar.fire({ email: email });
  212. return avatar.uri;
  213. } catch {
  214. avatar.uri = undefined;
  215. avatar.timestamp = Date.now();
  216. avatar.retries++;
  217. return undefined;
  218. }
  219. }
  220. const presenceStatusColorMap = new Map<ContactPresenceStatus, string>([
  221. ['online', '#28ca42'],
  222. ['away', '#cecece'],
  223. ['busy', '#ca5628'],
  224. ['dnd', '#ca5628'],
  225. ['offline', '#cecece'],
  226. ]);
  227. export function getPresenceDataUri(status: ContactPresenceStatus) {
  228. let dataUri = presenceCache.get(status);
  229. if (dataUri == null) {
  230. const contents = base64(`<?xml version="1.0" encoding="utf-8"?>
  231. <svg xmlns="http://www.w3.org/2000/svg" width="4" height="16" viewBox="0 0 4 16">
  232. <circle cx="2" cy="14" r="2" fill="${presenceStatusColorMap.get(status)!}"/>
  233. </svg>`);
  234. dataUri = encodeURI(`data:image/svg+xml;base64,${contents}`);
  235. presenceCache.set(status, dataUri);
  236. }
  237. return dataUri;
  238. }
  239. export function resetAvatarCache(reset: 'all' | 'failed' | 'fallback') {
  240. switch (reset) {
  241. case 'all':
  242. void Container.instance.storage.delete('avatars');
  243. avatarCache?.clear();
  244. avatarQueue.clear();
  245. break;
  246. case 'failed':
  247. for (const avatar of avatarCache?.values() ?? []) {
  248. // Reset failed requests
  249. if (avatar.uri == null) {
  250. avatar.timestamp = 0;
  251. avatar.retries = 0;
  252. }
  253. }
  254. break;
  255. case 'fallback':
  256. for (const avatar of avatarCache?.values() ?? []) {
  257. avatar.fallback = undefined;
  258. }
  259. break;
  260. }
  261. }