Skip to content
Snippets Groups Projects
Commit c43a397b authored by Eino Tuominen's avatar Eino Tuominen
Browse files

Initial

parents
No related branches found
No related tags found
No related merge requests found
README 0 → 100644
Python helper module to save scanned documents to Seafile
# -*- coding: utf-8 -*-
import ConfigParser
class config:
pass
configparser = ConfigParser.ConfigParser()
#defaults
config.add_section('config')
configparser.set('config', 'debug', 'False')
configparser.set('config', 'scan_library', 'Scans')
configparser.set('config', 'max_attachment_bytes', '0') #'2097152') # 2MB
configparser.set('config', 'expire_days', '7')
configparser.set('config', 'template_dir', '/etc/scan2seafile/templates')
configparser.set('config', 'howto_url', 'https://howto/nönnönnöö')
configparser.set('config', 'smtp_host', 'smtp.utu.fi')
configparser.set('config', 'smtp_port', '25')
configparser.read('/etc/scan2seafile/scan2seafile.conf')
# set options
config.DEBUG = config.getboolean('config', 'debug')
config.seafile = config.get('config', 'seafile')
config.scan_library = config.get('config', 'scan_library')
config.max_att_size = int(config.get('config', 'max_attachment_bytes'))
config.token = config.get('config', 'token')
config.ldapserver = config.get('config', 'ldapserver')
config.ldapfilter = config.get('config', 'ldapfilter')
config.expire_days = int(config.get('config', 'expire_days'))
config.template_dir = config.get('config', 'template_dir')
config.howto_url = config.get('config', 'howto_url')
config.smtp_host = config.get('config', 'smtp_host')
config.smtp_port = int(config.get('config', 'smtp_port'))
import requests
import datetime
class SeafileException(Exception):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class ShareLinkFailed(SeafileException):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class DeleteItemFailed(SeafileException):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class GetUploadLinkFailed(SeafileException):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class UploadFileFailed(SeafileException):
def __init__(self,*args,**kwargs):
Exception.__init__(self,*args,**kwargs)
class Item(object):
def __init__(self, p, d):
self._path = p
self._name = d['name']
self._mtime = d['mtime']
self._type = d['type']
@property
def name(self):
return self._name
@property
def type(self):
return self._type
@property
def isFolder(self):
return self._type == 'dir'
@property
def isFile(self):
return self._type == 'file'
@property
def fullpath(self):
# ugly..
if self._path != '/':
return "{base}/{folder}".format(base=self._path, folder=self._name)
else:
return "/{folder}".format(folder=self._name)
@property
def mtime(self):
return self._mtime
@property
def age(self):
return datetime.datetime.now() - datetime.datetime.fromtimestamp(self._mtime)
class Scans(object):
def __init__(self, host, token, identity=None, libname='Scans'):
self.host = host
self.token = token
self.internal = False
self.shared = False
self.foldercreated = False
self.repo_id = None
if identity:
self._init_recipient(identity, libname)
# default if not internal and shared
if not self.repo_id:
resp = requests.get(
"https://{host}/api2/default-repo/".format(host=self.host),
headers={'Authorization': 'Token {token}'.format(token=self.token)}
)
self.repo_id = resp.json()['repo_id']
def _init_recipient(self, identity, libname):
# Try to find the user
resp = requests.get(
"https://{host}/api2/search-user/?q={user}".format(host=self.host, user=identity),
headers={
'Authorization': 'Token {token}'.format(token=self.token),
'Accept': 'application/json'
}
)
if resp.status_code == 200:
for u in resp.json()['users']:
if u['email'] == identity:
self.internal = True
break
if self.internal:
# Try to find the shared library
resp = requests.get(
"https://{host}/api2/repos/?type=shared".format(host=self.host),
headers={
'Authorization': 'Token {token}'.format(token=self.token),
'Accept': 'application/json'
}
)
if resp.status_code == 200:
for d in resp.json():
if d['name'].lower() == libname.lower() and d['owner'] == identity and 'w' in d['permission']:
self.repo_id = d['id']
self.shared = True
break
def get_upload_link(self):
resp = requests.get(
"https://{host}/api2/repos/{repo_id}/upload-link/".format(host=self.host, repo_id=self.repo_id),
headers={'Authorization': 'Token {token}'. format(token=self.token)}
).json()
# ugly api
if isinstance(resp, unicode) and resp.startswith('http'):
return str(resp)
else:
raise GetUploadLinkFailed
def share_link(self, filename, expire_days=7):
resp = requests.post(
"https://{host}/api/v2.1/share-links/".format(host=self.host),
data={
'path': '{fname}'.format(fname=filename),
'repo_id': self.repo_id,
'expire_days': expire_days
},
headers={'Authorization': 'Token {token}'. format(token=self.token)}
)
if resp.status_code == 200:
return resp.json()['link']
else:
raise ShareLinkFailed
def store(self, fhandle, fname):
upload_link = self.get_upload_link()
resp = requests.post(
upload_link, data={'parent_dir': '/'},
files={'file': (fname, fhandle)},
headers={'Authorization': 'Token {token}'. format(token=self.token)}
)
if resp.status_code != 200:
raise UploadFileFailed
def list_folders(self, base='/', fullpath=False):
resp = requests.get(
"https://{host}/api2/repos/{repo_id}/dir/?t=d&p={path}".format(host=self.host, repo_id=self.repo_id, path=base),
headers={'Authorization': 'Token {token}'. format(token=self.token)}
)
for e in resp.json():
yield Item(base, e)
def delete_item(self, item):
if isinstance(item, Item):
path = item.fullpath
else:
path = item
resp = requests.delete(
"https://{host}/api2/repos/{repo_id}/file/?p={path}".format(host=self.host, repo_id=self.repo_id, path=path),
headers={'Authorization': 'Token {token}'. format(token=self.token)}
)
if resp.status_code != 200:
raise DeleteItemFailed
@property
def folders(self, folder='/'):
resp = requests.get(
"https://{host}/api2/repos/{repo_id}/dir/?p={folder}&t=d".format(host=self.host, repo_id=self.repo_id, folder=folder),
headers={'Authorization': 'Token {token}'. format(token=self.token)}
)
for e in resp.json():
yield Item(folder, e)
@property
def files(self, folder='/'):
resp = requests.get(
"https://{host}/api2/repos/{repo_id}/dir/?p={folder}&t=f".format(host=self.host, repo_id=self.repo_id, folder=folder),
headers={'Authorization': 'Token {token}'. format(token=self.token)}
)
for e in resp.json():
yield Item(folder, e)
setup.py 0 → 100644
import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "Scan2Seafile",
version = "0.9.0",
author = "Eino Tuominen",
author_email = "eino@utu.fi",
description = ("Helper module for save scanned documents to Seafile"),
license = "BSD",
keywords = "seafile",
url = "https://gitlab.utu.fi/eino/Scan2Seafile",
packages=['Scan2Seafile'],
long_description=read('README'),
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: Office/Business",
"License :: OSI Approved :: BSD License",
],
)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment