mkgallery

Instagram clone MDA
Log | Files | Refs

mkgallery.py (2021B)


      1 #! /usr/local/bin/python2
      2 
      3 import base64
      4 import datetime
      5 import email
      6 import errno
      7 import hashlib
      8 import os
      9 import re
     10 import subprocess
     11 import sys
     12 
     13 os.chdir( "/var/www/gallery" )
     14 mail = email.message_from_file( sys.stdin )
     15 now = datetime.datetime.now().strftime( "%Y-%m-%d" )
     16 
     17 def try_mkdir( path ):
     18 	try:
     19 		os.makedirs( path )
     20 	except OSError as e:
     21 		if e.errno != errno.EEXIST:
     22 			raise
     23 
     24 try_mkdir( now )
     25 
     26 # parse + save images from incoming mail
     27 def save_image( part, ext ):
     28 	body = base64.b64decode( part.get_payload() )
     29 	checksum = hashlib.sha256( body ).hexdigest()
     30 	filename = checksum + "." + ext
     31 	fullpath = now + "/" + filename
     32 	thumbpath = os.path.splitext( now + "/thumb_" + filename )[ 0 ] + ".jpg"
     33 
     34 	f = open( fullpath, "w" )
     35 	f.write( body )
     36 	f.close()
     37 
     38 	# generate thumbnail
     39 	subprocess.call( [ "convert", fullpath, "-resize", "400x400>", "-quality", "80", "-auto-orient", thumbpath ] )
     40 
     41 for part in mail.walk():
     42 	ct = part.get_content_type()
     43 	if ct == "image/jpeg":
     44 		save_image( part, "jpg" )
     45 	elif ct == "image/png":
     46 		save_image( part, "png" )
     47 
     48 # build a new gallery page
     49 page = open( now + "/index.html", "w" )
     50 page.write( "<style>" )
     51 page.write( "body { margin: 0; }" )
     52 page.write( "img { width: 100%; height: auto; margin-bottom: 1em; }" )
     53 page.write( "@media screen and ( min-width: 700px ) {" )
     54 page.write( "body { column-count: 4; column-gap: 1em; margin: 1em; }" )
     55 page.write( "}" )
     56 page.write( "</style>" )
     57 for filename in os.listdir( now ):
     58 	if filename.startswith( "thumb_" ):
     59 		continue
     60 	if filename.endswith( ".jpg" ) or filename.endswith( ".png" ):
     61 		page.write( '<a href="{}"><img src="{}"></a><br>\n'.format( filename, "thumb_" + filename ) )
     62 page.close()
     63 
     64 # build new index
     65 galleries = [ ]
     66 for gallery in os.listdir( "." ):
     67 	galleries.append( gallery )
     68 galleries.sort( reverse = True )
     69 
     70 index = open( "index.html", "w" )
     71 for gallery in galleries:
     72 	if re.match( r"\d{4}-\d{2}-\d{2}", gallery ):
     73 		index.write( '<h3><a href="{}">{}</a></h3>\n'.format( gallery, gallery ) )
     74 index.close()