-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMixamo Download All.user.js
More file actions
1240 lines (1134 loc) · 42.3 KB
/
Copy pathMixamo Download All.user.js
File metadata and controls
1240 lines (1134 loc) · 42.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Mixamo Download All With Resume
// @namespace local.codex.mixamo
// @version 0.1.11
// @description Download all Mixamo motions and motion packs with the currently selected uploaded character.
// @match https://www.mixamo.com/*
// @connect *
// @grant GM_download
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
const STATE_KEY = 'codex.mixamoDownloadAll.v1';
const SCRIPT_VERSION = '0.1.11';
const CONCURRENCY_KEY = 'codex.mixamoDownloadAll.concurrency';
const MAX_RETRIES = 4;
const MONITOR_DELAY_MS = 2500;
const PAGE_LIMIT = 96;
const CRAWL_PASSES = 10;
const DEFAULT_CONCURRENCY = 2;
const MIN_CONCURRENCY = 1;
const MAX_CONCURRENCY = 8;
const globalObject = typeof window !== 'undefined' ? window : globalThis;
let paused = false;
let running = false;
let pauseReason = '';
let ui = null;
let uiSearch = null;
let capturedCharacterId = '';
let downloadWindow = null;
function sanitizeName(value) {
const cleaned = String(value || '')
.replace(/[\\/:*?"<>|\u0000-\u001f]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return cleaned || 'Untitled';
}
function productName(product) {
return sanitizeName(product.description || product.name || product.label || product.id);
}
function motionName(product) {
return sanitizeName(product.name || product.label || product.description || product.id || product.product_id || product.motion_id);
}
function packName(product) {
return sanitizeName(product.name || product.label || product.description || product.id);
}
function createStandaloneEntry(product) {
const motionName = productName(product);
return {
key: `standalone/${product.id}`,
id: product.id,
productId: product.id,
productType: 'Motion',
packId: null,
packName: 'Standalone',
motionName,
downloadName: `Standalone__${motionName}`,
};
}
function createPackEntry(pack, motion) {
const packNameValue = packName(pack);
const motionNameValue = motionName(motion);
const productId = motion.product_id || motion.productId || motion.id || motion.motion_id;
const motionId = motion.motion_id || motion.motionId || motion.id || productId;
return {
key: `packs/${pack.id}/${productId}`,
id: motionId,
productId,
productType: 'Motion',
packId: pack.id,
packName: packNameValue,
motionName: motionNameValue,
downloadName: `${packNameValue}__${motionNameValue}`,
};
}
function resolveEntryDownloadName(entry, product) {
if (entry && entry.packId && product) {
return `${entry.packName}__${motionName(product)}`;
}
return entry.downloadName;
}
function filterPendingQueue(queue, state) {
const completed = state && state.completed ? state.completed : {};
return queue.filter((item) => !completed[item.key]);
}
function getRetryDelayMs(error, attempt) {
const status = error && (error.status || error.statusCode);
if (status === 429) {
return Math.min(30000 * Math.pow(2, attempt), 300000);
}
return Math.min(5000 * Math.pow(2, attempt), 60000);
}
function extractCharacterIdFromText(value) {
const text = String(value || '');
const queryMatch = text.match(/[?&]character_id=([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})/i);
if (queryMatch) {
return queryMatch[1];
}
const pathMatch = text.match(/\/characters\/([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})(?:[/?#]|$)/i);
if (pathMatch) {
return pathMatch[1];
}
const jsonMatch = text.match(/["']character[_-]?id["']\s*:\s*["']([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})["']/i);
if (jsonMatch) {
return jsonMatch[1];
}
return '';
}
function rememberCharacterId(characterId) {
if (!characterId || characterId === capturedCharacterId) {
return;
}
capturedCharacterId = characterId;
const state = loadState();
state.characterId = characterId;
saveState(state);
if (ui && ui.characterInput) {
ui.characterInput.value = characterId;
ui.characterInput.style.display = 'none';
}
setStatus(`Captured character ${characterId}`);
}
function captureCharacterIdFromValue(value) {
if (!value) {
return '';
}
if (typeof value === 'string') {
return extractCharacterIdFromText(value);
}
if (typeof URL !== 'undefined' && value instanceof URL) {
return extractCharacterIdFromText(value.href);
}
if (typeof Request !== 'undefined' && value instanceof Request) {
return extractCharacterIdFromText(value.url);
}
try {
return extractCharacterIdFromText(JSON.stringify(value));
} catch (error) {
return '';
}
}
function installCharacterIdCapture() {
if (globalObject.__mixamoDownloadAllCaptureInstalled) {
return;
}
globalObject.__mixamoDownloadAllCaptureInstalled = true;
const originalFetch = globalObject.fetch;
if (typeof originalFetch === 'function') {
globalObject.fetch = function patchedFetch(input, init) {
rememberCharacterId(captureCharacterIdFromValue(input));
if (init && init.body) {
rememberCharacterId(captureCharacterIdFromValue(init.body));
}
return originalFetch.apply(this, arguments);
};
}
const Xhr = globalObject.XMLHttpRequest;
if (Xhr && Xhr.prototype) {
const originalOpen = Xhr.prototype.open;
const originalSend = Xhr.prototype.send;
Xhr.prototype.open = function patchedOpen(method, url) {
this.__mixamoDownloadAllUrl = url;
rememberCharacterId(captureCharacterIdFromValue(url));
return originalOpen.apply(this, arguments);
};
Xhr.prototype.send = function patchedSend(body) {
rememberCharacterId(captureCharacterIdFromValue(this.__mixamoDownloadAllUrl));
rememberCharacterId(captureCharacterIdFromValue(body));
return originalSend.apply(this, arguments);
};
}
}
function getInitialUiModel() {
return {
characterInputVisible: false,
statusVisible: false,
buttonLabels: {
crawl: 'Crawl',
download: 'Download All',
pause: 'Pause',
reset: 'Reset',
importDone: 'Import Done',
},
};
}
function defaultState() {
return {
version: 1,
completed: {},
failed: {},
retryCounts: {},
queue: [],
characterId: '',
preferences: { format: 'fbx7', skin: 'false', fps: '30', reducekf: '0' },
concurrency: DEFAULT_CONCURRENCY,
updatedAt: null,
};
}
function getDownloadConcurrency(state) {
const value = Number(state && state.concurrency);
if (!Number.isFinite(value)) {
return DEFAULT_CONCURRENCY;
}
return Math.min(MAX_CONCURRENCY, Math.max(MIN_CONCURRENCY, Math.floor(value)));
}
function readSavedConcurrency(fallbackState) {
if (typeof GM_getValue === 'function') {
return getDownloadConcurrency({ concurrency: GM_getValue(CONCURRENCY_KEY, getDownloadConcurrency(fallbackState)) });
}
return getDownloadConcurrency(fallbackState);
}
function writeSavedConcurrency(value) {
const concurrency = getDownloadConcurrency({ concurrency: value });
if (typeof GM_setValue === 'function') {
GM_setValue(CONCURRENCY_KEY, concurrency);
}
return concurrency;
}
function applySavedConcurrency(state, savedConcurrency) {
const nextState = Object.assign(defaultState(), state || {});
nextState.concurrency = getDownloadConcurrency({ concurrency: savedConcurrency });
return nextState;
}
function loadState() {
try {
const state = Object.assign(defaultState(), JSON.parse(localStorage.getItem(STATE_KEY) || '{}'));
return applySavedConcurrency(state, readSavedConcurrency(state));
} catch (error) {
console.warn('[Mixamo Download All] Failed to read state; starting clean.', error);
const state = defaultState();
return applySavedConcurrency(state, readSavedConcurrency(state));
}
}
function saveState(state) {
state.updatedAt = new Date().toISOString();
localStorage.setItem(STATE_KEY, JSON.stringify(state));
refreshUiCounts(state);
}
function resetState() {
const state = loadState();
const nextState = defaultState();
nextState.characterId = state.characterId || '';
nextState.completed = Object.fromEntries(
Object.entries(state.completed || {}).filter((entry) => entry[1] && entry[1].source === 'imported-file'),
);
saveState(nextState);
}
function setStatus(message) {
if (ui && ui.status) {
ui.status.textContent = message;
ui.status.title = message;
ui.status.style.display = running || /character id|failed|error|pause|reset/i.test(message) ? 'inline-block' : 'none';
}
if (ui && ui.root) {
ui.root.title = message;
}
console.log('[Mixamo Download All]', message);
}
function formatDownloadButtonLabel(state) {
const queue = Array.isArray(state && state.queue) ? state.queue : [];
if (!queue.length) {
return 'Download All';
}
const completed = state && state.completed ? state.completed : {};
const remaining = filterPendingQueue(queue, state).length;
const completedCount = Object.keys(completed).length;
return `Download All (${remaining}/${queue.length})`;
}
function getFailureBucket(failure) {
const status = failure && failure.status;
if (status) {
return `HTTP ${status}`;
}
const reason = String((failure && failure.reason) || 'unknown error');
const statusMatch = reason.match(/\bHTTP\s+(\d{3})\b/i);
if (statusMatch) {
return `HTTP ${statusMatch[1]}`;
}
return reason.replace(/\s+/g, ' ').trim() || 'unknown error';
}
function formatFailureSummary(state) {
const failures = Object.values((state && state.failed) || {});
if (!failures.length) {
return '';
}
const buckets = new Map();
for (const failure of failures) {
const bucket = getFailureBucket(failure);
buckets.set(bucket, (buckets.get(bucket) || 0) + 1);
}
const parts = Array.from(buckets.entries())
.sort((left, right) => {
const leftIsHttp = /^HTTP \d{3}$/.test(left[0]);
const rightIsHttp = /^HTTP \d{3}$/.test(right[0]);
if (leftIsHttp !== rightIsHttp) {
return leftIsHttp ? -1 : 1;
}
return right[1] - left[1] || left[0].localeCompare(right[0]);
})
.map(([bucket, count]) => `${bucket} x${count}`);
const summary = `Failed ${failures.length}: ${parts.join('; ')}.`;
if (buckets.size === 1 && buckets.get('HTTP 404') === failures.length) {
return `${summary} Mixamo returned 404 for every failed item; those products or generated files are likely unavailable on the site.`;
}
return summary;
}
function refreshUiCounts(state) {
if (ui && ui.downloadButton) {
const nextState = state || loadState();
const failureSummary = formatFailureSummary(nextState);
ui.downloadButton.textContent = formatDownloadButtonLabel(nextState);
ui.downloadButton.title = failureSummary || `Download all Mixamo motions and packs using the current uploaded character. Script ${SCRIPT_VERSION}.`;
}
}
function registerMenuCommands() {
if (typeof GM_registerMenuCommand !== 'function') {
return;
}
GM_registerMenuCommand('Set Mixamo Download Concurrency', () => {
const state = loadState();
const current = readSavedConcurrency(state);
const input = globalObject.prompt(
`How many Mixamo files should download at the same time? (${MIN_CONCURRENCY}-${MAX_CONCURRENCY})`,
String(current),
);
if (input === null) {
return;
}
const next = writeSavedConcurrency(input);
state.concurrency = next;
saveState(state);
setStatus(running ? `Download concurrency set to ${next}; restart download to apply.` : `Download concurrency set to ${next}.`);
});
}
function authHeaders() {
const bearer = localStorage.access_token;
if (!bearer) {
throw new Error('Mixamo access token was not found. Log in to Mixamo first.');
}
return {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${bearer}`,
'X-Api-Key': 'mixamo2',
'X-Requested-With': 'XMLHttpRequest',
};
}
async function apiFetch(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const error = new Error(`Mixamo API returned HTTP ${response.status}`);
error.status = response.status;
throw error;
}
return response.json();
}
async function getAnimationList(page) {
const url = `https://www.mixamo.com/api/v1/products?page=${page}&limit=${PAGE_LIMIT}&order=&type=Motion%2CMotionPack&query=`;
return apiFetch(url, { method: 'GET', headers: authHeaders() });
}
async function getProduct(productId, characterId) {
const url = `https://www.mixamo.com/api/v1/products/${productId}?similar=0&character_id=${encodeURIComponent(characterId)}`;
return apiFetch(url, { method: 'GET', headers: authHeaders() });
}
async function exportAnimation(characterId, gmsHashArray, productNameForDownload, preferences) {
return apiFetch('https://www.mixamo.com/api/v1/animations/export', {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify({
character_id: characterId,
gms_hash: gmsHashArray,
preferences,
product_name: productNameForDownload,
type: 'Motion',
}),
});
}
async function monitorAnimation(characterId) {
const url = `https://www.mixamo.com/api/v1/characters/${encodeURIComponent(characterId)}/monitor`;
const msg = await apiFetch(url, { method: 'GET', headers: authHeaders() });
if (msg.status === 'completed') {
return msg.job_result;
}
if (msg.status === 'processing') {
await wait(MONITOR_DELAY_MS);
return monitorAnimation(characterId);
}
const error = new Error(`Mixamo export failed: ${msg.message || JSON.stringify(msg.job_result || msg)}`);
error.status = msg.status;
throw error;
}
function normalizeGmsHash(gmsHash) {
if (!gmsHash || !Array.isArray(gmsHash.params)) {
return gmsHash;
}
return Object.assign({}, gmsHash, {
params: gmsHash.params.map((param) => param[1]).join(','),
});
}
function createDownloadRequest(url, downloadName) {
const name = /\.fbx$/i.test(downloadName) ? downloadName : `${downloadName}.fbx`;
return { url, name };
}
function buildManifestExport(state) {
const queue = Array.isArray(state.queue) ? state.queue : [];
const completed = state.completed || {};
const failed = state.failed || {};
return {
exportedAt: new Date().toISOString(),
version: state.version || 1,
characterId: state.characterId || '',
preferences: state.preferences || {},
totalQueued: queue.length,
totalCompleted: Object.keys(completed).length,
totalFailed: Object.keys(failed).length,
queue,
completed,
failed,
missingFromCompleted: queue.filter((entry) => !completed[entry.key]),
};
}
function normalizeDownloadedFileName(fileName) {
return sanitizeName(String(fileName || '').replace(/\\/g, '/').split('/').pop().replace(/\.fbx$/i, '')).toLowerCase();
}
function normalizeDownloadedPath(fileName) {
return String(fileName || '')
.replace(/\\/g, '/')
.split('/')
.map((part) => sanitizeName(part.replace(/\.fbx$/i, '')).toLowerCase())
.filter(Boolean)
.join('/');
}
function organizedEntryPath(entry) {
return `${sanitizeName(entry.packName).toLowerCase()}/${sanitizeName(entry.motionName).toLowerCase()}`;
}
function matchDownloadedFilesToQueue(fileNames, queue) {
const entriesByDownloadName = new Map();
const entriesByOrganizedPath = new Map();
const entriesByMotionName = new Map();
const ambiguousMotionNames = new Set();
for (const entry of queue || []) {
entriesByDownloadName.set(normalizeDownloadedFileName(entry.downloadName), entry);
entriesByOrganizedPath.set(organizedEntryPath(entry), entry);
const motionKey = sanitizeName(entry.motionName).toLowerCase();
if (entriesByMotionName.has(motionKey)) {
ambiguousMotionNames.add(motionKey);
} else {
entriesByMotionName.set(motionKey, entry);
}
}
const matchedKeys = [];
const matchedEntries = [];
const unmatchedFiles = [];
const seenKeys = new Set();
for (const fileName of fileNames || []) {
if (!/\.fbx$/i.test(String(fileName))) {
unmatchedFiles.push(fileName);
continue;
}
const normalizedPath = normalizeDownloadedPath(fileName);
const normalizedName = normalizeDownloadedFileName(fileName);
const entry = entriesByDownloadName.get(normalizedName)
|| entriesByOrganizedPath.get(normalizedPath)
|| (!ambiguousMotionNames.has(normalizedName) ? entriesByMotionName.get(normalizedName) : null);
if (!entry) {
unmatchedFiles.push(fileName);
continue;
}
if (!seenKeys.has(entry.key)) {
seenKeys.add(entry.key);
matchedKeys.push(entry.key);
matchedEntries.push(entry);
}
}
return { matchedKeys, matchedEntries, unmatchedFiles };
}
function importDownloadedFilesIntoState(state, fileNames, queue) {
const nextState = Object.assign(defaultState(), state || {});
nextState.completed = Object.assign({}, nextState.completed || {});
nextState.failed = Object.assign({}, nextState.failed || {});
nextState.retryCounts = Object.assign({}, nextState.retryCounts || {});
const result = matchDownloadedFilesToQueue(fileNames, queue || nextState.queue || []);
const importedAt = new Date().toISOString();
for (const entry of result.matchedEntries) {
nextState.completed[entry.key] = {
at: importedAt,
source: 'imported-file',
downloadName: entry.downloadName,
packName: entry.packName,
motionName: entry.motionName,
};
delete nextState.failed[entry.key];
delete nextState.retryCounts[entry.key];
}
return {
state: nextState,
importedCount: result.matchedEntries.length,
unmatchedFiles: result.unmatchedFiles,
matchedKeys: result.matchedKeys,
};
}
function applyCrawledQueueToState(state, queue, characterId) {
const nextState = Object.assign(defaultState(), state || {});
nextState.queue = Array.isArray(queue) ? queue : [];
nextState.characterId = characterId || nextState.characterId || '';
nextState.completed = Object.assign({}, nextState.completed || {});
nextState.failed = {};
nextState.retryCounts = {};
return nextState;
}
function getQueueSortKey(entry) {
return [
sanitizeName(entry.packName || '').toLowerCase(),
sanitizeName(entry.motionName || '').toLowerCase(),
entry.key || '',
].join('\u0000');
}
function mergeQueuePasses(queuePasses) {
const entriesByKey = new Map();
for (const queue of queuePasses || []) {
for (const entry of queue || []) {
if (!entry || !entry.key || entriesByKey.has(entry.key)) {
continue;
}
entriesByKey.set(entry.key, entry);
}
}
return Array.from(entriesByKey.values()).sort((left, right) => getQueueSortKey(left).localeCompare(getQueueSortKey(right)));
}
function summarizeQueue(queue) {
const packIds = new Set();
let packAnimations = 0;
let standalone = 0;
for (const entry of queue || []) {
if (entry.packId) {
packAnimations += 1;
packIds.add(entry.packId);
} else {
standalone += 1;
}
}
return {
total: (queue || []).length,
standalone,
packAnimations,
packs: packIds.size,
};
}
function formatCrawlStatus(summary) {
return `Crawled ${summary.total} animation(s): ${summary.standalone} standalone, ${summary.packAnimations} from ${summary.packs} pack(s).`;
}
function selectDownloadedFiles() {
return new Promise((resolve) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.fbx,model/fbx,application/octet-stream';
input.multiple = true;
input.style.display = 'none';
input.addEventListener('change', () => {
resolve(Array.from(input.files || []).map((file) => file.name));
input.remove();
}, { once: true });
document.body.appendChild(input);
input.click();
});
}
async function importDoneFiles() {
if (running) {
setStatus('Pause before importing completed files.');
return;
}
const state = loadState();
const fileNames = await selectDownloadedFiles();
await finishImportDoneFiles(state, fileNames);
}
async function planImportDoneFlow(options) {
const state = options.state || defaultState();
const fileNames = await options.selectFiles();
let queue = Array.isArray(state.queue) ? state.queue : [];
if (queue.length === 0) {
throw new Error('Crawl first before importing downloaded files.');
}
return importDownloadedFilesIntoState(state, fileNames, queue);
}
async function finishImportDoneFiles(state, fileNames) {
if (!Array.isArray(state.queue) || state.queue.length === 0) {
setStatus('Crawl first before importing downloaded files.');
return;
}
const result = importDownloadedFilesIntoState(state, fileNames, state.queue);
saveState(result.state);
setStatus(`Imported ${result.importedCount} file(s); ${result.unmatchedFiles.length} unmatched.`);
}
async function crawlAllAnimations() {
if (running) {
setStatus('Pause before crawling.');
return;
}
running = true;
try {
const state = loadState();
const characterId = await resolveCharacterId();
setStatus('Crawling full animation list...');
const queue = await buildQueue(characterId);
const nextState = applyCrawledQueueToState(state, queue, characterId);
saveState(nextState);
setStatus(formatCrawlStatus(summarizeQueue(queue)));
} catch (error) {
setStatus(error.message || String(error));
} finally {
running = false;
}
}
function formatError(error) {
if (!error) {
return 'unknown error';
}
if (error.message) {
return error.message;
}
try {
return JSON.stringify(error);
} catch (jsonError) {
return String(error);
}
}
function formatRetryStatus(downloadName, error, delayMs) {
return `Retrying ${downloadName} in ${Math.round(delayMs / 1000)}s: ${formatError(error)}`;
}
function isRateLimitError(error) {
const status = error && (error.status || error.statusCode);
return status === 429 || /\bHTTP\s+429\b/i.test(formatError(error));
}
function applyRateLimitThrottle(state) {
const concurrency = writeSavedConcurrency(MIN_CONCURRENCY);
state.concurrency = concurrency;
return `Mixamo rate limited downloads (HTTP 429). Concurrency reduced to ${concurrency}; wait a few minutes, then click Download All again.`;
}
function downloadWithAnchor(request) {
const anchor = document.createElement('a');
anchor.href = request.url;
anchor.download = request.name;
anchor.rel = 'noopener';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
return wait(1000);
}
function downloadWithGmDownload(request) {
if (typeof GM_download !== 'function') {
return Promise.reject(new Error('GM_download is not available'));
}
return new Promise((resolve, reject) => {
GM_download({
url: request.url,
name: request.name,
saveAs: false,
onload: resolve,
onerror: (error) => reject(new Error(`GM_download failed: ${formatError(error)}`)),
ontimeout: () => reject(new Error('GM_download timed out')),
});
});
}
function downloadWithGmXhrBlob(request) {
if (typeof GM_xmlhttpRequest !== 'function') {
return Promise.reject(new Error('GM_xmlhttpRequest is not available'));
}
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: request.url,
responseType: 'blob',
onload: (response) => {
if (response.status < 200 || response.status >= 300) {
reject(new Error(`GM_xmlhttpRequest download returned HTTP ${response.status}`));
return;
}
const blobUrl = URL.createObjectURL(response.response);
downloadWithAnchor({ url: blobUrl, name: request.name })
.then(resolve, reject)
.finally(() => URL.revokeObjectURL(blobUrl));
},
onerror: (error) => reject(new Error(`GM_xmlhttpRequest failed: ${formatError(error)}`)),
ontimeout: () => reject(new Error('GM_xmlhttpRequest timed out')),
});
});
}
function downloadWithWindow(request) {
if (downloadWindow && !downloadWindow.closed) {
downloadWindow.location.href = request.url;
return wait(1500);
}
return Promise.reject(new Error('Download window is not available'));
}
async function triggerDownload(url, downloadName) {
const request = createDownloadRequest(url, downloadName);
const errors = [];
for (const strategy of [downloadWithGmDownload, downloadWithGmXhrBlob, downloadWithWindow]) {
try {
await strategy(request);
return;
} catch (error) {
errors.push(formatError(error));
console.warn('[Mixamo Download All] Download strategy failed:', errors[errors.length - 1]);
}
}
throw new Error(`All download strategies failed: ${errors.join(' | ')}`);
}
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isPackProduct(product) {
const typeText = [
product.type,
product.product_type,
product.productType,
product.category,
product.subtype,
].filter(Boolean).join(' ');
const nameText = [
product.name,
product.label,
].filter(Boolean).join(' ');
return /motion\s*pack|motionpack|\bpack\b/i.test(typeText)
|| /\bpack\b/i.test(nameText)
|| Boolean(product.num_animations || product.animation_count || product.animationCount || product.motion_count || product.motionCount)
|| (Array.isArray(product.motions) && product.motions.length > 0);
}
function isMotionProduct(product) {
const type = String(product.type || product.product_type || product.productType || '');
return type === 'Motion' || (!isPackProduct(product) && product.id);
}
function collectPackMotions(value, packId, seen) {
if (!value || typeof value !== 'object') {
return [];
}
if (Array.isArray(value)) {
return value.flatMap((item) => collectPackMotions(item, packId, seen));
}
const found = [];
if (value.id && value.id !== packId && isMotionProduct(value) && !seen.has(value.id)) {
seen.add(value.id);
found.push(value);
}
for (const key of Object.keys(value)) {
if (['similar', 'character', 'characters'].includes(key)) {
continue;
}
found.push(...collectPackMotions(value[key], packId, seen));
}
return found;
}
async function expandPack(product, characterId) {
if (Array.isArray(product.motions) && product.motions.length > 0) {
return product.motions.map((motion) => createPackEntry(product, motion));
}
const details = await getProduct(product.id, characterId);
const motions = collectPackMotions(details, product.id, new Set());
return motions.map((motion) => createPackEntry(product, motion));
}
async function buildQueuePass(characterId, pass, totalPasses) {
const queue = [];
let page = 1;
let totalPages = 1;
do {
setStatus(`Crawl pass ${pass}/${totalPasses}: fetching product page ${page}/${totalPages}`);
const json = await getAnimationList(page);
totalPages = Number(json.pagination && json.pagination.num_pages) || totalPages;
const products = Array.isArray(json.results) ? json.results : [];
for (const product of products) {
if (isPackProduct(product)) {
queue.push(...await expandPack(product, characterId));
} else if (isMotionProduct(product)) {
queue.push(createStandaloneEntry(product));
}
}
page += 1;
} while (page <= totalPages);
return queue;
}
async function buildQueue(characterId) {
const queuePasses = [];
for (let pass = 1; pass <= CRAWL_PASSES; pass += 1) {
const queue = await buildQueuePass(characterId, pass, CRAWL_PASSES);
queuePasses.push(queue);
const uniqueCount = mergeQueuePasses(queuePasses).length;
setStatus(`Crawl pass ${pass}/${CRAWL_PASSES} found ${queue.length}; unique ${uniqueCount}.`);
}
return mergeQueuePasses(queuePasses);
}
function getSavedCharacterId() {
const manual = ui && ui.characterInput ? ui.characterInput.value.trim() : '';
if (manual) {
return manual;
}
if (capturedCharacterId) {
return capturedCharacterId;
}
return loadState().characterId || '';
}
function findUuidNearCharacter(text) {
const uuidPattern = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ig;
const matches = String(text || '').match(uuidPattern) || [];
return matches[0] || '';
}
function detectCharacterIdFromStorage() {
for (const storage of [localStorage, sessionStorage]) {
for (let index = 0; index < storage.length; index += 1) {
const key = storage.key(index);
if (!/character|mixamo|redux|state|user/i.test(key || '')) {
continue;
}
const value = storage.getItem(key);
if (/character/i.test(value || '')) {
const uuid = findUuidNearCharacter(value);
if (uuid) {
return uuid;
}
}
}
}
return '';
}
async function resolveCharacterId() {
const saved = getSavedCharacterId();
if (saved) {
return saved;
}
const detected = detectCharacterIdFromStorage();
if (detected) {
return detected;
}
throw new Error('Could not detect the current character ID. Refresh Mixamo once, then select your uploaded character or open the native Download dialog so this userscript can capture Mixamo\'s own character_id request.');
}
function showManualCharacterInput(message) {
if (ui && ui.characterInput) {
ui.characterInput.style.display = 'inline-block';
ui.characterInput.focus();
}
setStatus(message);
}
async function downloadEntry(entry, characterId, state) {
const product = await getProduct(entry.productId, characterId);
const gmsHash = product && product.details && product.details.gms_hash;
if (!gmsHash) {
throw new Error(`Product ${entry.productId} did not include a gms_hash.`);
}
const downloadName = resolveEntryDownloadName(entry, product);
await exportAnimation(characterId, [normalizeGmsHash(gmsHash)], downloadName, state.preferences);
const url = await monitorAnimation(characterId);
await triggerDownload(url, downloadName);
return downloadName;
}
async function runWithRetries(entry, characterId, state, options) {
const runDownloadEntry = options && options.downloadEntry ? options.downloadEntry : downloadEntry;
const savedAttempts = state.retryCounts[entry.key] || 0;
const previousAttempts = savedAttempts >= MAX_RETRIES ? 0 : savedAttempts;
for (let attempt = previousAttempts; attempt < MAX_RETRIES; attempt += 1) {
if (paused) {
throw new Error('Paused');
}
try {
const downloadName = await runDownloadEntry(entry, characterId, state);
delete state.failed[entry.key];
delete state.retryCounts[entry.key];
state.completed[entry.key] = {
at: new Date().toISOString(),
downloadName,
packName: entry.packName,
motionName: entry.motionName,
};
saveState(state);
return;
} catch (error) {
state.retryCounts[entry.key] = attempt + 1;
state.failed[entry.key] = {
at: new Date().toISOString(),
attempts: attempt + 1,
reason: error.message || String(error),
status: error.status || null,
};
saveState(state);
if (isRateLimitError(error)) {
const message = applyRateLimitThrottle(state);
saveState(state);
if (options && typeof options.onRateLimit === 'function') {
options.onRateLimit(message);
}
const rateLimitError = new Error(message);
rateLimitError.status = 429;
throw rateLimitError;
}
if (attempt + 1 >= MAX_RETRIES) {
throw error;
}
const delay = getRetryDelayMs(error, attempt);
setStatus(formatRetryStatus(entry.downloadName, error, delay));
await wait(delay);
}
}
}
async function runConcurrentQueue(options) {
const entries = Array.isArray(options.entries) ? options.entries : [];
const concurrency = getDownloadConcurrency({ concurrency: options.concurrency });
let nextIndex = 0;
let finished = 0;
let started = 0;
async function worker() {