Skip to content

Instantly share code, notes, and snippets.

@qingfeng
Created September 26, 2010 14:49
Show Gist options
  • Save qingfeng/597983 to your computer and use it in GitHub Desktop.
Save qingfeng/597983 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# encoding: utf-8
"""
mms.py
Created by yanxu on 2006-11-27.
Copyright (c) 2006 __80s__. All rights reserved.
"""
import os, sys
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
def load_config(settings_mod):
project_directory = os.path.dirname(settings_mod.__file__)
project_name = os.path.basename(project_directory)
sys.path.append(os.path.join(project_directory, '..'))
project_module = __import__(project_name, '', '', [''])
sys.path.pop()
# Set DJANGO_SETTINGS_MODULE appropriately.
os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project_name
if os.uname()[0] == 'FreeBSD':
os.environ['LC_ALL'] = 'zh_CN.UTF-8'
def main(msg):
load_config(settings)
from apps.blog.models import *
from apps.photos.models import *
from apps.photos.img import *
from apps.photos.EXIF import *
"""Unpack a MIME message into a directory of files."""
import email
from email.Header import decode_header
import errno
import mimetypes
import apps.photos.uuid
import datetime
import base64
from optparse import OptionParser
msg = email.message_from_string(msg)
counter = 1
fname = []
d=datetime.datetime.now()
body=''
if msg.is_multipart():
for part in msg.walk():#处理附件的部分
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
#filename = part.get_filename()
if part.get_content_maintype() == 'image':
ext = mimetypes.guess_extension(part.get_type())
uuidfname = str(uuid.uuid1())
filename = '%s%s' % ( uuidfname,ext )
if ext.find('jp')!=-1:#Image
filename = '%s' % ( uuidfname, )
fname.append(filename)
fp = open(os.path.join('/home/yanxu/mysite/templates/photos/static/images/yanxu/%s/%s/'%(str(d.year),str(d.month)), filename+'.jpg'), 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
if part.get_content_type() == 'text/html':
content=base64.decodestring(part.get_payload())
try:
body+=content.decode(part.get_content_charset()).encode('utf8')
except UnicodeDecodeError:
body+=content
body=body.replace("\n","<br>")
else:
body=msg.get_payload().replace("\n","<br>")
s = ""
for f in fname:
#save to photos
path='/home/yanxu/mysite/templates/photos/static/images/yanxu/%s/%s/'%(str(d.year),str(d.month))
resizeBig(of=path+f+'.jpg',path=path,fname=f+'-big.jpg')
resizeSmall(of=path+f+'.jpg',path=path,fname=f+'-mini.jpg')
s += '''<a href="http://qingfeng.ushared.com/photos_media/images/yanxu/%s/%s/%s.jpg"><img src="http://qingfeng.ushared.com/photos_media/images/yanxu/%s/%s/%s-big.jpg" border="0"/></a><br/>'''%((str(d.year),str(d.month),f)*2)
img = MyImage()
img.title = "By MMS"
img.summary = "By MMS"
img.pic = f
tags = process_file( open(path+f+'.jpg','rb') )
if len(tags)>0:
try:
img.exif_image_make = tags["Image Make"].values
img.exif_image_model = tags["Image Model"].values
img.exif_image_datetime = tags["Image DateTime"].values
img.exif_color_space = tags["EXIF ColorSpace"].values
img.exif_flash = tags["EXIF Flash"].values
img.exif_focal_length = tags["EXIF FocalLength"].values
img.exif_isospeed = tags["EXIF ISOSpeedRatings"].values
img.exif_imagewidth = tags["EXIF ExifImageWidth"].values
img.exif_imagelength = tags["EXIF ExifImageLength"].values
except:
pass
try:
img.save()
except:
pass
#Save to blog
e = Entry()
e.headline = "MMS Blog"
e.summary = "MMS Blog"
try:
if "Subject" in msg:
subj=msg["Subject"]
title,enc=decode_header(subj)[0]
if enc!=None:
subj=title.decode(enc).encode("utf8")
e.headline = subj
e.summary = subj
except:
pass
e.body = s+body
e.author = "MMS"
if "From" in msg:
if msg["From"]!="[email protected]":
e.email = msg["From"]
e.save()
if __name__ == '__main__':
main(sys.stdin.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment