From cf6d71f8360accf3437e88431c5404761a36d0c1 Mon Sep 17 00:00:00 2001 From: Apkawa Date: Wed, 3 Sep 2008 13:24:45 +0400 Subject: [PATCH] =?utf8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=BE=D0=B1=D1=83=D1=8E?= =?utf8?q?=20=D1=81=D0=BE=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=B8=D1=82=D1=8C?= =?utf8?q?=20svn=20=D1=81=20git?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- uimge-svn/PKGBUILD | 38 +++++++ uimgepy/libuimge/__init__.py | 1 + uimgepy/libuimge/imagehost.py | 245 ++++++++++++++++++++++++++++++++++++++++++ uimgepy/libuimge/lang.py | 68 ++++++++++++ uimgepy/libuimge/libiu.py | 78 ++++++++++++++ uimgepy/setup_win.py | 5 + uimgepy/uimge.py | 113 +++++++++++++++++++ 7 files changed, 548 insertions(+) create mode 100644 uimge-svn/PKGBUILD create mode 100644 uimgepy/libuimge/__init__.py create mode 100644 uimgepy/libuimge/imagehost.py create mode 100644 uimgepy/libuimge/lang.py create mode 100644 uimgepy/libuimge/libiu.py create mode 100644 uimgepy/setup_win.py create mode 100644 uimgepy/uimge.py diff --git a/uimge-svn/PKGBUILD b/uimge-svn/PKGBUILD new file mode 100644 index 0000000..2803a74 --- /dev/null +++ b/uimge-svn/PKGBUILD @@ -0,0 +1,38 @@ +# Contributor: Kostin Dmitrij [DsTr] + +pkgname=uimge-svn +pkgver=68 +pkgrel=2 +pkgdesc="Python picture uploader to different imagehostings" +arch=(i686 x86_64) +url="http://code.google.com/p/uimge/" +license=('GPL') +depends=(pil python) +provides=(uimge) +conflicts=(uimge) +replaces=(uimge) +source=( ) +md5sums=( ) + +_svntrunk=http://uimge.googlecode.com/svn/trunk/src/uimgepy/ +_svnmod=uimge-svn + +build() { + cd $startdir/src + + if [ -d $_svnmod/.svn ]; then + (cd $_svnmod && svn up -r $pkgver) + else + svn co $_svntrunk --config-dir ./ -r $pkgver $_svnmod + fi + + msg "SVN checkout done or server timeout" + + cd $_svnmod + + mkdir -p $startdir/pkg/usr/lib/python2.5/site-packages/libuimge + mkdir -p $startdir/pkg/usr/bin + + install -Dm555 libuimge/* $startdir/pkg/usr/lib/python2.5/site-packages/libuimge + install -Dm755 uimge.py $startdir/pkg/usr/bin/uimge +} \ No newline at end of file diff --git a/uimgepy/libuimge/__init__.py b/uimgepy/libuimge/__init__.py new file mode 100644 index 0000000..b2c2f95 --- /dev/null +++ b/uimgepy/libuimge/__init__.py @@ -0,0 +1 @@ +import libiu, imagehost,lang \ No newline at end of file diff --git a/uimgepy/libuimge/imagehost.py b/uimgepy/libuimge/imagehost.py new file mode 100644 index 0000000..7294360 --- /dev/null +++ b/uimgepy/libuimge/imagehost.py @@ -0,0 +1,245 @@ +# -*- coding: utf-8 -*- +import libiu +from re import findall +from urllib import urlopen + +def label(file, name): + from PIL import Image + from os import stat + img=Image.open(file) + size=stat(file).st_size/1024 + title='%s %sx%s %s Kb' %(name,str(img.size[0]),str(img.size[1]),str(size) ) + return title + +def host_i_ipicture(send): + file_name,label_name,mode=send[0],send[1],send[2] + if not mode: + ihost={\ + 'host':'ipicture.ru', \ + 'post':'/Upload/', \ + 'name':'userfile',\ + 'cookie':''\ + } + + form_vaule = [\ + ('uploadtype','1'),\ + ('method','file'),\ + ('file','upload'),\ + ('thumb_resize_on','on'),('thumb_resize','200'),\ + ('submit','"Загрузить"')\ + ] + elif mode: + ihost={\ + 'host':'ipicture.ru', \ + 'post':'/Upload/', \ + 'name':'userfile',\ + 'cookie':''\ + + } + form_vaule = [\ + ('uploadtype','2'),\ + ('method','url'),\ + ('userurl[]',file_name),\ + ('thumb_resize_on','on'),('thumb_resize','200'),\ + ('submit','"Загрузить"')\ + ] + if label_name != None: + form_vaule.insert(-1,('string_small_on','on')) + form_vaule.insert(-1,('string_small', label(file_name,label_name) )) + + reurl=libiu.send_file(file_name, ihost, form_vaule, (mode,None)) + reurl=reurl.getheaders()[-5] + reurl=findall('(http://.*.html)',reurl[1]) + url=findall('\[IMG\](http://.*)\[\/IMG\]',urlopen(reurl[0]).read()) + url=[url[0],url[2]] + #return ihost,form_vaule + return url + +def host_r_radikal(send): + file_name,label_name, mode=send[0],send[1],send[2] + ihost={\ + 'host':'www.radikal.ru', \ + 'post':'/action.aspx', \ + 'name':'F',\ + 'cookie':''\ + } + + form_vaule = [\ + ('upload', 'yes'),\ + ('VM','200'),\ + ('CP','yes'),\ + ('Submit', '')\ + ] + if label_name != None: + form_vaule.insert(-1,('VE','yes')) + form_vaule.insert(-1,('V', label(file_name,label_name) )) + + if mode: + form_vaule.insert(1,('URLF',file_name)) + url=libiu.send_file(file_name, ihost, form_vaule, (mode,None)).read() + url=findall('\[IMG\](http://.*.radikal.ru.*)\[/IMG\]',url) + return url + +def host_s_imageshack(send): + file_name,label,mode=send[0],send[1],send[2] + ihost={\ + 'host':'imageshack.us', \ + 'post':'/', \ + 'name':'fileupload',\ + 'cookie':''\ + } + + form_vaule = [\ + ('uploadtype', 'on'),\ + ('Submit', '"host it!"')\ + ] + src=libiu.send_file(file_name, ihost, form_vaule, (None, mode)).read() + url=findall('value=\"(http://img.[\d]+?.imageshack.us/img[\d]+?/.*?/.*?)\"', src) + + tumburl=url[0].split('.') + tumburl.insert(-1,'th') + urls=[url[0],'.'.join(tumburl)] + return urls + +def host_t_tinypic(send): + file_name,label,mode=send[0],send[1],send[2] + ihost={\ + 'host':'s3.tinypic.com', \ + 'post':'/upload.php', \ + 'name':'the_file',\ + 'cookie':''\ + } + + form_vaule = [\ + ('action', 'upload'),\ + ('MAX_FILE_SIZE', '200000000'),\ + ('action', 'upload'),\ + ('Submit', '')\ + ] + + src=libiu.send_file(file_name, ihost, form_vaule , (None, mode)).read() + reurl=findall('http://tinypic.com/view.php\?pic=.*?\&s=[\d]',src) + src=urlopen(reurl[0]).read() + url=findall('\[IMG\](http://i[\d]+?.tinypic.com/.*?)\[/IMG\]',src) + tumburl=url[0].split('.') + tumburl[-2] += '_th' + tumburl = '.'.join(tumburl) + urls=[url[0],tumburl] + return urls + +def host_m_smages(send): + from re import sub + file_name,label,mode=send[0],send[1],send[2] + ihost={\ + 'host':'smages.com', \ + 'post':'/upload', \ + 'name':'img',\ + 'cookie':''\ + } + + form_vaule = [('Submit', '')] + reurl = sub('(\/code\/)|(\.htm)','', libiu.send_file(file_name, ihost, form_vaule , (None, mode) ).getheaders()[4][1]) + url,tmb = 'http://smages.com/i/%s'%reurl,'http://smages.com/t/%s'%reurl + return [url,tmb] + +def host_u_funkyimg(send): + file_name,label,mode=send[0],send[1],send[2] + ihost={\ + 'host':'funkyimg.com', \ + 'post':'/up.php', \ + 'name':'file_0',\ + 'cookie':''\ + } + form_vaule = [\ + ('addInfo','on'),\ + ('upload','"Upload Images"'),('uptype','file'),\ + ('file_1',''),('maxNumber','1'),('maxId','') + ] + url=findall('\[IMG\](http://funkyimg.com/.*)\[/IMG\]\[/URL\]',\ + libiu.send_file(file_name, ihost, form_vaule, (None,mode)).read()) + url.reverse() + return url + +def _host_avangard_foto_cod(send): + import urllib2 + + email='nanodesu@in-mail.ru' + passwd='splenchb' + username='nanodesu4' + album_id='7469727749' + host='avangard.photo.cod.ru' + + def auth_id_cod(user,passwd): + cookes=str(urllib2.urlopen('https://id.cod.ru/auth?email=%s&password=%s' %(user,passwd)).info()) + cookes=findall('(codsid=.+?;)[\s\S\w\W]*(auth=YES;)[\s\S\w\W]*(modified=\d+?;)', cookes)[0] + cookes='%s %s %s' %(cookes[0],cookes[1],cookes[2]) + return cookes + + def get_pages_urls(cookie,o): + + def get_pages(i,cookie): + urlpage='http://avangard.photo.cod.ru/users/%s/%s/?page=%d' %(username,album_id,i) + req = urllib2.Request(urlpage) + req.add_header('Cookie', cookie) + return urllib2.urlopen(req).read() + i=1 + url_data= get_pages(i,cookie) + i=findall('.*(\d{1,})',url_data) + + if i and not o: + i=int(i[0]) + url_data= get_pages(i,cookie) + urls = findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data) + + elif i and o: + i=int(i[0]) + urls=[] + for i in range(o,i+1): + url_data = get_pages(i,cookie) + for url in findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data): + urls.append(url) + + elif not i: + url_data= get_pages(1,cookie) + urls = findall('(http://avangard.photo.cod.ru/photos.*/w100_.*)" alt=',url_data) + #print type(urls), len(urls) + return urls,i + + def output_urls(urls): + out_url=[] + for url in urls: + tmb_100=url + urlre=url.split('/w100_') + tmb_400='%s/w400_%s'%(urlre[0],urlre[1]) + direct_url = '%s/%s'%(urlre[0],urlre[1]) + out_url.append((direct_url,tmb_400)) + return out_url + + def main(files): + mode = None + cookie=auth_id_cod(email,passwd) + ihost={\ + 'host':host, \ + 'post':'/upload/', \ + 'name':'photos[]',\ + 'cookie':cookie\ + } + + form_vaule = [\ + ('action', 'photo_upload'),\ + ('album_id',album_id),\ + ('Submit', '')\ + ] + + old_urls, o= get_pages_urls(cookie, None) + for file in files: + if libiu.send_file(file, ihost, form_vaule , (None, mode)).status == 302: pass + else: print 'error' + new_urls, o=get_pages_urls(cookie, o) + upload_urls = list( set(old_urls) ^ set(new_urls) ) + return output_urls(upload_urls) + + return main(send) + + + diff --git a/uimgepy/libuimge/lang.py b/uimgepy/libuimge/lang.py new file mode 100644 index 0000000..7d736ff --- /dev/null +++ b/uimgepy/libuimge/lang.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +from locale import getdefaultlocale + +def ru_RU(): + options_help = {'usage':u'Использование: python %prog [-i|-r|-f|-s|-t] картинка',\ + 'Major options':u'Основные опции',\ + '--ipicture':u'Залить на ipicture.ru',\ + '--radikal':u'Залить на radikal.ru',\ + '--imageshack':u'Залить на imageshack.us',\ + '--tinypic':u'Залить на tinypic.com',\ + '--smages':u'Залить на smages.com',\ + '--funkyimg':u'Залить на funkyimg.com',\ + '--photo-cod':u'Залить на avangard.photo.cod.ru',\ + 'Additional options':u'Дополнительные опции',\ + '--name':u'Добавить свое имя в превью картинки (Требуется PIL)',\ + '--file':u'Взять список файлов или url из текстового файла.',\ + '--url-mode':u'Режим перезаливки картинок с других источников в сети.',\ + 'Output options':u'Опции вывода',\ + '--bb-all':u'Объединяет опции -bo и -bt',\ + '--bb-thumb':u'Вывести в ввиде BB-кода с превью',\ + '--bb-orig':u'Вывести в ввиде BB-кода в оригинальном размере',\ + '--direct-url':u'Прямая ссылка на картинку',\ + '--user-output':u'Установить свой вид вывода. \n#URL# - url к картинке оригинального размера, \n#TMB# - url к превью. \nПример: [URL=#URL#][IMG]#TMB#[/IMG][/URL]',\ + } + error_mesages = {'Enter option':'Нет основных опций! Введите [-i|-r|-f|-s|-t]...',\ + 'ImportError PIL':'Ошибка: Нет модуля Python Imaging Library (PIL)!\nПожалуйста установите его.\n',\ + 'Not support hosting':'Данная операция не позволяется этим хостингом\n',\ + 'file format':'This file not image format\n',\ + } + messages={'progress':'Залито %d картинок из %d.\r'} + return options_help,error_mesages,messages + +def en_EN(): + options_help = {'usage':'usage: python %prog [-i|-r|-f|-s|-t] picture',\ + 'Major options':'Major options',\ + '--ipicture':'Upload to ipicture.ru',\ + '--radikal':'Upload to radikal.ru',\ + '--imageshack':'Upload to imageshack.us',\ + '--tinypic':'Upload to tinypic.com',\ + '--smages':'Upload to smages.com',\ + '--funkyimg':u'Upload to funkyimg.com',\ + '--photo-cod':'Upload to avangard.photo.cod.ru',\ + 'Additional options':'Additional options',\ + '--name':'Adding a name to preview images (Used PIL). Works with [-r|-i]',\ + '--file':'Upload image from list',\ + '--url-mode':'Upload by url. Work with [-r|-i]',\ + 'Output options':'Output options',\ + '--bb-all':'List all the options bb code',\ + '--bb-thumb':'Output in bb code with a preview',\ + '--bb-orig':'Output in bb code in the original amount',\ + '--direct-url':'The withdrawal of direct references to pictures',\ + '--user-output':'Set user output #URL# - original image, #TMB# - preview image Sample: [URL=#URL#][IMG]#TMB#[/IMG][/URL]',\ + } + error_mesages = {'Enter option':'Enter option [-i|-r|-f|-s|-t]...',\ + 'ImportError PIL':'Error: No module Python Imaging Library (PIL)!\nPlease install it.\n',\ + 'Not support hosting':'This operation does not allow it hosted.\n',\ + 'file format':'This file not image format\n',\ + } + messages={'progress':'Upload %d images of %d.\r'} + return options_help,error_mesages,messages + +def check(LANG=getdefaultlocale()[0]): + if LANG == 'ru_RU': + return ru_RU() + else: + return en_EN() + +#check(getdefaultlocale()[0]) diff --git a/uimgepy/libuimge/libiu.py b/uimgepy/libuimge/libiu.py new file mode 100644 index 0000000..f27294d --- /dev/null +++ b/uimgepy/libuimge/libiu.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +import httplib, mimetypes +#import sys,os +USER_AGENT='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) \ + Gecko/20050922 Firefox/1.0.7 (Debian package 1.0.7-1)' + +def get_file_contents(file_name): + ''' + Получаем содержание файла. + ''' + f = open(file_name); + data = f.read() + f.close() + return data +def get_content_type(file_name): + cont_type=mimetypes.guess_type(file_name)[0] or 'application/octet-stream' + return cont_type +def encode_multipart_formdata(form_vaule, file_data, mode): + ''' + Подготовка HTTP передачи + ''' + BOUNDARY = '----------' + CRLF = '\r\n' + L = [] + # add additional form fields + for (key, value) in form_vaule: + L.append('--' + BOUNDARY) + L.append('Content-Disposition: form-data; name="%s"' % key) + L.append('') + L.append(value) + # add file + if not mode: + L.append('--' + BOUNDARY) + L.append('Content-Disposition: form-data; name="%s"; filename="%s"' \ + % (file_data[0], file_data[1])) + L.append('Content-Type: %s' % get_content_type(file_data[1])) + L.append('') + L.append(file_data[2]) + + L.append('--' + BOUNDARY + '--') + L.append('') + body = CRLF.join(L) + content_type = 'multipart/form-data; boundary=%s' % BOUNDARY + + return content_type, body + +def send_file(file_name, ihost, form_vaule, mode): + ''' + send_file(file_name, ihost={'name':'','post':'','cookie':''}, form_vaule={}, mode=[True,True]) + mode,flag = mode[0],mode[1] + mode = False - заливаем просто файл, если True - то заливаем по урлу. + + flag = True - хостинг не поддерживает задивку по урлам, и поэтому обманываем его. + ''' + mode,flag = mode[0],mode[1] + + if not mode and not flag: + file_data = (ihost['name'], file_name, get_file_contents(file_name)) + + elif mode and not flag: + file_data = (ihost['name'], file_name, None) + elif not mode and flag: + from urllib import urlopen + file_data = (ihost['name'], file_name.split('/')[-1], urlopen(file_name).read()) + + + content_type, body = encode_multipart_formdata(form_vaule, file_data, mode) + header = httplib.HTTPConnection(ihost['host']) + header.putrequest('POST', ihost['post']) + header.putheader('Content-Type', content_type) + header.putheader('Content-Length', str(len(body))) + header.putheader('Referer', 'http://'+ihost['host']+'/') + header.putheader('Cookie',ihost['cookie']) + header.putheader('User-Agent', USER_AGENT) + header.endheaders() + header.send(body) + #header.set_debuglevel(1) + return header.getresponse() diff --git a/uimgepy/setup_win.py b/uimgepy/setup_win.py new file mode 100644 index 0000000..eef244e --- /dev/null +++ b/uimgepy/setup_win.py @@ -0,0 +1,5 @@ +from distutils.core import setup +import py2exe + + +setup(console=['uimge.py']) \ No newline at end of file diff --git a/uimgepy/uimge.py b/uimgepy/uimge.py new file mode 100644 index 0000000..3da0ebf --- /dev/null +++ b/uimgepy/uimge.py @@ -0,0 +1,113 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +''' +Разработчик: apkawa@gmail.com +Сайт проекта: http://code.google.com/p/uimge/ +''' +import optparse +from sys import argv,exit,stderr,stdout +from os import stat +from re import sub,search +from libuimge import imagehost,lang +import inspect +VERSION = '0.06.0.2' + +opt_help,error_mes,messages=lang.check() +IMAGEHOSTS = {} +for (name,value) in inspect.getmembers(imagehost): + if name.startswith('host_'): + IMAGEHOSTS[name[len('host_'):]]= value + +OUTPRINT={ + 'default': lambda url, eva: stdout.write('%s\n'%url[0]), + 'bt_bb-thumb': lambda url, eva: stdout.write('[url=%s][img]%s[/img][/url] ' %(url[0], url[1])), + 'bo_bb-orig': lambda url, eva: stdout.write('[img]%s[/img]\n' %(url[0])), + 'usr_user-output': lambda url, eva: stdout.write(sub('\\\\n','\n',sub('#TMB#',url[1],sub('#URL#',url[0], eva)))) + } + +class input(): + '''Usage: + > i = input(opt,filename) + > i.upload() + ''' + def __init__(self,opt,filenames): + '''__init__(self,opt, filenames) + Начальная иницилизация''' + if opt.filelist: + self.read_list(opt.filelist) + else: + self.filenames = filenames + self.count= 0 + self.mode = False + self.name = None + self.host = opt.check + self.out = opt.out + self.out_eval = None + if not OUTPRINT.has_key(self.out): + self.out_eval=self.out + self.out = 'usr_user-output' + def upload(self): + '''функция заливки изображений или урлов с изображениями''' + for file in self.filenames: + if not self.check(file): + continue + send = [file,self.name,self.mode] + url = IMAGEHOSTS[self.host](send) + OUTPRINT[self.out](url,self.out_eval) + stdout.write('\n') + def read_list(self,filelist): + self.filenames = [] + f = open(filelist,'r') + files = f.readlines() + f.close() + for file in files: self.filenames.append(sub('\n','',file)) + def check(self,filename): + if search('^http\:\/\/',filename): self.mode = True + else: self.mode = False + if not self.mode: + try: + test=stat(filename) + except OSError: + stderr.write('Not file\n') + return False + return True + +def parseopt(arg): + '''Функциия парсинга опций и вывод справки''' + usage = opt_help['usage'] + version = 'uimgepy-'+VERSION + parser = optparse.OptionParser(usage=usage, version=version) + # Major options + group_1 = optparse.OptionGroup(parser, opt_help['Major options']) + for host in IMAGEHOSTS.keys(): + sp = host.split('_') + group_1.add_option('-'+sp[0],'--'+sp[1],action='store_const', const=host, dest='check', \ + help=opt_help['--'+sp[1]]) + parser.add_option_group(group_1) + # Additional options + group_2 = optparse.OptionGroup(parser, opt_help['Additional options']) + group_2.add_option('-f','--file', action='store', default=None, dest='filelist', \ + help=opt_help['--file']) + parser.add_option_group(group_2) + group_3 = optparse.OptionGroup(parser, opt_help['Output options']) + for key in OUTPRINT.keys(): + if key != 'default': + sp = key.split('_') + if key != 'usr_user-output': + group_3.add_option('--'+sp[0],'--'+sp[1], const=key, action='store_const', \ + default='default', dest='out', help=opt_help['--'+sp[1]]) + else: + group_3.add_option('--'+sp[0],'--'+sp[1], action='store_true', \ + default='default', dest='out', help=opt_help['--'+sp[1]]) + parser.add_option_group(group_3) + opt, arguments = parser.parse_args(args=arg,) + if opt.check == None: + print error_mes['Enter option'] + parser.print_help() + exit() + return opt, arguments + +if __name__ == '__main__': + opt, filenames = parseopt(argv[1:]) + inp=input(opt, filenames) + inp.upload() -- 2.11.4.GIT