Skip to content

Instantly share code, notes, and snippets.

@n8henrie
Last active December 3, 2021 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8henrie/f888de70778f3e545b430f885d6f4181 to your computer and use it in GitHub Desktop.
Save n8henrie/f888de70778f3e545b430f885d6f4181 to your computer and use it in GitHub Desktop.
Apple JXA script to create and populate an album with a random sample of favorite photos
#!/usr/bin/osascript -l JavaScript
// Apple JXA script to create and populate an album with a random sample of favorite photos
// Author: @n8henrie
// Rename from .applescript.js to .applescript (.js for GitHub syntax highlighting)
// https://stackoverflow.com/a/11935263/1588795
function getRandomSubarray(arr, size) {
var shuffled = arr.slice(0), i = arr.length, temp, index;
while (i--) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(0, size);
}
function main() {
const Photos = new Application("Photos")
Photos.includeStandardAdditions = true
const millisInYear = (1000 * 60 * 60 * 24 * 365)
const today = new Date()
// Oversample starting with
const startDate = new Date(today - millisInYear * 1.5)
const albumLength = 100
// Ratio that should be since startDate
const newItemRatio = 0.5
const newLength = Math.floor(albumLength * newItemRatio)
var atvAlbum = Photos.albums().find(album => album.name() == "Apple TV Screensaver")
if (atvAlbum !== undefined) {
Photos.delete(atvAlbum)
}
atvAlbum = Photos.make({new: "album", named: "Apple TV Screensaver"})
var favorites = Photos.favoritesAlbum().mediaItems().filter(item => {
return (
!/.mov$/i.test(item.filename()) &&
!/.avi$/i.test(item.filename())
)
})
var newFavs = favorites.filter(item => item.date() >= startDate)
var oldFavs = favorites.filter(item => item.date() < startDate)
var newSample = getRandomSubarray(newFavs, newLength)
var oldSample = getRandomSubarray(oldFavs, albumLength - newSample.length)
Photos.add(newSample, {to: atvAlbum})
Photos.add(oldSample, {to: atvAlbum})
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment