Skip to content

Instantly share code, notes, and snippets.

@davidmz
Created November 25, 2019 14:00
Show Gist options
  • Save davidmz/3b1942a314aee58024716d722166dc9a to your computer and use it in GitHub Desktop.
Save davidmz/3b1942a314aee58024716d722166dc9a to your computer and use it in GitHub Desktop.
[500px sorder] Snipper for sorting 500px private gallery in photo id order #500px
(async () => {
const galleryId = (() => {
const m = /^\/g\/(\w+)$/.exec(location.pathname);
if (!m) {
throw new Error("Invalid location (not a private gallery)");
}
return m[1];
})();
const userId = window.currentUser.id;
const csrfToken = window.PxApp.csrf_token;
const itemsURL = `https://api.500px.com/v1/users/${userId}/galleries/${galleryId}/items`;
async function loadPage(page = 1) {
const rpp = 50;
const itemsURL = `${itemsURL}?rpp=${rpp}&page=${page}`;
const res = await fetch(itemsURL).then(r => r.json());
if (res.error) {
throw new Error(`Invalid response: ${res.error}`);
}
const { photos, current_page, total_pages } = res;
if (current_page < total_pages) {
const nextPhotos = await loadPage(current_page + 1);
return [...photos, ...nextPhotos];
}
return photos;
}
async function moveToBegin(photoId) {
const res = await fetch(itemsURL, {
method: "PUT",
body: JSON.stringify({
add: {
after: { id: null },
photos: [photoId]
}
}),
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken
},
credentials: "include"
}).then(r => r.json());
if (res.error) {
throw new Error(`Invalid response: ${res.error}`);
}
}
const photosIds = (await loadPage()).map(photo => photo.id);
photosIds.sort();
photosIds.reverse();
for (let i = 0; i < photosIds.length; i++) {
console.log(`⌛ ${i + 1}/${photosIds.length}...`);
await moveToBegin(photosIds[i]);
}
console.log("✔ Done");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment