Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

259 rindas
7.0 KiB

  1. 'use strict';
  2. import * as fs from 'fs';
  3. import { EventEmitter, Uri } from 'vscode';
  4. import { GravatarDefaultStyle } from './config';
  5. import { GlobalState } from './constants';
  6. import { Container } from './container';
  7. import { GitRevisionReference } from './git/git';
  8. import { Functions, Iterables, Strings } from './system';
  9. import { MillisecondsPerDay, MillisecondsPerHour, MillisecondsPerMinute } from './system/date';
  10. import { ContactPresenceStatus } from './vsls/vsls';
  11. const _onDidFetchAvatar = new EventEmitter<{ email: string }>();
  12. _onDidFetchAvatar.event(
  13. Functions.debounce(() => {
  14. const avatars =
  15. avatarCache != null
  16. ? [
  17. ...Iterables.filterMap(avatarCache, ([key, avatar]) =>
  18. avatar.uri != null
  19. ? [
  20. key,
  21. {
  22. uri: avatar.uri.toString(),
  23. timestamp: avatar.timestamp,
  24. },
  25. ]
  26. : undefined,
  27. ),
  28. ]
  29. : undefined;
  30. void Container.context.globalState.update(GlobalState.Avatars, avatars);
  31. }, 1000),
  32. );
  33. export namespace Avatars {
  34. export const onDidFetch = _onDidFetchAvatar.event;
  35. }
  36. interface Avatar {
  37. uri?: Uri;
  38. fallback?: Uri;
  39. timestamp: number;
  40. retries: number;
  41. }
  42. interface SerializedAvatar {
  43. uri: string;
  44. timestamp: number;
  45. }
  46. let avatarCache: Map<string, Avatar> | undefined;
  47. const avatarQueue = new Map<string, Promise<Uri>>();
  48. const missingGravatarHash = '00000000000000000000000000000000';
  49. const presenceCache = new Map<ContactPresenceStatus, string>();
  50. const gitHubNoReplyAddressRegex = /^(?:(?<userId>\d+)\+)?(?<userName>[a-zA-Z\d-]{1,39})@users\.noreply\.github\.com$/;
  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. if (email == null || email.length === 0) {
  67. const avatar = createOrUpdateAvatar(
  68. `${missingGravatarHash}:${size}`,
  69. undefined,
  70. missingGravatarHash,
  71. size,
  72. defaultStyle,
  73. );
  74. return avatar.uri ?? avatar.fallback!;
  75. }
  76. const hash = Strings.md5(email.trim().toLowerCase(), 'hex');
  77. const key = `${hash}:${size}`;
  78. const avatar = createOrUpdateAvatar(
  79. key,
  80. getAvatarUriFromGitHubNoReplyAddress(email, size),
  81. hash,
  82. size,
  83. defaultStyle,
  84. );
  85. if (avatar.uri != null) return avatar.uri;
  86. let query = avatarQueue.get(key);
  87. if (query == null && repoPathOrCommit != null && hasAvatarExpired(avatar)) {
  88. query = getAvatarUriFromRemoteProvider(avatar, key, email, repoPathOrCommit, { size: size }).then(
  89. uri => uri ?? avatar.uri ?? avatar.fallback!,
  90. );
  91. avatarQueue.set(key, query);
  92. }
  93. if (query != null) return query;
  94. return avatar.uri ?? avatar.fallback!;
  95. }
  96. function createOrUpdateAvatar(
  97. key: string,
  98. uri: Uri | undefined,
  99. hash: string,
  100. size: number,
  101. defaultStyle?: GravatarDefaultStyle,
  102. ): Avatar {
  103. let avatar = avatarCache!.get(key);
  104. if (avatar == null) {
  105. avatar = {
  106. uri: uri,
  107. fallback: getAvatarUriFromGravatar(hash, size, defaultStyle),
  108. timestamp: 0,
  109. retries: 0,
  110. };
  111. avatarCache!.set(key, avatar);
  112. } else if (avatar.fallback == null) {
  113. avatar.fallback = getAvatarUriFromGravatar(hash, size, defaultStyle);
  114. }
  115. return avatar;
  116. }
  117. function ensureAvatarCache(cache: Map<string, Avatar> | undefined): asserts cache is Map<string, Avatar> {
  118. if (cache == null) {
  119. const avatars: [string, Avatar][] | undefined = Container.context.globalState
  120. .get<[string, SerializedAvatar][]>(GlobalState.Avatars)
  121. ?.map<[string, Avatar]>(([key, avatar]) => [
  122. key,
  123. {
  124. uri: Uri.parse(avatar.uri),
  125. timestamp: avatar.timestamp,
  126. retries: 0,
  127. },
  128. ]);
  129. avatarCache = new Map<string, Avatar>(avatars);
  130. }
  131. }
  132. function hasAvatarExpired(avatar: Avatar) {
  133. return Date.now() >= avatar.timestamp + retryDecay[Math.min(avatar.retries, retryDecay.length - 1)];
  134. }
  135. function getAvatarUriFromGravatar(
  136. hash: string,
  137. size: number,
  138. defaultStyle: GravatarDefaultStyle = GravatarDefaultStyle.Robot,
  139. ): Uri {
  140. return Uri.parse(`https://www.gravatar.com/avatar/${hash}.jpg?s=${size}&d=${defaultStyle}`);
  141. }
  142. function getAvatarUriFromGitHubNoReplyAddress(email: string, size: number = 16): Uri | undefined {
  143. const match = gitHubNoReplyAddressRegex.exec(email);
  144. if (match == null) return undefined;
  145. const [, userId, userName] = match;
  146. return Uri.parse(`https://avatars.githubusercontent.com/${userId ? `u/${userId}` : userName}?size=${size}`);
  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 (typeof repoPathOrCommit === 'string') {
  159. // const remote = await Container.git.getRemoteWithApiProvider(repoPathOrCommit);
  160. // account = await remote?.provider.getAccountForEmail(email, { avatarSize: size });
  161. // } else {
  162. if (typeof repoPathOrCommit !== 'string') {
  163. const remote = await Container.git.getRemoteWithApiProvider(repoPathOrCommit.repoPath);
  164. account = await remote?.provider.getAccountForCommit(repoPathOrCommit.ref, { avatarSize: size });
  165. }
  166. if (account == null) {
  167. // If we have no account assume that won't change (without a reset), so set the timestamp to "never expire"
  168. avatar.uri = undefined;
  169. avatar.timestamp = Number.MAX_SAFE_INTEGER;
  170. avatar.retries = 0;
  171. return undefined;
  172. }
  173. avatar.uri = Uri.parse(account.avatarUrl);
  174. avatar.timestamp = Date.now();
  175. avatar.retries = 0;
  176. if (account.email != null && Strings.equalsIgnoreCase(email, account.email)) {
  177. avatarCache.set(`${Strings.md5(account.email.trim().toLowerCase(), 'hex')}:${size}`, { ...avatar });
  178. }
  179. _onDidFetchAvatar.fire({ email: email });
  180. return avatar.uri;
  181. } catch {
  182. avatar.uri = undefined;
  183. avatar.timestamp = Date.now();
  184. avatar.retries++;
  185. return undefined;
  186. } finally {
  187. avatarQueue.delete(key);
  188. }
  189. }
  190. export function getPresenceDataUri(status: ContactPresenceStatus) {
  191. let dataUri = presenceCache.get(status);
  192. if (dataUri == null) {
  193. const contents = fs
  194. .readFileSync(Container.context.asAbsolutePath(`images/dark/icon-presence-${status}.svg`))
  195. .toString('base64');
  196. dataUri = encodeURI(`data:image/svg+xml;base64,${contents}`);
  197. presenceCache.set(status, dataUri);
  198. }
  199. return dataUri;
  200. }
  201. export function resetAvatarCache(reset: 'all' | 'failed' | 'fallback') {
  202. switch (reset) {
  203. case 'all':
  204. void Container.context.globalState.update(GlobalState.Avatars, undefined);
  205. avatarCache?.clear();
  206. avatarQueue.clear();
  207. break;
  208. case 'failed':
  209. for (const avatar of avatarCache?.values() ?? []) {
  210. // Reset failed requests
  211. if (avatar.uri == null) {
  212. avatar.timestamp = 0;
  213. avatar.retries = 0;
  214. }
  215. }
  216. break;
  217. case 'fallback':
  218. for (const avatar of avatarCache?.values() ?? []) {
  219. avatar.fallback = undefined;
  220. }
  221. break;
  222. }
  223. }