This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Photo.py
612 lines (478 loc) · 20.6 KB
/
Photo.py
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
import re
import logging
import time
import stat
import random
from Globals import InitializeClass, MessageDialog, DTMLFile
from AccessControl import ClassSecurityInfo
from DateTime import DateTime
from Acquisition import aq_inner, aq_parent
from Products.PythonScripts.standard import html_quote
from Products.Photo.Photo import Photo
from Products.CheckoutableTemplates import CTPageTemplateFile
try:
from PIL import Image
except ImportError:
Image = None
from SQL import SQLBlogItemViews
from Homepage import PeterbecomBase
from TemplateAdder import addTemplates2Class
from Constants import *
import Utils
logger = logging.getLogger('Peterbecom.Photo')
#-------------------------------------------------------------------------------
manage_addPeterbePhotoForm = DTMLFile('dtml/addPeterbePhotoForm', globals())
def manage_addPeterbePhoto(dispatcher, id, title, file,
content_type='', precondition='',
store='ExtImage', engine='ImageMagick', quality=100,
timeout=0, pregen=1, description='',
reportchange=0, create_small_thumbnail=True,
pub_date=None, REQUEST=None):
"""Add Photo object."""
id = id.strip()
title = title.strip()
id, __ = Utils.cookId(id, title, file)
dest = dispatcher.Destination()
photo = PeterbePhoto(id, title, '', content_type=content_type,
precondition=precondition, store=store,
engine=engine, quality=quality,
pregen=pregen, timeout=timeout,
description=description,
pub_date=pub_date)
if hasattr(file, 'read'):
photo._data = file.read()
elif len(file) > 10000:
photo._data = file
else:
raise AttributeError, "File has no read()"
dest._setObject(id, photo)
# Images are generated at this point by manage_afterAdd()
self = dest._getOb(id)
self.index_object(idxs=PHOTO_INDEXES)
photo = self
if create_small_thumbnail:
try:
photo.manage_createSmallThumbnail()
except:
m = "Failed to create small thumbnail (%s)"
m = m % photo.absolute_url()
logger.error(m, exc_info=True)
photo.prepareExtraDisplays()
if REQUEST is not None:
try: url=dispatcher.DestinationURL()
except: url=REQUEST['URL1']
REQUEST.RESPONSE.redirect('%s/manage_main' % url)
return id
#-------------------------------------------------------------------------------
class PeterbePhoto(Photo, PeterbecomBase):
""" Photo for Peterbecom """
meta_type = PETERBEPHOTO_METATYPE
_properties = (
{'id':'title', 'type': 'string', 'mode': 'w'},
{'id':'description', 'type': 'text', 'mode': 'w'},
{'id':'pub_date', 'type': 'date', 'mode': 'w'},
{'id':'previous_ids', 'type': 'lines', 'mode': 'w'},
)
# legacy
previous_ids = []
manage_options = Photo.manage_options[:2]+\
({'label':'Got here', 'action':'manage_GotHere'},) +\
Photo.manage_options[2:]
security=ClassSecurityInfo()
def __init__(self, id, title, file, content_type='', precondition='',
store='ExtImage', engine='ImageMagick', quality=100,
pregen=0, timeout=0, description='',
pub_date=None):
""" init """
self.description = description
if pub_date is None:
pub_date = DateTime()
elif type(pub_date) == type('s'):
pub_date = DateTime(pub_date)
self.pub_date = pub_date
# the purpose of previous_ids is to remember what
# other ID/filename the object has when it gets
# renamed. This is useful if for example you rename
# dsc_1234.jpg to albert.jpg and the your friend
# Albert wants a copy of the original fullsize jpg.
self.previous_ids = []
self._cacheddescription = ''
Photo.__init__(self, id, title, file, content_type='',
precondition='', store=store, engine=engine,
quality=quality, pregen=0, timeout=0)
def getTitle(self):
""" return self.title """
title= self.title
if not title:
return self.id
return title
def hasNikonId(self):
""" return true if this objects Id looks like a Nikon generated
filename which is like 'DSC_1234.JPG' """
regex = re.compile('dsc_\d{3,4}\.jpg', re.I)
return bool(regex.findall(self.getId()))
security.declarePublic(VMS, 'setTitle')
def setTitle(self, title):
""" set self.title """
self.title = title.strip()
security.declarePublic(VMS, 'addPreviousId')
def addPreviousId(self, id):
""" add to previous_ids """
previous = getattr(self, 'previous_ids', [])
if id not in previous:
previous.append(id)
self.previous_ids = previous
def getDescription(self):
""" return self.description """
return self.description
def _getCachedDescription(self):
return getattr(self, '_cacheddescription', None)
def cacheDescription(self):
text = self.ShowDescription(self.getDescription(), 'structuredtext',
debug="caching photo description")
self._cacheddescription = text
def showDescription(self):
""" return description with structured_text """
text = self.getDescription()
text = self._getCachedDescription()
if text is None:
self.cacheDescription()
logging.info('%s Photo NOT already cached' % self.absolute_url_path())
return self._getCachedDescription()
else:
return text
security.declareProtected(VMS, 'manage_beforeDelete')
def manage_beforeDelete(self, request, response):
""" unindex """
self.unindex_object()
def index_object(self, idxs=[]):
"""A common method to allow Findables to index themselves."""
path = '/'.join(self.getPhysicalPath())
self.getCatalog().catalog_object(self, path, idxs=idxs)
def unindex_object(self):
"""A common method to allow Findables to unindex themselves."""
self.getCatalog().uncatalog_object('/'.join(self.getPhysicalPath()))
def inText(self, display=None, height=None, width=None, cookie=0,
alt=None, align='left', css_class=None, **kw):
""" return HTML rep of image link """
tagged = self.tag('thumbnail', height, width, cookie, alt,
css_class, border=1, align=align, kw=kw)
url = self.absolute_url()+'/view'
s = '<a href="%s">%s</a>'%(url, tagged)
# s += '<tr><td><small><a href="%s">%s</a></small></td></tr></table>'%\
# (url, '')
return s
# security.declareProtected(VMS, 'manage_editPhoto')
# def manage_editPhoto(self, file='', REQUEST=None):
# """ overload the super method """
# self.reportChange(self, action="Changed", comment=" the image",
# title=self.title)
# return Photo.manage_editPhoto(self, file, REQUEST)
security.declareProtected(VMS, 'manage_editPhotoDetails')
def manage_editPhotoDetails(self, title=None, description=None,
pub_date=None, newid=None,
return_ok=False, REQUEST=None):
""" save the details of the photo via the web.
If 'return_ok' is true, just return OK if everthing went
well (used by AJAX).
The 'newid' parameter can be used to rename yourself. """
if title is not None:
self.setTitle(title.strip())
if description is not None:
self.description = description.strip()
if pub_date is not None:
if isinstance(pub_date, basestring):
pub_date = DateTime(pub_date)
else:
assert hasattr(pub_date, 'strftime'), \
"pub_date doesn't have strftime()"
self.pub_date = pub_date
parent = aq_parent(aq_inner(self))
if newid and newid != self.getId():
self.addPreviousId(self.getId())
parent.manage_renameObjects([self.getId()], [newid.strip()])
self.cacheDescription()
if return_ok:
return "OK"
elif REQUEST is not None:
REQUEST.RESPONSE.redirect(parent.absolute_url())
security.declareProtected(VMS, 'manage_createSmallThumbnail')
def manage_createSmallThumbnail(self, drawstring=None, overwrite=1):
""" crop out a thumbnail and save a thumbnail that is smaller
than that of the original. """
roottitle = self.getRoot().title.split()[0]
if drawstring is None:
drawstring = roottitle
if Image is None:
return self.__old_manage_createSmallThumbnail(drawstring, overwrite)
crop_ratio = THUMBNAIL_CROP_RATIO
base = getattr(self.aq_parent, 'aq_base', self.aq_parent)
if not hasattr(base, 'thumbnails'):
base.manage_addFolder('thumbnails')
thumbfolder = getattr(self.aq_parent, 'thumbnails')
thumbfolderbase = getattr(thumbfolder, 'aq_base', thumbfolder)
if hasattr(thumbfolderbase, self.getId()):
if overwrite:
thumbfolder.manage_delObjects([self.getId()])
else:
return "Difference: 0Kb"
randstr = str(random.randrange(100, 500))
try:
extension = self.getId().split('.')[-1]
except:
extension = 'jpg'
imagefilepath = '/tmp/photo-%s.%s'%(randstr, extension)
imagefile = open(imagefilepath, 'wb')
thumbdata = self._original._PILdata()
imagefile.write(self._original._data())
imagefile.close()
img = Image.open(imagefilepath)
fmt = img.format
size_x, size_y = img.size
start_x = size_x* (crop_ratio/100.0/2.0)
end_x = size_x - start_x
start_y = size_y* (crop_ratio/100.0/2.0)
end_y = size_y - start_y
box = (int(start_x), int(start_y),
int(end_x), int(end_y))
img = img.crop(box)
# Peter: 25/12 2006, Adding resample=True because the picture looks better
# then.
img.thumbnail(self._displays['thumbnail'], resample=True)
img.save(imagefilepath, fmt)
del img
time.sleep(1)
# Run 'convert'
IN = imagefilepath
OUT = '/tmp/photo-%s-converted.%s'%(randstr, extension)
cmd = 'convert -draw '
if 1 or drawstring.find(' ') > -1:
cmd += '"%s" '%drawstring
else:
cmd += '%s '%drawstring
cmd += IN + ' ' + OUT
os.system(cmd)
# Upload new thumbnail
thumbimage = open(OUT, 'rb')
thumbfolder.manage_addImage(self.getId(), file=thumbimage.read(),
title=self.getTitle())
# Find out how much was saved
before = int(os.stat(IN)[stat.ST_SIZE]/1024.0)
after = int(os.stat(OUT)[stat.ST_SIZE]/1024.0)
# Clean up
os.remove(IN)
os.remove(OUT)
return "Difference: %sKb"%(before-after)
def __old_manage_createSmallThumbnail(self, drawstring='Peterbe.com',
overwrite=1):
""" Use 'convert' to create a filesizely smaller thumbnail """
base = getattr(self.aq_parent, 'aq_base', self.aq_parent)
if not hasattr(base, 'thumbnails'):
base.manage_addFolder('thumbnails')
thumbfolder = getattr(self.aq_parent, 'thumbnails')
thumbfolderbase = getattr(thumbfolder, 'aq_base', thumbfolder)
if hasattr(thumbfolderbase, self.getId()):
if overwrite:
thumbfolder.manage_delObjects([self.getId()])
else:
return "Difference: 0Kb"
randstr = str(random.randrange(100, 500))
try:
extension = self.getId().split('.')[-1]
except:
extension = 'jpg'
imagefile = open('/tmp/photo-%s.%s'%(randstr, extension), 'wb')
thumbdata = self._getDisplayData('thumbnail')
imagefile.write(thumbdata.getvalue())
imagefile.close()
# Run 'convert'
IN = '/tmp/photo-%s.%s'%(randstr, extension)
OUT = '/tmp/photo-%s-converted.%s'%(randstr, extension)
cmd = 'convert -draw '
if drawstring.find(' ') > -1:
cmd += '"%s" '%drawstring
else:
cmd += '%s '%drawstring
cmd += IN + ' ' + OUT
os.system(cmd)
# Upload new thumbnail
thumbimage = open(OUT, 'rb')
thumbfolder.manage_addImage(self.getId(), file=thumbimage.read(),
title=self.getTitle())
# Find out how much was saved
before = int(os.stat(IN)[stat.ST_SIZE]/1024.0)
after = int(os.stat(OUT)[stat.ST_SIZE]/1024.0)
# Clean up
os.remove(IN)
os.remove(OUT)
return "Difference: %sKb"%(before-after)
def getPubDate(self):
""" return pub_date """
return self.pub_date
security.declareProtected(VMS, 'manage_changePubDate')
def manage_changePubDate(self, date):
""" update the pub_date property """
if type(date) ==type('s'):
date = DateTime(date)
self.pub_date = date
def getContainerParts(self, root):
""" return [<folder>, <folder>,...] objects from here to root """
parts = []
container = self.aq_parent
c=1
while container != root:
parts.append(container)
try:
container = container.aq_parent
except:
break
c+=1
if c>10:
break
parts.reverse()
return parts
def direct_ext_url(self, default=None):
"""if possible return a URL to the image that is suitable for caching
if the image is based on ExtImage
The direct_ext_url is an optimization hack.
When that is true and the original image is a ExtImage then return a
special URL that puts in a special unique URL thing that nginx can
snap up.
"""
if hasattr(self, '_original') and \
os.path.isfile(self._original._get_filename(self._original.filename)):
u = self.absolute_url_path()
full_filename = self._original._get_filename(self._original.filename)
u = full_filename.replace(os.path.join(INSTANCE_HOME, 'var'),
'/peterbecom-ext-cache-%s' % \
os.stat(full_filename)[stat.ST_MTIME])
if os.environ.get('ABSOLUTE_MISC_URLS'):
u = '%s%s' % (os.environ.get('ABSOLUTE_MISC_URLS'), u)
return u
return default
## copied and slightly modified
security.declareProtected('View', 'tag')
def tag(self, display=None, height=None, width=None, cookie=0,
alt=None, css_class=None,
**kw):
"""Return HTML img tag.
"""
# Get cookie if display is not specified.
if display is None:
display = self.REQUEST.cookies.get('display', None)
# display may be set from a cookie.
if display is not None and self._displays.has_key(display):
if not self._isGenerated(display):
# Generate photo on-the-fly
self._makeDisplayPhoto(display, 1)
image = self._photos[display]
width, height = (image._width(), image._height())
# Set cookie for chosen size
if cookie:
self.REQUEST.RESPONSE.setCookie('display', display, path="/")
else:
# TODO: Add support for on-the-fly resize?
height = self._original._height()
width = self._original._width()
base = getattr(self.aq_parent, 'aq_base',self.aq_parent)
if display == 'thumbnail' and hasattr(base, 'thumbnails') and \
hasattr(getattr(base, 'thumbnails'), self.getId()):
u_s = self.absolute_url().split('/')
u_s.insert(len(u_s)-1, 'thumbnails')
u = '/'.join(u_s)
else:
u = self.absolute_url_path()
if display:
u = u.split('/')
u.insert(-2, 'display-%s' % display)
u = '/'.join(u)
else:
u = self.direct_ext_url(default=u)
result = '<img src="%s"' % (u)
if alt is None:
alt = getattr(self, 'title', '')
if alt == '':
alt = self.getId()
result = '%s alt="%s"' % (result, html_quote(alt))
if height:
result = '%s height="%s"' % (result, height)
if width:
result = '%s width="%s"' % (result, width)
if not 'border' in [x.lower() for x in kw.keys()]:
result = '%s border="0"' % (result)
if css_class is not None:
result = '%s class="%s"' % (result, css_class)
for key in kw.keys():
value = kw.get(key)
result = '%s %s="%s"' % (result, key, value)
result = '%s />' % (result)
return result
def getPrevNext(self, with_display_param=True):
""" return the URLs and titles for the previous and next item """
# do what the container would do
objects = self.aq_parent.getPhotos()
#objects.reverse()
#tmpl = '''<!--\n%s\n-->'''
thisid=self.getId()
prev=None
next=None
result = {}
for i in range(len(objects)):
if objects[i].getId()==thisid:
try:
if i-1 > -1:
prev = objects[i-1]
except IndexError:
prev = None
try:
next = objects[i+1]
except IndexError:
next = None
break
display_size = self.getPhotosDisplaySize(default=None,
use_cookies=False)
if prev:
href = prev.alias_absolute_url()+'/view'
if with_display_param and display_size is not None:
href = href.split('/')
href.insert(-2, 'display-%s' % display_size)
href = '/'.join(href)
result['prev'] = {'href':href,
'title':prev.getTitle()}
if next:
href = next.alias_absolute_url()+'/view'
if with_display_param and display_size is not None:
href = href.split('/')
href.insert(-2, 'display-%s' % display_size)
href = '/'.join(href)
result['next'] = {'href':href,
'title':next.getTitle()}
return result
def getPhotosDisplaySize(self, default='', use_cookies=False):
""" look in REQUEST and look in cookies """
if use_cookies:
value = self.REQUEST.get('display',
self.REQUEST.cookies.get('photos_display_size',
None))
else:
value = self.REQUEST.get('display', None)
if isinstance(value, list):
value = value[0]
return value
def getGotHereRecords(self, limit=40):
""" Look at the referers table for how they got here """
sql_select = self.SQLSelectCountByURL
urls = [self.absolute_url()]
for i in range(len(urls)):
urls[i] = urls[i]+'%'
return sql_select(limit=limit, urls=urls)
def prepareExtraDisplays(self):
self.manage_addDisplay('tiny', 75, 75)
self.manage_addDisplay('puny', 20, 20)
zpts =(('zpt/view_photo','view'),)
addTemplates2Class(PeterbePhoto, zpts, extension='zpt')
dtmls = ('dtml/cookieDisplaySizeJS',
('dtml/got_here', 'manage_GotHere'),
)
addTemplates2Class(PeterbePhoto, dtmls, extension='dtml')
InitializeClass(PeterbePhoto)