···
3
+
# Dynamic Profile Picture Updater
4
+
# Automatically updates your profile pictures across platforms based on time and weather
5
+
# Usage: ./auto_pfp.sh [options]
9
+
# Default configuration
10
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
11
+
CONFIG_FILE="${SCRIPT_DIR}/config.json"
12
+
IMAGES_DIR="${SCRIPT_DIR}/rendered_timelines"
13
+
LOG_FILE="${SCRIPT_DIR}/auto_pfp.log"
14
+
SESSION_FILE="${SCRIPT_DIR}/.bluesky_session"
15
+
DEFAULT_TIMELINE="sunny"
22
+
NC='\033[0m' # No Color
29
+
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
30
+
echo -e "${timestamp} - ${level} - ${message}" | tee -a "$LOG_FILE" >&2
33
+
log_info() { log "${BLUE}[INFO]${NC}" "$@"; }
34
+
log_success() { log "${GREEN}[SUCCESS]${NC}" "$@"; }
35
+
log_warning() { log "${YELLOW}[WARNING]${NC}" "$@"; }
36
+
log_error() { log "${RED}[ERROR]${NC}" "$@"; }
38
+
# Check dependencies
39
+
check_dependencies() {
40
+
local missing_deps=()
42
+
if ! command -v curl &> /dev/null; then
43
+
missing_deps+=("curl")
46
+
if ! command -v jq &> /dev/null; then
47
+
missing_deps+=("jq")
50
+
if ! command -v sha256sum &> /dev/null; then
51
+
missing_deps+=("sha256sum")
54
+
if [ ${#missing_deps[@]} -ne 0 ]; then
55
+
log_error "Missing required dependencies:"
56
+
for dep in "${missing_deps[@]}"; do
63
+
# Create default config file
64
+
create_default_config() {
65
+
cat > "$CONFIG_FILE" << 'EOF'
70
+
"handle": "your-handle.bsky.social",
71
+
"password": "your-app-password"
82
+
"timeline_mapping": {
87
+
"thunderstorm": "stormy",
94
+
"default_timeline": "sunny",
95
+
"images_dir": "./rendered_timelines"
99
+
log_info "Created default config file: $CONFIG_FILE"
100
+
log_warning "Please edit the config file with your platform credentials"
103
+
# Load configuration
105
+
if [ ! -f "$CONFIG_FILE" ]; then
106
+
log_warning "Config file not found, creating default..."
107
+
create_default_config
111
+
# Read platform settings
112
+
BLUESKY_ENABLED=$(jq -r '.platforms.bluesky.enabled' "$CONFIG_FILE")
113
+
BLUESKY_HANDLE=$(jq -r '.platforms.bluesky.handle' "$CONFIG_FILE")
114
+
BLUESKY_PASSWORD=$(jq -r '.platforms.bluesky.password' "$CONFIG_FILE")
115
+
SLACK_ENABLED=$(jq -r '.platforms.slack.enabled' "$CONFIG_FILE")
116
+
SLACK_USER_TOKEN=$(jq -r '.platforms.slack.user_token' "$CONFIG_FILE")
118
+
# Read weather settings
119
+
WEATHER_ENABLED=$(jq -r '.weather.enabled' "$CONFIG_FILE")
120
+
WEATHER_API_KEY=$(jq -r '.weather.api_key' "$CONFIG_FILE")
121
+
WEATHER_LOCATION=$(jq -r '.weather.location' "$CONFIG_FILE")
123
+
# Read general settings
124
+
DEFAULT_TIMELINE=$(jq -r '.settings.default_timeline' "$CONFIG_FILE")
125
+
IMAGES_DIR=$(jq -r '.settings.images_dir' "$CONFIG_FILE")
127
+
# Validate at least one platform is enabled and configured
128
+
local enabled_platforms=()
131
+
if [ "$BLUESKY_ENABLED" = "true" ]; then
132
+
if [ "$BLUESKY_HANDLE" = "your-handle.bsky.social" ] || [ "$BLUESKY_HANDLE" = "null" ] || [ -z "$BLUESKY_HANDLE" ]; then
133
+
log_warning "Bluesky enabled but handle not configured - will be skipped"
134
+
BLUESKY_ENABLED="false"
135
+
elif [ "$BLUESKY_PASSWORD" = "your-app-password" ] || [ "$BLUESKY_PASSWORD" = "null" ] || [ -z "$BLUESKY_PASSWORD" ]; then
136
+
log_warning "Bluesky enabled but password not configured - will be skipped"
137
+
BLUESKY_ENABLED="false"
139
+
enabled_platforms+=("Bluesky")
144
+
if [ "$SLACK_ENABLED" = "true" ]; then
145
+
if [ -z "$SLACK_USER_TOKEN" ] || [ "$SLACK_USER_TOKEN" = "null" ]; then
146
+
log_warning "Slack enabled but no user token provided - will be skipped"
147
+
SLACK_ENABLED="false"
149
+
enabled_platforms+=("Slack")
153
+
# Ensure at least one platform is enabled
154
+
if [ ${#enabled_platforms[@]} -eq 0 ]; then
155
+
log_error "No platforms are properly configured. Please check your config file."
159
+
# Convert relative paths to absolute
160
+
if [[ ! "$IMAGES_DIR" =~ ^/ ]]; then
161
+
IMAGES_DIR="${SCRIPT_DIR}/${IMAGES_DIR}"
164
+
log_info "Loaded configuration with enabled platforms: ${enabled_platforms[*]}"
167
+
# Authenticate with Bluesky
168
+
authenticate_bluesky() {
169
+
if [ "$BLUESKY_ENABLED" != "true" ]; then
173
+
log_info "Authenticating with Bluesky..."
175
+
local auth_response
176
+
auth_response=$(curl -s -X POST \
177
+
"https://bsky.social/xrpc/com.atproto.server.createSession" \
178
+
-H "Content-Type: application/json" \
179
+
-d "{\"identifier\":\"$BLUESKY_HANDLE\",\"password\":\"$BLUESKY_PASSWORD\"}")
181
+
if echo "$auth_response" | jq -e '.accessJwt' > /dev/null 2>&1; then
182
+
echo "$auth_response" > "$SESSION_FILE"
183
+
log_success "Successfully authenticated with Bluesky"
186
+
log_error "Bluesky authentication failed: $(echo "$auth_response" | jq -r '.message // "Unknown error"')"
191
+
# Get session token
192
+
get_session_token() {
193
+
if [ ! -f "$SESSION_FILE" ]; then
197
+
# Check if session is still valid (sessions typically last 24 hours)
198
+
local session_age=$(($(date +%s) - $(stat -c %Y "$SESSION_FILE" 2>/dev/null || echo 0)))
199
+
if [ $session_age -gt 86400 ]; then # 24 hours
200
+
log_info "Session expired, re-authenticating..."
201
+
rm -f "$SESSION_FILE"
205
+
jq -r '.accessJwt' "$SESSION_FILE" 2>/dev/null || return 1
208
+
# Calculate SHA256 hash of image file
209
+
calculate_image_hash() {
210
+
local image_path="$1"
211
+
if [ ! -f "$image_path" ]; then
214
+
sha256sum "$image_path" | cut -d' ' -f1
217
+
# Get blob reference from ATProto record
218
+
get_cached_blob() {
219
+
local weather_type="$1"
221
+
local image_hash="$3"
225
+
did=$(jq -r '.did' "$SESSION_FILE")
226
+
local rkey="${weather_type}_hour_${hour}"
229
+
if [ -z "$did" ] || [ "$did" = "null" ]; then
230
+
log_error "Could not get DID from session file"
234
+
log_info "Checking for cached blob: $weather_type hour $hour (DID: ${did:0:20}...)"
236
+
# Try to get existing record
237
+
local record_response
238
+
record_response=$(curl -s \
239
+
"https://bsky.social/xrpc/com.atproto.repo.getRecord?repo=$did&collection=pfp.updates.${weather_type}&rkey=$rkey" \
240
+
-H "Authorization: Bearer $token")
242
+
if echo "$record_response" | jq -e '.value' > /dev/null 2>&1; then
243
+
local stored_hash=$(echo "$record_response" | jq -r '.value.imageHash // empty')
244
+
local stored_blob=$(echo "$record_response" | jq -c '.value.blobRef // empty')
246
+
if [ "$stored_hash" = "$image_hash" ] && [ -n "$stored_blob" ] && [ "$stored_blob" != "empty" ]; then
247
+
log_success "Found cached blob with matching hash"
248
+
echo "$stored_blob"
251
+
log_info "Cached blob found but hash mismatch or missing blob reference"
255
+
log_info "No cached blob record found"
260
+
# Store blob reference in ATProto record
261
+
store_blob_reference() {
262
+
local weather_type="$1"
264
+
local image_hash="$3"
265
+
local blob_ref="$4"
269
+
did=$(jq -r '.did' "$SESSION_FILE")
270
+
local rkey="${weather_type}_hour_${hour}"
273
+
if [ -z "$did" ] || [ "$did" = "null" ]; then
274
+
log_error "Could not get DID from session file"
278
+
log_info "Storing blob reference for $weather_type hour $hour (DID: ${did:0:20}...)"
280
+
# Create record data
282
+
record_data=$(jq -n \
283
+
--arg type_field "pfp.updates.${weather_type}" \
284
+
--arg hash "$image_hash" \
285
+
--argjson blob "$blob_ref" \
286
+
--arg weather "$weather_type" \
287
+
--arg hour "$hour" \
288
+
--arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)" \
290
+
"$type": $type_field,
291
+
"timeline": $weather,
293
+
"imageHash": $hash,
295
+
"createdAt": $timestamp
298
+
log_info "Record data: $record_data"
300
+
# Create the request payload using direct JSON construction
301
+
local request_payload
302
+
request_payload=$(jq -n \
303
+
--arg repo "$did" \
304
+
--arg collection "pfp.updates.${weather_type}" \
305
+
--arg rkey "$rkey" \
306
+
--argjson record "$record_data" \
309
+
"collection": $collection,
314
+
log_info "Request payload preview: $(echo "$request_payload" | jq -c '.' | head -c 200)..."
316
+
# Validate the payload has required fields
317
+
if ! echo "$request_payload" | jq -e '.repo' > /dev/null 2>&1; then
318
+
log_error "Request payload missing 'repo' field"
319
+
log_error "DID value: '$did'"
320
+
log_error "Full payload: $request_payload"
324
+
# In dry run mode, don't actually store
325
+
if [ "${DRY_RUN:-false}" = "true" ]; then
326
+
log_info "DRY RUN MODE - Would store blob reference"
331
+
local store_response
332
+
store_response=$(curl -s -X POST \
333
+
"https://bsky.social/xrpc/com.atproto.repo.putRecord" \
334
+
-H "Authorization: Bearer $token" \
335
+
-H "Content-Type: application/json" \
336
+
-d "$request_payload")
338
+
if echo "$store_response" | jq -e '.uri' > /dev/null 2>&1; then
339
+
log_success "Successfully stored blob reference"
342
+
log_error "Failed to store blob reference: $(echo "$store_response" | jq -r '.message // "Unknown error"')"
343
+
log_error "Full response: $store_response"
348
+
# Upload image as blob
350
+
local image_path="$1"
353
+
if [ ! -f "$image_path" ]; then
354
+
log_error "Image file not found: $image_path"
358
+
# Check image file size (should be reasonable)
359
+
local file_size=$(stat -c%s "$image_path" 2>/dev/null || echo 0)
360
+
if [ "$file_size" -lt 1000 ]; then
361
+
log_error "Image file too small ($file_size bytes): $image_path"
365
+
if [ "$file_size" -gt 10000000 ]; then # 10MB limit
366
+
log_error "Image file too large ($file_size bytes): $image_path"
370
+
log_info "Uploading image: $(basename "$image_path") ($(numfmt --to=iec "$file_size"))"
372
+
local upload_response
373
+
upload_response=$(curl -s -X POST \
374
+
"https://bsky.social/xrpc/com.atproto.repo.uploadBlob" \
375
+
-H "Authorization: Bearer $token" \
376
+
-H "Content-Type: image/jpeg" \
377
+
--data-binary "@$image_path")
379
+
if echo "$upload_response" | jq -e '.blob' > /dev/null 2>&1; then
381
+
blob_result=$(echo "$upload_response" | jq -c '.blob')
382
+
log_success "Successfully uploaded image"
383
+
log_info "Blob data: $blob_result"
384
+
echo "$blob_result"
387
+
local error_type=$(echo "$upload_response" | jq -r '.error // "Unknown"')
388
+
local error_msg=$(echo "$upload_response" | jq -r '.message // "Unknown error"')
390
+
if [ "$error_type" = "ExpiredToken" ] || echo "$error_msg" | grep -qi "expired"; then
391
+
log_error "Token has expired - session needs refresh"
392
+
# Remove the expired session file so it will be regenerated
393
+
rm -f "$SESSION_FILE"
394
+
return 2 # Special return code for expired token
396
+
log_error "Failed to upload image: $error_msg"
397
+
log_error "Full response: $upload_response"
403
+
# Get or upload blob with caching
404
+
get_or_upload_blob() {
405
+
local image_path="$1"
406
+
local weather_type="$2"
410
+
if [ ! -f "$image_path" ]; then
411
+
log_error "Image file not found: $image_path"
415
+
# Calculate image hash
417
+
image_hash=$(calculate_image_hash "$image_path")
418
+
if [ -z "$image_hash" ]; then
419
+
log_error "Failed to calculate image hash"
423
+
log_info "Image hash: $image_hash"
425
+
# Try to get cached blob
427
+
if cached_blob=$(get_cached_blob "$weather_type" "$hour" "$image_hash" "$token"); then
428
+
log_success "Using cached blob reference"
429
+
echo "$cached_blob"
433
+
# No cache hit, upload the blob
434
+
log_info "No valid cache found, uploading new blob..."
436
+
new_blob=$(upload_blob "$image_path" "$token")
438
+
if [ -n "$new_blob" ]; then
439
+
# Store the blob reference for future use
440
+
if store_blob_reference "$weather_type" "$hour" "$image_hash" "$new_blob" "$token"; then
441
+
log_success "Blob uploaded and cached successfully"
443
+
log_warning "Blob uploaded but failed to cache reference"
448
+
log_error "Failed to upload blob"
453
+
# List all cached blobs
454
+
list_cached_blobs() {
458
+
did=$(jq -r '.did' "$SESSION_FILE")
460
+
log_info "Listing cached blob records..."
462
+
# Get list of available timelines to check each collection
464
+
if [ -d "$IMAGES_DIR" ]; then
465
+
for timeline_dir in "$IMAGES_DIR"/*; do
466
+
if [ -d "$timeline_dir" ]; then
467
+
timelines+=($(basename "$timeline_dir"))
472
+
local total_records=0
473
+
echo "Cached blob records:"
475
+
for timeline in "${timelines[@]}"; do
476
+
# List records in each timeline collection
477
+
local list_response
478
+
list_response=$(curl -s \
479
+
"https://bsky.social/xrpc/com.atproto.repo.listRecords?repo=$did&collection=pfp.updates.${timeline}" \
480
+
-H "Authorization: Bearer $token" 2>/dev/null)
482
+
if echo "$list_response" | jq -e '.records' > /dev/null 2>&1; then
483
+
local timeline_count=$(echo "$list_response" | jq '.records | length')
484
+
if [ "$timeline_count" -gt 0 ]; then
485
+
echo " $timeline timeline:"
486
+
echo "$list_response" | jq -r '.records[] | " hour \(.value.hour) - Hash: \(.value.imageHash[0:12])... (Created: \(.value.createdAt))"'
487
+
total_records=$((total_records + timeline_count))
492
+
echo "Total cached records: $total_records"
495
+
# Clean up old cached blobs (optional maintenance function)
496
+
cleanup_cached_blobs() {
498
+
local days_to_keep="${2:-30}" # Keep records for 30 days by default
501
+
did=$(jq -r '.did' "$SESSION_FILE")
503
+
log_info "Cleaning up cached blobs older than $days_to_keep days..."
505
+
# Get current timestamp minus retention period
507
+
cutoff_date=$(date -u -d "$days_to_keep days ago" +%Y-%m-%dT%H:%M:%S.%3NZ)
509
+
# Get list of available timelines to check each collection
511
+
if [ -d "$IMAGES_DIR" ]; then
512
+
for timeline_dir in "$IMAGES_DIR"/*; do
513
+
if [ -d "$timeline_dir" ]; then
514
+
timelines+=($(basename "$timeline_dir"))
519
+
local deleted_count=0
521
+
for timeline in "${timelines[@]}"; do
522
+
# List all records in this timeline collection
523
+
local list_response
524
+
list_response=$(curl -s \
525
+
"https://bsky.social/xrpc/com.atproto.repo.listRecords?repo=$did&collection=pfp.updates.${timeline}" \
526
+
-H "Authorization: Bearer $token" 2>/dev/null)
528
+
if echo "$list_response" | jq -e '.records' > /dev/null 2>&1; then
529
+
# Find records older than cutoff
531
+
old_records=$(echo "$list_response" | jq --arg cutoff "$cutoff_date" '.records[] | select(.value.createdAt < $cutoff)')
533
+
if [ -n "$old_records" ]; then
534
+
echo "$old_records" | jq -r '.uri' | while read -r record_uri; do
535
+
local rkey=$(echo "$record_uri" | sed 's/.*\///')
536
+
log_info "Deleting old record: $timeline/$rkey"
539
+
"https://bsky.social/xrpc/com.atproto.repo.deleteRecord" \
540
+
-H "Authorization: Bearer $token" \
541
+
-H "Content-Type: application/json" \
542
+
-d "{\"repo\":\"$did\",\"collection\":\"pfp.updates.${timeline}\",\"rkey\":\"$rkey\"}" > /dev/null
544
+
deleted_count=$((deleted_count + 1))
550
+
if [ "$deleted_count" -eq 0 ]; then
551
+
log_info "No old records found to clean up"
553
+
log_success "Deleted $deleted_count old records"
557
+
# Update profile picture
558
+
update_profile_picture() {
559
+
local blob_ref="$1"
563
+
# Validate blob reference
564
+
if [ -z "$blob_ref" ] || [ "$blob_ref" = "null" ]; then
565
+
log_error "Invalid blob reference provided"
569
+
# Validate blob reference format
570
+
if ! echo "$blob_ref" | jq -e '.ref' > /dev/null 2>&1; then
571
+
log_error "Blob reference missing required 'ref' field: $blob_ref"
575
+
# Get DID from session
576
+
did=$(jq -r '.did' "$SESSION_FILE")
578
+
log_info "Updating profile picture..."
579
+
log_info "Using blob: $blob_ref"
581
+
# Get current profile
582
+
local current_profile
583
+
current_profile=$(curl -s \
584
+
"https://bsky.social/xrpc/com.atproto.repo.getRecord?repo=$did&collection=app.bsky.actor.profile&rkey=self" \
585
+
-H "Authorization: Bearer $token")
587
+
log_info "Current profile response: $current_profile"
590
+
if echo "$current_profile" | jq -e '.value' > /dev/null 2>&1; then
591
+
# Update existing profile - PRESERVE ALL EXISTING FIELDS
592
+
profile_data=$(echo "$current_profile" | jq --argjson avatar "$blob_ref" '.value | .avatar = $avatar')
593
+
log_info "Updating existing profile (preserving existing fields)"
595
+
log_error "No existing profile found - cannot safely create new profile"
596
+
log_error "Please manually restore your profile in the Bluesky app first"
600
+
log_info "Profile data to send: $profile_data"
602
+
# Validate profile data before sending
603
+
if ! echo "$profile_data" | jq -e '.avatar' > /dev/null 2>&1; then
604
+
log_error "Generated profile data is invalid"
608
+
# Double-check we're preserving important fields
609
+
local display_name=$(echo "$profile_data" | jq -r '.displayName // empty')
610
+
local description=$(echo "$profile_data" | jq -r '.description // empty')
612
+
if [ -n "$display_name" ]; then
613
+
log_info "Preserving display name: $display_name"
616
+
if [ -n "$description" ]; then
617
+
log_info "Preserving description: $(echo "$description" | head -c 50)..."
620
+
# Create the request payload
621
+
local request_payload
622
+
request_payload=$(jq -n \
623
+
--arg repo "$did" \
624
+
--arg collection "app.bsky.actor.profile" \
625
+
--arg rkey "self" \
626
+
--argjson record "$profile_data" \
627
+
'{repo: $repo, collection: $collection, rkey: $rkey, record: $record}')
629
+
log_info "Request payload: $request_payload"
631
+
# In dry run mode, don't actually update
632
+
if [ "${DRY_RUN:-false}" = "true" ]; then
633
+
log_info "DRY RUN MODE - Would send profile update with avatar"
634
+
log_info "DRY RUN MODE - Profile fields would be preserved"
639
+
local update_response
640
+
update_response=$(curl -s -X POST \
641
+
"https://bsky.social/xrpc/com.atproto.repo.putRecord" \
642
+
-H "Authorization: Bearer $token" \
643
+
-H "Content-Type: application/json" \
644
+
-d "$request_payload")
646
+
log_info "Update response: $update_response"
648
+
if echo "$update_response" | jq -e '.uri' > /dev/null 2>&1; then
649
+
log_success "Successfully updated profile picture"
652
+
log_error "Failed to update profile picture: $(echo "$update_response" | jq -r '.message // "Unknown error"')"
653
+
log_error "Full error response: $update_response"
658
+
# Update Slack profile picture
659
+
update_slack_profile_picture() {
660
+
local image_path="$1"
662
+
if [ "$SLACK_ENABLED" != "true" ] || [ -z "$SLACK_USER_TOKEN" ] || [ "$SLACK_USER_TOKEN" = "null" ]; then
663
+
log_info "Slack integration disabled or not configured"
667
+
if [ ! -f "$image_path" ]; then
668
+
log_error "Image file not found for Slack: $image_path"
672
+
log_info "Updating Slack profile picture..."
674
+
# First, upload the image to Slack
675
+
local upload_response
676
+
upload_response=$(curl -s -X POST \
677
+
"https://slack.com/api/users.setPhoto" \
678
+
-H "Authorization: Bearer $SLACK_USER_TOKEN" \
679
+
-F "image=@$image_path")
681
+
if echo "$upload_response" | jq -e '.ok' > /dev/null 2>&1; then
682
+
local ok_status=$(echo "$upload_response" | jq -r '.ok')
683
+
if [ "$ok_status" = "true" ]; then
684
+
log_success "Successfully updated Slack profile picture"
687
+
local error_msg=$(echo "$upload_response" | jq -r '.error // "Unknown error"')
688
+
log_error "Failed to update Slack profile picture: $error_msg"
690
+
# Handle common errors
691
+
case "$error_msg" in
693
+
log_error "Invalid Slack token - please check your user token"
696
+
log_error "Authentication failed - token may be expired"
699
+
log_error "Token missing required scope - needs 'users.profile:write'"
702
+
log_error "Image file too large for Slack"
708
+
log_error "Invalid response from Slack API: $upload_response"
713
+
# Get weather-based timeline
714
+
get_weather_timeline() {
715
+
if [ "$WEATHER_ENABLED" != "true" ] || [ -z "$WEATHER_API_KEY" ] || [ "$WEATHER_API_KEY" = "null" ]; then
716
+
log_info "Weather integration disabled, using default timeline: $DEFAULT_TIMELINE"
717
+
echo "$DEFAULT_TIMELINE"
721
+
log_info "Fetching weather data..."
725
+
if [ "$WEATHER_LOCATION" = "auto" ]; then
726
+
# Auto-detect location from IP
728
+
ip_data=$(curl -s "http://ip-api.com/json/" --connect-timeout 10)
730
+
if echo "$ip_data" | jq -e '.lat' > /dev/null 2>&1; then
731
+
lat=$(echo "$ip_data" | jq -r '.lat')
732
+
lon=$(echo "$ip_data" | jq -r '.lon')
733
+
local city=$(echo "$ip_data" | jq -r '.city')
734
+
local country=$(echo "$ip_data" | jq -r '.country')
735
+
log_info "Auto-detected location: $city, $country"
737
+
log_warning "Could not auto-detect location, using default timeline"
738
+
echo "$DEFAULT_TIMELINE"
742
+
# Use provided location (assume it's "lat,lon" or city name)
743
+
if [[ "$WEATHER_LOCATION" =~ ^-?[0-9]+\.?[0-9]*,-?[0-9]+\.?[0-9]*$ ]]; then
745
+
lat=$(echo "$WEATHER_LOCATION" | cut -d',' -f1)
746
+
lon=$(echo "$WEATHER_LOCATION" | cut -d',' -f2)
748
+
# It's a city name, geocode it
749
+
local geocode_response
750
+
geocode_response=$(curl -s "http://api.openweathermap.org/geo/1.0/direct?q=$WEATHER_LOCATION&limit=1&appid=$WEATHER_API_KEY")
752
+
if echo "$geocode_response" | jq -e '.[0].lat' > /dev/null 2>&1; then
753
+
lat=$(echo "$geocode_response" | jq -r '.[0].lat')
754
+
lon=$(echo "$geocode_response" | jq -r '.[0].lon')
755
+
log_info "Geocoded location: $WEATHER_LOCATION"
757
+
log_warning "Could not geocode location: $WEATHER_LOCATION"
758
+
echo "$DEFAULT_TIMELINE"
764
+
# Get current weather
765
+
local weather_response
766
+
weather_response=$(curl -s "http://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$WEATHER_API_KEY" --connect-timeout 10)
768
+
if echo "$weather_response" | jq -e '.weather[0].main' > /dev/null 2>&1; then
769
+
local weather_main=$(echo "$weather_response" | jq -r '.weather[0].main' | tr '[:upper:]' '[:lower:]')
770
+
local weather_desc=$(echo "$weather_response" | jq -r '.weather[0].description')
771
+
log_info "Current weather: $weather_desc"
773
+
# Map weather to timeline
775
+
timeline=$(jq -r ".weather.timeline_mapping.\"$weather_main\" // \"$DEFAULT_TIMELINE\"" "$CONFIG_FILE")
777
+
# Check if the mapped timeline exists
778
+
if [ ! -d "$IMAGES_DIR/$timeline" ]; then
779
+
log_warning "Timeline '$timeline' not found, falling back to default: $DEFAULT_TIMELINE"
780
+
echo "$DEFAULT_TIMELINE"
782
+
log_info "Weather mapped to timeline: $timeline"
786
+
log_warning "Could not fetch weather data, using default timeline"
787
+
echo "$DEFAULT_TIMELINE"
791
+
# Get current hour image path
792
+
get_hour_image_path() {
793
+
local timeline="$1"
794
+
local hour=$(date +%H)
795
+
# Remove leading zero to avoid octal interpretation, then pad with zero
796
+
local hour_decimal=$((10#$hour)) # Force decimal interpretation
797
+
local hour_padded=$(printf "%02d" "$hour_decimal")
798
+
local image_path="$IMAGES_DIR/$timeline/hour_${hour_padded}.jpg"
800
+
if [ -f "$image_path" ]; then
804
+
log_warning "Image not found: $image_path" >&2
806
+
# Try fallback to default timeline
807
+
if [ "$timeline" != "$DEFAULT_TIMELINE" ]; then
808
+
local fallback_path="$IMAGES_DIR/$DEFAULT_TIMELINE/hour_${hour_padded}.jpg"
809
+
if [ -f "$fallback_path" ]; then
810
+
log_info "Using fallback image: $fallback_path" >&2
811
+
echo "$fallback_path"
820
+
# List available timelines
822
+
if [ ! -d "$IMAGES_DIR" ]; then
823
+
log_error "Images directory not found: $IMAGES_DIR"
827
+
echo "Available timelines:"
828
+
for timeline_dir in "$IMAGES_DIR"/*; do
829
+
if [ -d "$timeline_dir" ]; then
830
+
local timeline_name=$(basename "$timeline_dir")
831
+
local image_count=$(find "$timeline_dir" -name "hour_*.jpg" | wc -l)
832
+
echo " - $timeline_name ($image_count images)"
837
+
# Test mode - show what would be used
840
+
timeline=$(get_weather_timeline)
843
+
image_path=$(get_hour_image_path "$timeline")
845
+
local hour=$(date +%H)
847
+
echo "=== Test Mode ==="
848
+
echo "Current time: $(date)"
849
+
echo "Current hour: $hour"
850
+
echo "Weather enabled: $WEATHER_ENABLED"
851
+
echo "Selected timeline: $timeline"
852
+
echo "Image path: $image_path"
854
+
if [ -f "$image_path" ]; then
855
+
echo "✓ Image exists"
856
+
echo "Image size: $(du -h "$image_path" | cut -f1)"
858
+
# Show hash info in test mode
859
+
local test_hash=$(calculate_image_hash "$image_path")
860
+
echo "Image hash: $test_hash"
862
+
echo "✗ Image not found"
864
+
# Show available alternatives
866
+
echo "Available timelines:"
871
+
# Show weather info if enabled
872
+
if [ "$WEATHER_ENABLED" = "true" ] && [ -n "$WEATHER_API_KEY" ] && [ "$WEATHER_API_KEY" != "null" ]; then
874
+
echo "Weather integration: enabled"
875
+
echo "Location setting: $WEATHER_LOCATION"
878
+
echo "Weather integration: disabled (using default timeline)"
881
+
# Show platform info
883
+
echo "Enabled platforms:"
884
+
if [ "$BLUESKY_ENABLED" = "true" ]; then
885
+
echo " ✓ Bluesky ($BLUESKY_HANDLE)"
887
+
echo " ✗ Bluesky (disabled or not configured)"
890
+
if [ "$SLACK_ENABLED" = "true" ]; then
893
+
echo " ✗ Slack (disabled or not configured)"
896
+
# Show caching info
898
+
echo "Blob caching: enabled for Bluesky uploads"
899
+
local hour_decimal=$((10#$hour))
900
+
local hour_padded=$(printf "%02d" "$hour_decimal")
901
+
echo "Cache key would be: ${timeline}_hour_${hour_padded}"
904
+
# Modified update_pfp function to use caching
906
+
log_info "Starting profile picture update..."
908
+
# Determine timeline based on weather
910
+
timeline=$(get_weather_timeline)
911
+
log_info "Using timeline: $timeline"
913
+
# Get appropriate image for current hour
915
+
image_path=$(get_hour_image_path "$timeline")
917
+
if [ -z "$image_path" ]; then
918
+
log_error "No suitable image found for current time"
922
+
log_info "Selected image: $image_path"
924
+
# Get current hour for caching
925
+
local current_hour=$(date +%H)
926
+
local hour_decimal=$((10#$current_hour))
927
+
local hour_padded=$(printf "%02d" "$hour_decimal")
929
+
# Dry run mode - don't actually upload
930
+
if [ "${DRY_RUN:-false}" = "true" ]; then
931
+
log_info "DRY RUN MODE - Would upload: $image_path"
932
+
log_info "Image size: $(stat -c%s "$image_path" 2>/dev/null | numfmt --to=iec)"
933
+
local test_hash=$(calculate_image_hash "$image_path")
934
+
log_info "Image hash: $test_hash"
935
+
log_info "Would cache as: $timeline hour $hour_padded"
936
+
if [ "$BLUESKY_ENABLED" = "true" ]; then
937
+
log_info "DRY RUN MODE - Would update Bluesky profile"
939
+
if [ "$SLACK_ENABLED" = "true" ]; then
940
+
log_info "DRY RUN MODE - Would update Slack profile"
942
+
log_info "DRY RUN MODE - No changes made"
946
+
local bluesky_success=false
947
+
local slack_success=false
949
+
# Update Bluesky with caching
950
+
if [ "$BLUESKY_ENABLED" = "true" ]; then
951
+
log_info "Updating Bluesky profile picture with caching..."
953
+
# Get session token
955
+
token=$(get_session_token)
957
+
if [ -z "$token" ] || [ "$token" = "null" ]; then
958
+
log_info "No valid session found, authenticating..."
959
+
if ! authenticate_bluesky; then
960
+
log_error "Failed to authenticate with Bluesky"
962
+
token=$(get_session_token)
966
+
if [ -n "$token" ] && [ "$token" != "null" ]; then
967
+
# Get or upload blob with caching
969
+
blob_ref=$(get_or_upload_blob "$image_path" "$timeline" "$hour_padded" "$token")
971
+
# If operation failed due to expired token, try re-authenticating once
972
+
if [ -z "$blob_ref" ]; then
973
+
log_info "Failed to get blob, trying to re-authenticate..."
974
+
rm -f "$SESSION_FILE" # Remove expired session
975
+
if authenticate_bluesky; then
976
+
token=$(get_session_token)
977
+
if [ -n "$token" ] && [ "$token" != "null" ]; then
978
+
blob_ref=$(get_or_upload_blob "$image_path" "$timeline" "$hour_padded" "$token")
983
+
if [ -n "$blob_ref" ]; then
984
+
# Update profile picture
985
+
if update_profile_picture "$blob_ref" "$token"; then
986
+
bluesky_success=true
990
+
log_error "Could not obtain valid Bluesky session token"
994
+
# Update Slack (independent of Bluesky success)
995
+
if [ "$SLACK_ENABLED" = "true" ]; then
996
+
if update_slack_profile_picture "$image_path"; then
1002
+
local updated_services=()
1003
+
local failed_services=()
1005
+
if [ "$BLUESKY_ENABLED" = "true" ]; then
1006
+
if [ "$bluesky_success" = "true" ]; then
1007
+
updated_services+=("Bluesky")
1009
+
failed_services+=("Bluesky")
1013
+
if [ "$SLACK_ENABLED" = "true" ]; then
1014
+
if [ "$slack_success" = "true" ]; then
1015
+
updated_services+=("Slack")
1017
+
failed_services+=("Slack")
1022
+
if [ ${#updated_services[@]} -gt 0 ]; then
1023
+
log_success "Successfully updated: ${updated_services[*]}"
1026
+
if [ ${#failed_services[@]} -gt 0 ]; then
1027
+
log_error "Failed to update: ${failed_services[*]}"
1030
+
# Return success if at least one service updated
1031
+
if [ ${#updated_services[@]} -gt 0 ]; then
1041
+
Dynamic Profile Picture Updater
1043
+
Automatically updates your profile pictures across multiple platforms based on time and weather.
1044
+
Uses ATProto record caching to avoid re-uploading identical images.
1046
+
Usage: $0 [options]
1049
+
-c, --config FILE Use custom config file (default: $CONFIG_FILE)
1050
+
-t, --test Test mode - show what would be used without updating
1051
+
-d, --dry-run Dry run - authenticate and prepare but don't actually update
1052
+
-l, --list List available timelines
1053
+
-f, --force TIMELINE Force use of specific timeline (ignore weather)
1054
+
--list-cache List all cached blob references
1055
+
--cleanup-cache [DAYS] Clean up cached blobs older than DAYS (default: 30)
1056
+
--clear-cache Delete all cached blob references (USE WITH CAUTION)
1057
+
-h, --help Show this help message
1060
+
Edit $CONFIG_FILE to set your platform credentials and preferences.
1062
+
Supported platforms:
1063
+
- Bluesky: Set handle and app password
1064
+
- Slack: Set user token (xoxp-...) with users.profile:write scope
1067
+
Images are uploaded once and cached in ATProto records at:
1068
+
pfp.updates.{timeline}.{timeline}_hour_{HH}
1070
+
Each record contains:
1071
+
- Image SHA256 hash for change detection
1072
+
- Blob reference for reuse
1073
+
- Metadata (timeline, hour, creation time)
1075
+
Examples of cache locations:
1076
+
- pfp.updates.sunny.sunny_hour_09
1077
+
- pfp.updates.rainy.rainy_hour_14
1078
+
- pfp.updates.cloudy.cloudy_hour_23
1081
+
$0 # Update profile pictures (uses cache when possible)
1082
+
$0 --test # Test what would be used
1083
+
$0 --list-cache # Show all cached blob references
1084
+
$0 --cleanup-cache 7 # Remove cached blobs older than 7 days
1085
+
$0 --force sunny # Force sunny timeline
1087
+
For automated updates, add to crontab:
1088
+
# Update 2 minutes after every hour
1089
+
2 * * * * $0 >/dev/null 2>&1
1093
+
# Parse command line arguments
1097
+
while [[ $# -gt 0 ]]; do
1118
+
FORCE_TIMELINE="$2"
1123
+
check_dependencies
1125
+
# Get session token
1127
+
token=$(get_session_token)
1128
+
if [ -z "$token" ] || [ "$token" = "null" ]; then
1129
+
if ! authenticate_bluesky; then
1130
+
log_error "Failed to authenticate with Bluesky"
1133
+
token=$(get_session_token)
1137
+
list_cached_blobs "$token"
1141
+
local cleanup_days="30"
1142
+
if [[ "$2" =~ ^[0-9]+$ ]]; then
1148
+
check_dependencies
1150
+
# Get session token
1152
+
token=$(get_session_token)
1153
+
if [ -z "$token" ] || [ "$token" = "null" ]; then
1154
+
if ! authenticate_bluesky; then
1155
+
log_error "Failed to authenticate with Bluesky"
1158
+
token=$(get_session_token)
1162
+
cleanup_cached_blobs "$token" "$cleanup_days"
1166
+
echo "WARNING: This will delete ALL cached blob references!"
1167
+
echo "You will need to re-upload all images on next use."
1168
+
read -p "Are you sure? (y/N): " -n 1 -r
1170
+
if [[ $REPLY =~ ^[Yy]$ ]]; then
1172
+
check_dependencies
1174
+
# Get session token
1176
+
token=$(get_session_token)
1177
+
if [ -z "$token" ] || [ "$token" = "null" ]; then
1178
+
if ! authenticate_bluesky; then
1179
+
log_error "Failed to authenticate with Bluesky"
1182
+
token=$(get_session_token)
1186
+
cleanup_cached_blobs "$token" "0" # Delete all
1187
+
log_success "Cache cleared"
1189
+
log_info "Cache clear cancelled"
1198
+
echo "Unknown option: $1"
1206
+
# Override weather function if timeline is forced
1207
+
if [ -n "${FORCE_TIMELINE:-}" ]; then
1208
+
get_weather_timeline() {
1209
+
echo "$FORCE_TIMELINE"
1216
+
check_dependencies
1219
+
if ! update_pfp; then
1224
+
# Run main function