Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow fetching by texture IDs #42

Merged
merged 4 commits into from
Dec 27, 2024
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions src/worker/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export enum RequestedKind {
export enum IdentityKind {
Uuid,
Username,
TextureID,
}

export enum TextureKind {
Expand Down Expand Up @@ -126,6 +127,8 @@ export function interpretRequest(request: Request): CraftheadRequest | null {
} else if (identity.length === 36) {
identity = identity.replaceAll('-', '');
identityType = IdentityKind.Uuid;
} else if (identity.length === 64) {
identityType = IdentityKind.TextureID;
} else {
return null;
}
Expand Down
60 changes: 49 additions & 11 deletions src/worker/services/mojang/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default class MojangRequestService {
* @param gatherer any promise gatherer
*/
async normalizeRequest(request: CraftheadRequest, gatherer: PromiseGatherer): Promise<CraftheadRequest> {
if (request.identityType === IdentityKind.Uuid) {
if (request.identityType === IdentityKind.Uuid || request.identityType === IdentityKind.TextureID) {
return request;
}

Expand All @@ -67,22 +67,17 @@ export default class MojangRequestService {
* Fetches a texture directly from the Mojang servers. Assumes the request has been normalized already.
*/
private async retrieveTextureDirect(request: CraftheadRequest, gatherer: PromiseGatherer, kind: TextureKind): Promise<Response> {
if (request.identityType === IdentityKind.TextureID) {
const textureResponse = await MojangRequestService.fetchTextureFromId(request.identity);
return MojangRequestService.constructTextureResponse(textureResponse, request);
}
const rawUuid = fromHex(request.identity);
if (uuidVersion(rawUuid) === 4) {
const lookup = await this.mojangApi.fetchProfile(request.identity, gatherer);
if (lookup.result) {
const textureResponse = await MojangRequestService.fetchTextureFromProfile(lookup.result, kind);
if (textureResponse) {
const buff = await textureResponse.texture.arrayBuffer();
if (buff && buff.byteLength > 0) {
return new Response(buff, {
status: 200,
headers: {
'X-Crafthead-Profile-Cache-Hit': lookup.source,
'X-Crafthead-Skin-Model': request.model || textureResponse.model || 'default',
},
});
}
return MojangRequestService.constructTextureResponse(textureResponse, request, lookup.source);
}
return new Response(STEVE_SKIN, {
status: 404,
Expand Down Expand Up @@ -110,6 +105,26 @@ export default class MojangRequestService {
});
}

private static async constructTextureResponse(textureResponse: TextureResponse, request: CraftheadRequest, source?: string): Promise<Response> {
const buff = await textureResponse.texture.arrayBuffer();
if (buff && buff.byteLength > 0) {
return new Response(buff, {
status: 200,
headers: {
'X-Crafthead-Profile-Cache-Hit': source || 'miss',
'X-Crafthead-Skin-Model': request.model || textureResponse.model || 'default',
},
});
}
return new Response(STEVE_SKIN, {
status: 404,
headers: {
'X-Crafthead-Profile-Cache-Hit': 'not-found',
'X-Crafthead-Skin-Model': 'default',
},
});
}

async retrieveSkin(request: CraftheadRequest, gatherer: PromiseGatherer): Promise<Response> {
if (request.identity === 'char' || request.identity === 'MHF_Steve') {
// These are special-cased by Minotar.
Expand Down Expand Up @@ -174,6 +189,29 @@ export default class MojangRequestService {
return undefined;
}

private static async fetchTextureFromId(id: string): Promise<TextureResponse> {
const url = `https://textures.minecraft.net/texture/${id}`;
return this.fetchTextureFromUrl(url);
}

private static async fetchTextureFromUrl(textureUrl: string): Promise<TextureResponse> {
const textureResponse = await fetch(textureUrl, {
cf: {
cacheEverything: true,
cacheTtl: 86400,
},
headers: {
'User-Agent': 'Crafthead (+https://crafthead.net)',
},
});
if (!textureResponse.ok) {
throw new Error(`Unable to retrieve texture from Mojang, http status ${textureResponse.status}`);
}

//console.log('Successfully retrieved texture');
return { texture: textureResponse, model: 'default' };
}

async fetchProfile(request: CraftheadRequest, gatherer: PromiseGatherer): Promise<CacheComputeResult<MojangProfile | null>> {
const normalized = await this.normalizeRequest(request, gatherer);
if (!normalized.identity || uuidVersion(fromHex(normalized.identity)) === 3) {
Expand Down
24 changes: 24 additions & 0 deletions test/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,30 @@ describe('worker', () => {
expect(await response.headers.get('content-type')).toContain('image/png');
});

it('responds with image for avatar on texture ID', async () => {
const request = new IncomingRequest('http://crafthead.net/avatar/9d2e80355eed693e3f0485893ef04ff6a507f3aab33f2bedb48cef56e30f67d0');
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
expect(await response.headers.get('content-type')).toContain('image/png');
});

it('responds with a matching avatar image by UUID, username, and texture ID', async () => {
const request1 = new IncomingRequest('http://crafthead.net/avatar/ef6134805b6244e4a4467fbe85d65513');
const request2 = new IncomingRequest('http://crafthead.net/avatar/CherryJimbo');
const request3 = new IncomingRequest('http://crafthead.net/avatar/9d2e80355eed693e3f0485893ef04ff6a507f3aab33f2bedb48cef56e30f67d0');
const ctx = createExecutionContext();
const response1 = await worker.fetch(request1, env, ctx);
const response2 = await worker.fetch(request2, env, ctx);
const response3 = await worker.fetch(request3, env, ctx);
await waitOnExecutionContext(ctx);
const image1 = await response1.arrayBuffer();
const image2 = await response2.arrayBuffer();
const image3 = await response3.arrayBuffer();
expect(image1).toStrictEqual(image2);
expect(image2).toStrictEqual(image3);
});

type ProfileResponse = {
id: string;
name: string;
Expand Down
Loading