Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- # modify_date = '2016-05-31'
- # version 0.9
- import pygtk
- import gtk
- import sane
- import base64
- import StringIO
- import time
- import sys
- import urllib
- import httplib
- import cgi
- from optparse import OptionParser
- from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
- import logging
- import getpass
- import os
- pygtk.require('2.0')
- class Application(object):
- # main application class
- def __init__(self):
- self.mainTimeout = 300 # main timeout for http response to service
- self.imageId = '' # id image to response
- self.image = None # image date to response
- self.imageType = '' # image type to response
- self.options = None
- self.logParams = {}
- # init options
- self._parse_options_()
- try:
- sane.init()
- except Exception, m:
- logging.exception(m)
- logging.exception("Can't init sane!")
- time.sleep(60 * 5)
- sys.exit(0)
- def http_list(self):
- try:
- http_server = HTTPServer(('localhost', 32556), BaseHandler)
- http_server.app = self
- logging.info('Server http start')
- http_server.timeout = 300 # restart
- http_server.handle_request()
- except Exception, message:
- logging.exception(message)
- time.sleep(10)
- def _parse_options_(self):
- parser = OptionParser("usage: %prog [options]")
- parser.add_option("-u", "--url_service", action="store", type="string", dest="url_service",
- default="pscan.np.ua:80", help="index of device in use")
- parser.add_option("-i", "--device_index", action="store", dest="id_device", default=0,
- help="index of device in use", type="int")
- parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
- help="print status messages to stdout")
- log_filename = '/var/log/remotescan/%s.log' % getpass.getuser()
- log_format = '%(asctime)s ' + getpass.getuser() + ' %(levelname)-12s %(message)s'
- # init options
- try:
- global args
- (self.options, args) = parser.parse_args()
- except Exception, message:
- logging.exception(message)
- logging.error('Error parse options')
- logging.basicConfig(filename=log_filename if not self.options.verbose else None,
- level=logging.DEBUG,
- format=log_format
- )
- def post_image(self, b64image, count_try=0):
- # post to web service
- local_params = {'IdImage': self.imageId, 'DataImage': b64image, 'TypeImage': self.imageType,
- 'UserName': self.logParams.get('uName', 'None'),
- 'UserUUID': (self.logParams.get('uUUID', '00000000-0000-0000-0000-000000000000'),),
- 'UserWarehouse': self.logParams.get('uWarehouse', '00000000-0000-0000-0000-000000000000')}
- params = urllib.urlencode(local_params)
- headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
- service = self.options.url_service
- full_response = "error"
- try:
- connection = httplib.HTTPConnection(service, timeout=self.mainTimeout)
- connection.connect()
- connection.request("POST", "/imageshare.php", params, headers)
- response = connection.getresponse()
- full_response = response.read()
- connection.close()
- except Exception, message:
- if count_try < 4:
- logging.exception(message)
- full_response = self.post_image(b64image, count_try + 1)
- return full_response
- def response_image(self):
- try:
- if self.image != -1:
- buf = StringIO.StringIO()
- self.image.save(buf, "JPEG", quality=30)
- str_img = buf.getvalue()
- str_img = base64.b64encode(str_img)
- buf.close()
- logging.info("Scan image ok")
- logging.info("Image length: %s" % len(str_img))
- response = self.post_image(str_img)
- return response
- except Exception, message:
- logging.exception(message)
- return "Error"
- def scan_image(self):
- logging.info("Scan image")
- try:
- if sane.get_devices():
- scanner = sane.open(sane.get_devices()[self.options.id_device][0])
- scanner.depth = 2
- scanner.mode = "gray"
- logging.info("Open scanner")
- else:
- logging.info("No scanner")
- message_box("Немає підєднаного сканеру")
- return False
- except Exception, message:
- logging.exception(message)
- sane.exit()
- return False
- try:
- scanner.start()
- image = scanner.snap()
- except Exception, message:
- logging.exception(message)
- message_box("Помилка роботи сканеру!")
- return False
- form = MainForm(self, image)
- if form.image2send:
- response = self.response_image()
- if response == 'OK':
- logging.info('Image delivered to service')
- else:
- message_box('Зображення не передано!')
- logging.warning('Image not delivered')
- return False
- else:
- return False
- return True
- class MainForm:
- def image2pix_buf(self):
- file_io = StringIO.StringIO()
- self.image.save(file_io, "ppm")
- contents = file_io.getvalue()
- file_io.close()
- loader = gtk.gdk.PixbufLoader("pnm")
- loader.write(contents, len(contents))
- pix_buf = loader.get_pixbuf()
- loader.close()
- orig_width = pix_buf.get_width()
- orig_height = pix_buf.get_height()
- if orig_width > orig_height:
- new_width = 300
- new_height = 300 * orig_height / orig_width
- else:
- new_height = 300
- new_width = 300 * orig_width / orig_height
- pix_buf = pix_buf.scale_simple(new_width, new_height, gtk.gdk.INTERP_BILINEAR)
- self.img_new.set_from_pixbuf(pix_buf)
- def image_rotate(self, button, name):
- if button:
- self.image = self.image.rotate(90 if name == 'left' else -90)
- self.image2pix_buf()
- def _exit_(self, button=None, name=''):
- self.img_window.destroy()
- while gtk.events_pending():
- gtk.main_iteration(False)
- gtk.main_quit()
- if button and name:
- logging.info('Exit ' + name)
- def _send_(self, button=None):
- self.app.image = self.image
- self._exit_(button, 'send button')
- self.image2send = True
- def __init__(self, app, image):
- self.app = app
- self.image = image
- self._create_widgets_()
- self.image2pix_buf()
- self.img_window.show_all()
- self.image2send = False
- gtk.main()
- def __add_sleep__(self, widget=None):
- # auto close
- if widget:
- gtk.timeout_add(120*1000, self._exit_)
- def _create_widgets_(self):
- main_window = gtk.Window(gtk.WINDOW_POPUP)
- main_window.set_resizable(0)
- main_window.set_keep_above(True)
- main_window.set_modal(1)
- main_window.set_deletable(False)
- main_window.set_decorated(True)
- main_window.set_title("Remote Scan: Попередній перегляд")
- main_window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
- main_window.set_focus_on_map(True)
- main_window.set_accept_focus(True)
- accel_group = gtk.AccelGroup()
- main_window.add_accel_group(accel_group)
- v_box1 = gtk.VBox(False, 3)
- main_window.add(v_box1)
- v_box1.show()
- h_box1 = gtk.HBox(False, 4)
- h_box2 = gtk.HBox(False, 2)
- h_box1.set_size_request(60, 60)
- bt_rotate_left = gtk.Button()
- bt_rotate_right = gtk.Button()
- image1 = gtk.Image()
- image1.set_from_file("/usr/share/pixmaps/remotescan/rotate_left.png")
- bt_rotate_left.set_image(image1)
- image2 = gtk.Image()
- image2.set_from_file("/usr/share/pixmaps/remotescan/rotate_rigth.png")
- bt_rotate_right.set_image(image2)
- self.img_new = gtk.Image()
- self.img_new.set_size_request(300, 300)
- bt_send = gtk.Button("Зберегти")
- bt_exit = gtk.Button("Відмінити")
- bt_send.set_size_request(40, 40)
- bt_exit.set_size_request(40, 40)
- bt_rotate_left.add_accelerator("clicked", accel_group, ord("X"), gtk.gdk.CONTROL_MASK, 1)
- bt_rotate_right.add_accelerator("clicked", accel_group, ord("C"), gtk.gdk.CONTROL_MASK, 1)
- bt_send.add_accelerator("clicked", accel_group, ord("s"), gtk.gdk.CONTROL_MASK, 1)
- bt_exit.add_accelerator("clicked", accel_group, ord("q"), gtk.gdk.CONTROL_MASK, 1)
- h_box1.pack_start(bt_rotate_left, True, True, 0)
- h_box1.pack_start(bt_rotate_right, True, True, 0)
- h_box2.pack_start(bt_send, True, True, 0)
- h_box2.pack_start(bt_exit, True, True, 0)
- v_box1.pack_start(h_box1, True, True, 0)
- v_box1.pack_start(self.img_new, True, True, 0)
- v_box1.pack_start(h_box2, True, True, 0)
- bt_send.set_flags(gtk.CAN_FOCUS)
- bt_rotate_left.connect("clicked", self.image_rotate, 'left')
- bt_rotate_right.connect("clicked", self.image_rotate, 'right')
- bt_send.connect("clicked", self._send_)
- bt_exit.connect("clicked", self._exit_, 'Button clicked')
- main_window.connect("destroy", gtk.main_quit)
- main_window.connect_after('show', self.__add_sleep__)
- self.img_window = main_window
- class BaseHandler(BaseHTTPRequestHandler):
- def get_params(self, params):
- if isinstance(params, dict):
- log_params = {'uName': params.get('uName', ''),
- 'uWarehouse': params.get('uWarehouse', ''),
- 'uUUID': params.get('uUUID', '')
- }
- self.server.app.imageType = params.get('imname', None)
- self.server.app.imageId = params.get('idimage', None)
- self.server.app.logParams = log_params
- return True
- return None
- def do_GET(self):
- try:
- if self.path[1:11] == 'scanimage?':
- self.path, self.query_string = self.path.split('?', 1)
- result = dict(cgi.parse_qsl(self.query_string))
- params = self.get_params(result)
- self.send_response(200)
- self.send_header('Cache-Control', 'no-cache, must-revalidate')
- self.send_header('Content-Type', 'text/json; charset=utf-8;')
- self.end_headers()
- if params:
- if self.server.app.scan_image():
- self.wfile.write('{"Response" : "OK"}')
- else:
- self.wfile.write('{"Response" : "Error"}')
- else:
- self.wfile.write('{"Response" : "Error in params request"}')
- self.finish()
- return
- except Exception, message:
- logging.exception(message)
- return self.send_error(404, 'File Not Found: %s' % self.path)
- def message_box(message_text):
- os.system('zenity --title="Remote Scan v0.9" --width=300 --timeout=20 --warning --text="%s"' % message_text)
- try:
- base_app = Application()
- base_app.http_list()
- except Exception, msg:
- logging.exception(msg)
Add Comment
Please, Sign In to add comment