-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb.py
More file actions
executable file
·3269 lines (2693 loc) · 115 KB
/
Copy pathweb.py
File metadata and controls
executable file
·3269 lines (2693 loc) · 115 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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
CigarBox
~~~~~~
A smokin' fast personal photostream
:copyright: (c) 2015 by Nathan Hubbard @n8foo.
:license: Apache, see LICENSE for more details.
"""
import sys
import re
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, send_from_directory, jsonify, make_response
from flask_security import Security, PeeweeUserDatastore, UserMixin, RoleMixin, \
login_required, roles_required, current_user
from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix
import math
import secrets
import datetime
import hashlib
from app import app
from util import *
import util
from db import *
from security import get_visible_privacy_levels, can_view_photo, can_edit_photo, \
can_manage_tags, can_manage_photosets
from peewee import IntegrityError
import process
import aws
import os
# Configure Flask to work behind nginx proxy
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1)
# Setup logging (shared file with API)
logger = setup_custom_logger('cigarbox', service_name='web')
# Configure Flask's built-in logger to use our custom logger
app.logger.handlers = logger.handlers
app.logger.setLevel(logger.level)
# Add anti-AI scraping headers to all responses
@app.after_request
def add_security_headers(response):
"""Add headers to prevent AI scraping and training on content"""
response.headers['X-Robots-Tag'] = 'noai, noimageai'
response.headers['TDM-Reservation'] = '1'
return response
# Setup Flask-Security-Too
user_datastore = PeeweeUserDatastore(db, User, Role, UserRoles)
security = Security(app, user_datastore)
# Register user loader for Flask-Login (Flask-Security uses this)
@security.login_manager.user_loader
def load_user(user_id):
"""Load user by ID from database"""
try:
return User.get(User.id == int(user_id))
except User.DoesNotExist:
return None
# Flexible access control decorator
def require_access(auth=None, pow=None):
"""
Flexible route protection decorator.
Args:
auth: True=require login, False=skip auth check, None=check REQUIRE_AUTH_FOR_PHOTOS config
pow: True=require PoW, False=skip PoW check, None=check POW_ENABLED config
Logic:
1. If user is logged in → always allow (bypass PoW)
2. If auth required and not logged in → redirect to login
3. If PoW required and no valid token → return 403 challenge page
4. Otherwise → allow access
Server-side enforcement: Returns challenge page, never exposes protected content without valid token.
"""
from functools import wraps
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# Always allow authenticated users (skip all checks)
if current_user.is_authenticated:
return f(*args, **kwargs)
# Determine if auth is required (explicit param or config)
auth_required = auth if auth is not None else app.config.get('REQUIRE_AUTH_FOR_PHOTOS', False)
# If auth required, redirect to login
if auth_required:
return security.login_manager.unauthorized()
# Determine if PoW is required (explicit param or config)
pow_required = pow if pow is not None else app.config.get('POW_ENABLED', False)
# If PoW not required, allow access
if not pow_required:
return f(*args, **kwargs)
# PoW is required - validate token
pow_token = request.cookies.get('pow_token')
if pow_token:
try:
token = PowToken.get(PowToken.token == pow_token)
# Validate token hasn't expired (time-based)
if token.expires_at <= datetime.datetime.now():
raise PowToken.DoesNotExist()
# Validate IP binding (if enabled)
if app.config.get('POW_BIND_TO_IP', True):
# Check if either IP is a privacy proxy (iCloud Private Relay, etc)
is_privacy_proxy = False
if app.config.get('POW_ALLOW_PRIVACY_PROXIES', True):
proxy_ranges = app.config.get('POW_PRIVACY_PROXY_RANGES', [])
for prefix in proxy_ranges:
if token.ip_address.startswith(prefix) or request.remote_addr.startswith(prefix):
is_privacy_proxy = True
break
# Only enforce IP binding for non-privacy-proxy IPs
if not is_privacy_proxy and token.ip_address != request.remote_addr:
logger.warning(f'PoW token IP mismatch: expected={token.ip_address} got={request.remote_addr}')
raise PowToken.DoesNotExist()
# Validate request count limit
max_requests = app.config.get('POW_TOKEN_MAX_REQUESTS', 50)
if token.request_count >= max_requests:
logger.info(f'PoW token request limit reached: {token.request_count}/{max_requests}')
raise PowToken.DoesNotExist()
# Validate time-based expiry (minutes since creation)
expiry_minutes = app.config.get('POW_TOKEN_EXPIRY_MINUTES', 15)
age = datetime.datetime.now() - token.created_at
if age.total_seconds() > (expiry_minutes * 60):
logger.info(f'PoW token time limit exceeded: {age.total_seconds()/60:.1f} min > {expiry_minutes} min')
raise PowToken.DoesNotExist()
# Token is valid - increment usage counter
token.request_count += 1
token.last_request_at = datetime.datetime.now()
token.save()
# Allow access to protected content
return f(*args, **kwargs)
except PowToken.DoesNotExist:
# Token invalid, expired, or doesn't exist - fall through to challenge
pass
# No valid token - return challenge page (server-side enforcement)
# Store the requested URL so we can redirect back after solving
return_url = get_return_url()
session['pow_return_url'] = return_url
return render_template('pow_challenge.html', return_url=return_url), 403
return decorated_function
return decorator
# Backwards compatibility alias
def auth_required_if_configured(f):
"""Backwards compatibility wrapper - uses require_access with config defaults"""
return require_access(auth=None, pow=None)(f)
# Ensure database is connected for each request
@app.before_request
def before_request():
"""Connect to database before each request"""
if db.is_closed():
db.connect()
@app.teardown_request
def teardown_request(exception):
"""Close database after each request"""
if not db.is_closed():
db.close()
# POW protection for login page (brute-force prevention)
@app.before_request
def protect_login_with_pow():
"""Require POW for login page to prevent brute-force attacks"""
# Only check login routes
if request.path != '/login':
return None
# Skip if POW is disabled
if not app.config.get('POW_ENABLED', False):
return None
# Authenticated users don't need POW
if current_user.is_authenticated:
return None
# Check for valid POW token
pow_token = request.cookies.get('pow_token')
if pow_token:
try:
token = PowToken.get(PowToken.token == pow_token)
# Validate IP binding
if app.config.get('POW_BIND_TO_IP', True):
# Check if either IP is a privacy proxy (iCloud Private Relay, etc)
is_privacy_proxy = False
if app.config.get('POW_ALLOW_PRIVACY_PROXIES', True):
proxy_ranges = app.config.get('POW_PRIVACY_PROXY_RANGES', [])
for prefix in proxy_ranges:
if token.ip_address.startswith(prefix) or request.remote_addr.startswith(prefix):
is_privacy_proxy = True
break
# Only enforce IP binding for non-privacy-proxy IPs
if not is_privacy_proxy and token.ip_address != request.remote_addr:
raise PowToken.DoesNotExist()
# Validate time-based expiry
expiry_minutes = app.config.get('POW_TOKEN_EXPIRY_MINUTES', 15)
age = datetime.datetime.now() - token.created_at
if age.total_seconds() > (expiry_minutes * 60):
raise PowToken.DoesNotExist()
# Token is valid - allow login page access
return None
except PowToken.DoesNotExist:
pass # Fall through to require POW
# No valid token - redirect to POW challenge
return_url = get_return_url()
return render_template('pow_challenge.html',
return_url=return_url,
SITEURL=get_base_url()), 403
# Utility Functions
def get_base_url():
"""Get the base URL dynamically from request"""
return request.url_root.rstrip('/')
def get_return_url():
"""Get current URL for return/next parameters (includes subpath prefix)
IMPORTANT: Always use this for redirect URLs to avoid losing subpath prefix!
Example: In subpath deployment (/pictures):
- request.path = '/photostream' ❌ WRONG
- get_return_url() = '/pictures/photostream' ✓ CORRECT
"""
url = request.script_root + request.full_path
# Strip trailing ? if there are no query parameters
if url.endswith('?'):
url = url[:-1]
return url
@app.context_processor
def inject_siteurl():
"""Inject SITEURL into all templates"""
return dict(SITEURL=get_base_url())
@app.context_processor
def inject_return_url_helper():
"""Inject get_return_url helper into templates"""
return dict(get_return_url=get_return_url)
@app.context_processor
def inject_signed_url_helper():
"""Inject signed_s3_url helper for generating private S3 URLs"""
def signed_s3_url(photo_uri, size='_b', expiry=None):
"""
Generate signed S3 URL for private objects
Args:
photo_uri: Photo URI (sha1 path without extension)
size: Size suffix (_t, _m, _n, _c, _b)
expiry: URL expiry in seconds (default: read from config S3_SIGNED_URL_EXPIRY)
Returns:
Signed S3 URL string
"""
if expiry is None:
expiry = app.config.get('S3_SIGNED_URL_EXPIRY', 3600)
s3_key = f'{photo_uri}{size}.jpg'
return aws.getPrivateURL(app.config, s3_key, expiry)
return dict(signed_s3_url=signed_s3_url)
@app.context_processor
def inject_gallery_config():
"""Inject gallery configuration into all templates"""
return dict(gallery_thumbnail_size=app.config.get('GALLERY_THUMBNAIL_SIZE', 'n'))
@app.template_filter('format_datetime')
def format_datetime_filter(value, format='%Y-%m-%d %H:%M'):
"""Format a datetime or string as a formatted date string
Handles both datetime objects and string representations of dates.
Returns 'N/A' if value is None or invalid.
"""
if not value:
return 'N/A'
# If it's already a datetime object, format it
if isinstance(value, datetime.datetime):
return value.strftime(format)
# If it's a string, try to parse it first
if isinstance(value, str):
try:
# Try common datetime formats
for fmt in ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d']:
try:
dt = datetime.datetime.strptime(value, fmt)
return dt.strftime(format)
except ValueError:
continue
# If none worked, return the string as-is
return value
except:
return 'N/A'
return 'N/A'
def find(lst, key, value):
for i, dic in enumerate(lst):
if dic[key] == value:
return i
return -1
def get_pagination_data(query, page, per_page):
"""Calculate pagination metadata for a query
Args:
query: Peewee SelectQuery object
page: Current page number (1-indexed)
per_page: Items per page
Returns:
Dictionary with pagination metadata
"""
total_items = query.count()
total_pages = math.ceil(total_items / per_page)
has_prev = page > 1
has_next = page < total_pages
return {
'page': page,
'per_page': per_page,
'total_items': total_items,
'total_pages': total_pages,
'has_prev': has_prev,
'has_next': has_next,
'prev_page': page - 1 if has_prev else None,
'next_page': page + 1 if has_next else None
}
# URL Routing
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(error):
return render_template('500.html'), 500
@app.route('/robots.txt')
def robots_txt():
"""Serve robots.txt to block AI scrapers"""
return send_from_directory('static', 'robots.txt', mimetype='text/plain')
@app.route('/', defaults={'page': 1})
@app.route('/photostream', defaults={'page': 1})
@app.route('/photostream/page/<int:page>')
@require_access(pow=True)
def photostream(page):
"""the list of the most recently added pictures"""
baseurl = '%s/photostream' % (get_base_url())
# Filter by privacy level based on current user (treat NULL as public)
visible_levels = get_visible_privacy_levels(current_user)
photos_query = Photo.select().where(
(Photo.privacy.is_null()) | (Photo.privacy.in_(visible_levels))
).order_by(Photo.id.desc())
# Get pagination metadata
pagination = get_pagination_data(photos_query, page, app.config['PER_PAGE'])
# Get paginated results
photos = photos_query.paginate(page, app.config['PER_PAGE'])
for photo in photos:
(sha1Path,filename) = getSha1Path(photo.sha1)
photo.uri = sha1Path + '/' + filename
# Include page number in context for breadcrumb navigation
in_context = f'photostream:page:{page}' if page > 1 else 'photostream'
return render_template('photostream.html', photos=photos, pagination=pagination, baseurl=baseurl, in_context=in_context)
@app.route('/photos/<int:photo_id>')
def show_photo(photo_id):
"""a single photo"""
# Check POW manually for split-brain mode support
has_pow = False
if current_user.is_authenticated:
has_pow = True
elif app.config.get('POW_ENABLED', False):
# Validate POW token manually (same logic as require_access decorator)
pow_token = request.cookies.get('pow_token')
if pow_token:
try:
token = PowToken.get(PowToken.token == pow_token)
# Validate expiry and IP binding (same as decorator)
if token.expires_at > datetime.datetime.now():
if app.config.get('POW_BIND_TO_IP', True):
is_privacy_proxy = False
if app.config.get('POW_ALLOW_PRIVACY_PROXIES', True):
proxy_ranges = app.config.get('POW_PRIVACY_PROXY_RANGES', [])
for prefix in proxy_ranges:
if token.ip_address.startswith(prefix) or request.remote_addr.startswith(prefix):
is_privacy_proxy = True
break
if is_privacy_proxy or token.ip_address == request.remote_addr:
# Check request count and time limits
max_requests = app.config.get('POW_TOKEN_MAX_REQUESTS', 50)
expiry_minutes = app.config.get('POW_TOKEN_EXPIRY_MINUTES', 15)
age = datetime.datetime.now() - token.created_at
if token.request_count < max_requests and age.total_seconds() <= (expiry_minutes * 60):
has_pow = True
token.request_count += 1
token.last_request_at = datetime.datetime.now()
token.save()
except PowToken.DoesNotExist:
pass
else:
# POW not enabled, allow access
has_pow = True
# If split-brain mode disabled and no POW, return 403 challenge (old behavior)
if not has_pow and not app.config.get('POW_SPLIT_BRAIN_PHOTOS', True):
logger.info(f'Photo {photo_id}: 403 challenge (POW required, split-brain disabled)')
return_url = get_return_url()
session['pow_return_url'] = return_url
return render_template('pow_challenge.html', return_url=return_url), 403
# Log access mode for monitoring
if has_pow:
access_reason = 'authenticated' if current_user.is_authenticated else 'pow_token'
access_mode = 'full'
logger.info(f'Photo {photo_id}: Full access (200, {access_reason})')
else:
access_mode = 'preview'
logger.info(f'Photo {photo_id}: Split-brain preview (200, no POW token)')
photo = Photo.select().where(Photo.id == photo_id).get()
# Check if user has permission to view this photo
if not can_view_photo(current_user, photo):
abort(403)
(sha1Path,filename) = getSha1Path(photo.sha1)
photo.uri = sha1Path + '/' + filename
tags = Tag.select().join(PhotoTag).where(PhotoTag.photo == photo_id)
# Get photosets this photo belongs to
photo_photosets = (PhotoPhotoset.select()
.join(Photoset)
.where(PhotoPhotoset.photo == photo))
# Check if user can edit this photo
can_edit = can_edit_photo(current_user, photo)
# Detect navigation context from referrer or query params
in_context = request.args.get('in', '')
context_name = None
context_url = None
prev_photo = None
next_photo = None
visible_levels = get_visible_privacy_levels(current_user)
if in_context.startswith('photoset:'):
# Navigating within a photoset (ordered by datetaken)
# Context format: photoset:id or photoset:id:page:N
parts = in_context.split(':')
photoset_id = int(parts[1])
# Get photoset name for breadcrumb
photoset = Photoset.select().where(Photoset.id == photoset_id).first()
context_name = photoset.title if photoset else "Photoset"
context_url = f"{get_base_url()}/photosets/{photoset_id}"
# Check if there's a page number in the context
if len(parts) == 4 and parts[2] == 'page':
page_num = parts[3]
context_url = f"{get_base_url()}/photosets/{photoset_id}/page/{page_num}"
context_name = f"{context_name} : {page_num}"
# Base query for photos in this photoset
base_query = (Photo.select()
.join(PhotoPhotoset)
.where((PhotoPhotoset.photoset == photoset_id) &
((Photo.privacy.is_null()) | (Photo.privacy.in_(visible_levels)))))
# Get current photo's datetaken for comparison
current_datetaken = photo.datetaken
# Next photo: later date, or same date but higher ID
next_photo = (base_query
.where((Photo.datetaken > current_datetaken) |
((Photo.datetaken == current_datetaken) & (Photo.id > photo_id)))
.order_by(Photo.datetaken.asc(), Photo.id.asc())
.limit(1)
.first())
# Previous photo: earlier date, or same date but lower ID
prev_photo = (base_query
.where((Photo.datetaken < current_datetaken) |
((Photo.datetaken == current_datetaken) & (Photo.id < photo_id)))
.order_by(Photo.datetaken.desc(), Photo.id.desc())
.limit(1)
.first())
elif in_context.startswith('tags:'):
# Navigating within tag(s) (ordered by ID desc)
# Context format: tags:name or tags:name,name2 or tags:name:page:N
parts = in_context.split(':')
tags_str = parts[1]
tags_list = [t.strip() for t in tags_str.split(',') if t.strip()]
# Display name
if len(tags_list) == 1:
context_name = f"Tag: {tags_list[0]}"
else:
context_name = f"Tags: {', '.join(tags_list)}"
context_url = f"{get_base_url()}/tags/{tags_str}"
# Check if there's a page number in the context
if len(parts) == 4 and parts[2] == 'page':
page_num = parts[3]
context_url = f"{get_base_url()}/tags/{tags_str}/page/{page_num}"
context_name = f"{context_name} : {page_num}"
# Base query for photos with these tag(s)
if len(tags_list) == 1:
# Single tag: simple query
base_query = (Photo.select()
.join(PhotoTag)
.join(Tag)
.where((Tag.name == tags_list[0]) &
((Photo.privacy.is_null()) | (Photo.privacy.in_(visible_levels)))))
else:
# Multiple tags: intersection query
base_query = (Photo.select()
.join(PhotoTag)
.join(Tag)
.where((Tag.name.in_(tags_list)) &
((Photo.privacy.is_null()) | (Photo.privacy.in_(visible_levels))))
.group_by(Photo.id)
.having(fn.COUNT(fn.DISTINCT(Tag.id)) == len(tags_list)))
# Next photo: lower ID (because order is DESC)
next_photo = (base_query
.where(Photo.id < photo_id)
.order_by(Photo.id.desc())
.limit(1)
.first())
# Previous photo: higher ID (because order is DESC)
prev_photo = (base_query
.where(Photo.id > photo_id)
.order_by(Photo.id.asc())
.limit(1)
.first())
elif in_context.startswith('date:'):
# Navigating within a specific date (ordered by datetaken DESC - newest first)
# Context format: date:YYYY-MM-DD or date:YYYY-MM-DD:page:N
parts = in_context.split(':')
date_str = parts[1]
context_name = f"Date: {date_str}"
context_url = f"{get_base_url()}/date/{date_str}"
# Check if there's a page number in the context
if len(parts) == 4 and parts[2] == 'page':
page_num = parts[3]
context_url = f"{get_base_url()}/date/{date_str}/page/{page_num}"
context_name = f"Date: {date_str} : {page_num}"
# Base query for photos on this date (using startswith for flexible date matching)
base_query = (Photo.select()
.where((Photo.datetaken.startswith(date_str)) &
((Photo.privacy.is_null()) | (Photo.privacy.in_(visible_levels)))))
# Get current photo's datetaken for comparison
current_datetaken = photo.datetaken
# Next photo: earlier time (DESC order), or same time but lower ID
next_photo = (base_query
.where((Photo.datetaken < current_datetaken) |
((Photo.datetaken == current_datetaken) & (Photo.id < photo_id)))
.order_by(Photo.datetaken.desc(), Photo.id.desc())
.limit(1)
.first())
# Previous photo: later time (DESC order), or same time but higher ID
prev_photo = (base_query
.where((Photo.datetaken > current_datetaken) |
((Photo.datetaken == current_datetaken) & (Photo.id > photo_id)))
.order_by(Photo.datetaken.asc(), Photo.id.asc())
.limit(1)
.first())
elif in_context.startswith('photostream') or not in_context:
# Default: photostream navigation (ordered by ID desc)
context_name = "Photostream"
context_url = f"{get_base_url()}/photostream"
# Check if there's a page number in the context
if in_context.startswith('photostream:page:'):
page_num = in_context.split(':')[-1]
context_url = f"{get_base_url()}/photostream/page/{page_num}"
context_name = f"Photostream : {page_num}"
# Base query for all visible photos
base_query = Photo.select().where(
(Photo.privacy.is_null()) | (Photo.privacy.in_(visible_levels))
)
# Next photo: lower ID (because order is DESC)
next_photo = (base_query
.where(Photo.id < photo_id)
.order_by(Photo.id.desc())
.limit(1)
.first())
# Previous photo: higher ID (because order is DESC)
prev_photo = (base_query
.where(Photo.id > photo_id)
.order_by(Photo.id.asc())
.limit(1)
.first())
# Extract context photoset ID if in photoset context
context_photoset_id = None
if in_context.startswith('photoset:'):
context_photoset_id = int(in_context.split(':')[1])
# Get all tags for autocomplete
all_tags = Tag.select().order_by(Tag.name)
# Create response with custom header for nginx logging
response = make_response(render_template('photos.html', photo=photo, tags=tags,
photo_photosets=photo_photosets, can_edit=can_edit,
in_context=in_context, context_name=context_name, context_url=context_url,
prev_photo=prev_photo, next_photo=next_photo,
context_photoset_id=context_photoset_id, all_tags=all_tags, has_pow=has_pow))
# Add header for nginx to distinguish preview vs full access
response.headers['X-Cigarbox-Access'] = access_mode
return response
@app.route('/photos/<int:photo_id>/update', methods=['POST'])
@login_required
def update_photo_inline(photo_id):
"""Update photo metadata inline"""
photo = Photo.select().where(Photo.id == photo_id).get()
# Check permission
if not can_edit_photo(current_user, photo):
abort(403)
action = request.form.get('action')
if action == 'privacy':
# Update privacy
privacy = request.form.get('privacy')
if privacy:
photo.privacy = int(privacy) if privacy != 'null' else None
photo.save()
flash('Privacy updated')
elif action == 'tags':
# Update tags
tags_input = request.form.get('tags', '')
# Remove existing tags
PhotoTag.delete().where(PhotoTag.photo == photo_id).execute()
# Add new tags
if tags_input:
# Split on both comma and space to support CLI and web UI
tag_names = [t.strip().lower() for t in re.split(r'[,\s]+', tags_input) if t.strip()]
for tag_name in tag_names:
tag, created = Tag.get_or_create(name=tag_name)
PhotoTag.create(photo=photo, tag=tag)
flash('Tags updated')
# Preserve in parameter if present
in_context = request.args.get('in') or request.form.get('in')
if in_context:
return redirect(url_for('show_photo', photo_id=photo_id, **{'in': in_context}))
return redirect(url_for('show_photo', photo_id=photo_id))
@app.route('/photos/<int:photo_id>/original')
@login_required
def show_original_photo(photo_id):
"""Get signed S3 URL for original photo file"""
photo = Photo.select().where(Photo.id == photo_id).get()
# Check permission to view this photo
if not can_view_photo(current_user, photo):
abort(403)
(sha1Path,filename) = getSha1Path(photo.sha1)
S3Key = sha1Path+'/'+filename+'.'+photo.filetype
originalURL = aws.getPrivateURL(app.config,S3Key)
return redirect(originalURL)
@app.route('/photos/bulk-edit', methods=['GET', 'POST'], defaults={'page': 1})
@app.route('/photos/bulk-edit/page/<int:page>', methods=['GET', 'POST'])
@login_required
def bulk_edit_photos(page):
"""Bulk edit multiple photos at once"""
if request.method == 'POST':
# Handle bulk updates
photo_ids = request.form.get('photo_ids', '').split(',')
action = request.form.get('action')
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
# Debug logging
print(f"[BULK EDIT] Action: {action}, Photo IDs count: {len([p for p in photo_ids if p])}, AJAX: {is_ajax}")
message = ''
success = True
try:
if action == 'bulk_tags_add':
# Add tags to all photos
tags_input = request.form.get('bulk_tags', '')
if tags_input:
# Split on both comma and space to support CLI and web UI
tag_names = [t.strip().lower() for t in re.split(r'[,\s]+', tags_input) if t.strip()]
count = 0
for photo_id in photo_ids:
if not photo_id:
continue
photo = Photo.select().where(Photo.id == int(photo_id)).first()
if photo and can_edit_photo(current_user, photo):
for tag_name in tag_names:
tag, created = Tag.get_or_create(name=tag_name)
PhotoTag.get_or_create(photo=photo, tag=tag)
count += 1
message = f'Added tags to {count} photos'
else:
message = 'No tags provided'
success = False
elif action == 'bulk_privacy':
# Set privacy for all photos
privacy = request.form.get('bulk_privacy')
if privacy:
count = 0
for photo_id in photo_ids:
if not photo_id:
continue
photo = Photo.select().where(Photo.id == int(photo_id)).first()
if photo and can_edit_photo(current_user, photo):
photo.privacy = int(privacy) if privacy != 'null' else None
photo.save()
count += 1
message = f'Updated privacy for {count} photo{"s" if count != 1 else ""}'
else:
message = 'No privacy level selected'
success = False
elif action == 'bulk_photoset':
# Add all photos to photoset (or create new one)
photoset_id = request.form.get('bulk_photoset')
new_photoset_title = request.form.get('new_photoset_title', '').strip()
if photoset_id == '__new__' and new_photoset_title:
# Create new photoset (validate title is not blank)
title = new_photoset_title.strip()
if not title:
flash('Photoset title cannot be blank')
return redirect(url_for('bulk_edit_photos'))
photoset = Photoset.create(
title=title,
description='',
primary_photo_id=photo_ids[0] if photo_ids and photo_ids[0] else None
)
logger.info('PHOTOSET_CREATED id=%d title=%s user=%s', photoset.id, new_photoset_title, current_user.email)
elif photoset_id and photoset_id != '__new__':
photoset = Photoset.select().where(Photoset.id == int(photoset_id)).first()
else:
photoset = None
if photoset:
count = 0
for photo_id in photo_ids:
if not photo_id:
continue
photo = Photo.select().where(Photo.id == int(photo_id)).first()
if photo and can_edit_photo(current_user, photo):
PhotoPhotoset.get_or_create(photo=photo, photoset=photoset)
count += 1
message = f'Added {count} photos to photoset "{photoset.title}"'
else:
message = 'No photoset selected or created'
success = False
elif action == 'individual_privacy':
# Update individual photo privacy levels
count = 0
for photo_id in photo_ids:
if not photo_id:
continue
privacy_key = f'privacy_{photo_id}'
if privacy_key in request.form:
photo = Photo.select().where(Photo.id == int(photo_id)).first()
if photo and can_edit_photo(current_user, photo):
privacy = request.form.get(privacy_key)
photo.privacy = int(privacy) if privacy else None
photo.save()
count += 1
message = f'Updated privacy for {count} photo{"s" if count != 1 else ""}'
elif action == 'individual_tags':
# Update individual photo tags
count = 0
for photo_id in photo_ids:
if not photo_id:
continue
tags_key = f'tags_{photo_id}'
if tags_key in request.form:
photo = Photo.select().where(Photo.id == int(photo_id)).first()
if photo and can_edit_photo(current_user, photo):
# Remove existing tags
PhotoTag.delete().where(PhotoTag.photo == photo).execute()
# Add new tags
tags_input = request.form.get(tags_key, '')
if tags_input:
# Split on both comma and space to support CLI and web UI
tag_names = [t.strip().lower() for t in re.split(r'[,\s]+', tags_input) if t.strip()]
for tag_name in tag_names:
tag, created = Tag.get_or_create(name=tag_name)
PhotoTag.create(photo=photo, tag=tag)
count += 1
message = f'Updated tags for {count} photo{"s" if count != 1 else ""}'
elif action == 'individual_both':
# Update both privacy and tags for photos
count = 0
for photo_id in photo_ids:
if not photo_id:
continue
photo = Photo.select().where(Photo.id == int(photo_id)).first()
if photo and can_edit_photo(current_user, photo):
# Update privacy
privacy_key = f'privacy_{photo_id}'
if privacy_key in request.form:
privacy = request.form.get(privacy_key)
photo.privacy = int(privacy) if privacy else None
photo.save()
# Update tags
tags_key = f'tags_{photo_id}'
if tags_key in request.form:
tags_input = request.form.get(tags_key, '')
PhotoTag.delete().where(PhotoTag.photo == photo).execute()
if tags_input:
# Split on both comma and space to support CLI and web UI
tag_names = [t.strip().lower() for t in re.split(r'[,\s]+', tags_input) if t.strip()]
for tag_name in tag_names:
tag, created = Tag.get_or_create(name=tag_name)
PhotoTag.create(photo=photo, tag=tag)
count += 1
message = f'Saved changes to {count} photo{"s" if count != 1 else ""}'
except Exception as e:
message = f'Error: {str(e)}'
success = False
# Return JSON for AJAX requests
if is_ajax:
return jsonify({'success': success, 'message': message})
# Flash message and redirect for normal requests
flash(message)
return redirect(url_for('bulk_edit_photos', ids=','.join(photo_ids)))
# GET request - show bulk edit interface
try:
ids = request.args.get('ids', '')
if not ids:
flash('No photos selected')
return redirect(url_for('photostream'))
photo_ids = [int(id) for id in ids.split(',') if id.strip().isdigit()]
logger.info(f'Bulk edit: {len(photo_ids)} photo IDs requested')
# Load photos
photos = Photo.select().where(Photo.id.in_(photo_ids)).order_by(Photo.ts.desc())
# Check permissions and prepare photo data
editable_photos = []
for photo in photos:
if can_view_photo(current_user, photo):
(sha1Path, filename) = getSha1Path(photo.sha1)
photo.uri = sha1Path + '/' + filename
photo.can_edit = can_edit_photo(current_user, photo)
# Get existing tags
photo.tag_list = list(Tag.select().join(PhotoTag).where(PhotoTag.photo == photo))
editable_photos.append(photo)
# Get grouping preference (sanitize to prevent path injection)
group_by = request.args.get('group_by', 'upload_date')
# Strip any path components that got appended accidentally
if '/' in group_by:
group_by = group_by.split('/')[0]
# Validate it's a known value
if group_by not in ['upload_date', 'date_taken']:
group_by = 'upload_date'
# Group photos by chosen method
from collections import defaultdict
grouped_photos = defaultdict(list)
for photo in editable_photos:
if group_by == 'date_taken':
# Try to use date taken from EXIF
if photo.datetaken:
group_key = photo.datetaken.date()
group_label = photo.datetaken.strftime('%Y-%m-%d')
else:
# Fall back to file date from ImportMeta
import_meta = ImportMeta.select().where(ImportMeta.photo == photo.id).first()
if import_meta and import_meta.filedate:
# Parse filedate if it's a string
if isinstance(import_meta.filedate, str):
try:
filedate_obj = datetime.datetime.strptime(import_meta.filedate, '%Y-%m-%d %H:%M:%S')
group_key = filedate_obj.date()
group_label = filedate_obj.strftime('%Y-%m-%d') + ' (file date)'
except ValueError:
# Couldn't parse filedate
group_key = datetime.date(1970, 1, 1)
group_label = 'Unknown Date'
else:
group_key = import_meta.filedate.date()
group_label = import_meta.filedate.strftime('%Y-%m-%d') + ' (file date)'
else:
# No date info available
group_key = datetime.date(1970, 1, 1) # Sort to bottom
group_label = 'Unknown Date'
else:
# Group by upload date (day only)
group_key = photo.ts.date()
group_label = photo.ts.strftime('%Y-%m-%d')
grouped_photos[(group_key, group_label)].append(photo)
# Convert to sorted list of ((date, label), photos) tuples
photo_groups = sorted(grouped_photos.items(), key=lambda x: x[0][0], reverse=True)
# Get all photosets for dropdown
photosets = Photoset.select().order_by(Photoset.title)
# Paginate the editable_photos list
per_page = 100
total_photos = len(editable_photos)
start_idx = (page - 1) * per_page
end_idx = start_idx + per_page
paginated_photos = editable_photos[start_idx:end_idx]
# Re-group only the paginated photos
grouped_photos_paginated = defaultdict(list)
for photo in paginated_photos:
if group_by == 'date_taken':
if photo.datetaken:
group_key = photo.datetaken.date()
group_label = photo.datetaken.strftime('%Y-%m-%d')
else: