ECLAPI.py
Go to the documentation of this file.
1 from __future__ import print_function
2 import base64
3 import sys
4 import os.path
5 import urllib2, urllib
6 from urllib2 import HTTPError
7 try:
8  import hashlib
9 except ImportError:
10  try:
11  import md5 as hashlib
12  except ImportError:
13  print("Failed to import hashlib or md5")
14  sys.exit(1)
15 
16 import random
17 
18 try:
19  # Python 2.5+
20  import xml.etree.ElementTree as etree
21 # print("running with ElementTree on Python 2.5+")
22 except ImportError:
23  try:
24  # normal ElementTree install
25  import elementtree.ElementTree as etree
26 # print("running with ElementTree")
27  except ImportError:
28  print("Failed to import ElementTree from any known place")
29  sys.exit(1)
30 
32  def __init__(self, value):
33  self.value = value
34 
35  def __str__(self):
36  return repr(self.value)
37 
39  def __init__(self, code, msg, body):
40  self.Code = code
41  self.Message = msg
42  self.Body = body
43 
44  def __str__(self):
45  return '%s %s' % (self.Code, self.Body)
46 
48 
49  SignatureMethod = "md5"
50 
51  def __init__(self, url, username=None, password=None, xml_user=True):
52  '''
53  '''
54  self._url = url
55  self._username = username
56  self._password = password
57 
58 
59  def _make_salt(self):
60  m = hashlib.new('md5')
61  m.update("%s" % (random.randint(1,1234567890),))
62  return m.hexdigest()
63 
64 
65  def _signature(self, method, args, body):
66  text = '%s:%s:%s' % (args, self._password, body)
67  h = None
68  if method == 'sha1':
69  h = hashlib.sha1()
70  elif method == 'md5':
71  h = hashlib.md5()
72  elif method == 'sha512':
73  h = hashlib.sha512()
74  if h == None:
75  return None
76  h.update(text)
77  return h.hexdigest()
78 
79 
80  def _add_signature(self, req, args, body):
81  if self._username:
82  req.add_header("X-Signature-Method", self.SignatureMethod)
83  req.add_header("X-User", self._username)
84  req.add_header("X-Signature",
85  self._signature(self.SignatureMethod, args, body))
86 
87  def post(self, entry):
88  '''
89  '''
90  if self._username:
91  entry.setAuthor(self._username)
92  params = entry.xshow().strip()
93  args = "salt=%s" % (self._make_salt(),)
94  req = urllib2.Request(url=self._url + '/E/xml_post' +
95  '?' + args, data=params)
96  #print 'Signature: '+ self.calculate_signature(self._password + ":" + params,
97  # self.SignatureMethod)
98  req.add_header("Content-type", "text/xml")
99  if self._url.startswith("https:"):
100  req.add_header("X-Password", self._password)
101  self._add_signature(req, args, params)
102  try:
103  response = urllib2.urlopen(req)
104  except HTTPError, err:
105  return err.code, err.msg, err.fp.read()
106 
107  data = response.read()
108 
109  #print data # DEBUG
110  return response.code, response.msg, data
111 
112  def close(self):
113  pass
114 
115  def list(self, category=None, form=None, tag=None,
116  limit=None, after=None, substring=None, text=None):
117  args = ['o=ids', 'salt=%s' % (self._make_salt(),)]
118  if category:
119  args.append('c=%s' % (urllib.quote_plus(category,)))
120  if form:
121  args.append('f=%s' % (urllib.quote_plus(form,)))
122  if after:
123  if type(after) != type(''):
124  after = after.strptime('%Y-%m-%d %H:%M:%S')
125  args.append('a=%s' % (urllib.quote_plus(after),))
126  if tag:
127  args.append('t=%s' % (tag,))
128  if limit:
129  args.append('l=%s' % (limit,))
130  if substring:
131  args.append('st=%s' % (urllib.quote_plus(substring),))
132  if text:
133  args.append('si=%s' % (urllib.quote_plus(text),))
134 
135  url = self._url + '/E/xml_search'
136  args = '&'.join(args)
137 
138  if args:
139  url += '?' + args
140  req = urllib2.Request(url=url)
141  self._add_signature(req, args, '')
142  #print 'Signature: '+ self.calculate_signature(self._password + ":" + params,
143  # self.SignatureMethod)
144 
145  try:
146  response = urllib2.urlopen(req)
147  except HTTPError, error:
148  raise ECLHTTPError(error.code, error.msg, error.fp.read())
149  tree = etree.parse(response)
150  entries = tree.findall('entry')
151  return [int(e.attrib.get('id')) for e in entries]
152 
153  def get(self, eid):
154  args = ['e=%s' % (eid,), 'salt=%s' % (self._make_salt(),)]
155  url = self._url + '/E/xml_get'
156  args = '&'.join(args)
157  if args:
158  url += '?' + args
159  req = urllib2.Request(url=url)
160  self._add_signature(req, args, '')
161  response = urllib2.urlopen(req)
162  return response.read()
163 
164 
165 
166 class ECLEntry:
167 
168  def __init__(self, category, tags=[], formname='default', text='', preformatted=False,
169  private=False, textile=False, related=None):
170  self._category = category
171  self._tags = tags
172  self._formname = formname
173  self._text = text
174  # Create the top level element
175  self._entry = etree.Element('entry', category=category)
176  if not preformatted:
177  self._entry.attrib['formatted']='yes'
178  if textile:
179  self._entry.attrib['html_safe']='no'
180  if private:
181  self._entry.attrib['private'] = 'yes'
182  if related:
183  self._entry.attrib['related'] = '%s' % (related,)
184  # Create the form
185  self._form = etree.SubElement(self._entry, 'form', name=formname)
186  if text:
187  # Create the text field
188  textfield = etree.SubElement(self._form, 'field', name='text')
189  # Store the text
190  textfield.text = text
191  for tag in tags:
192  etree.SubElement(self._entry, 'tag', name=tag)
193 
194  def setValue(self, name, value):
195  # Create the field
196  field = etree.SubElement(self._form, 'field', name=name)
197  # Store the text
198  field.text = value
199 
200  def setAuthor(self, name):
201  self._entry.attrib['author'] = name
202 
203  def addAttachment(self, name, filename, data=None):
204  # Create the field
205  field = etree.SubElement(self._entry, 'attachment', type='file', name=name, filename=os.path.basename(filename))
206  if data:
207  # Store the text
208  field.text = base64.b64encode(data)
209  else:
210  f = open(filename,'r')
211  b = f.read()
212  field.text = base64.b64encode(b)
213  f.close()
214 
215  def addImage(self, name, filename, image=None):
216  # Create the field
217  field = etree.SubElement(self._entry, 'attachment', type='image', name=name, filename=os.path.basename(filename))
218  # Store the text
219  if image:
220  # Store the text
221  field.text = base64.b64encode(image)
222  else:
223  f = open(filename,'r')
224  b = f.read()
225  field.text = base64.b64encode(b)
226  f.close()
227 
228  def addSubject(self, text):
229  self._entry.attrib['subject'] = text
230 
231  def xshow(self):
232  return etree.tostring(self._entry)
233 
234 if __name__ == '__main__':
235 
236  import getopt, sys
237 
238  search_text = None
239  search_substring = None
240 
241  opts, args = getopt.getopt(sys.argv[1:], 't:s:')
242  for opt, val in opts:
243  if opt == '-t': search_text = val
244  if opt == '-s': search_substring = val
245 
246  url = args[0]
247 
248  c = ECLConnection(url)
249  lst = c.list(text=search_text, substring=search_substring, limit=10)
250  print (lst)
251 
def get(self, eid)
Definition: ECLAPI.py:153
def addAttachment(self, name, filename, data=None)
Definition: ECLAPI.py:203
def __str__(self)
Definition: ECLAPI.py:44
def post(self, entry)
Definition: ECLAPI.py:87
def _add_signature(self, req, args, body)
Definition: ECLAPI.py:80
int open(const char *, int)
Opens a file descriptor.
def __init__(self, code, msg, body)
Definition: ECLAPI.py:39
def xshow(self)
Definition: ECLAPI.py:231
def close(self)
Definition: ECLAPI.py:112
def setAuthor(self, name)
Definition: ECLAPI.py:200
def _signature(self, method, args, body)
Definition: ECLAPI.py:65
string SignatureMethod
Definition: ECLAPI.py:49
def list(self, category=None, form=None, tag=None, limit=None, after=None, substring=None, text=None)
Definition: ECLAPI.py:116
def addSubject(self, text)
Definition: ECLAPI.py:228
def addImage(self, name, filename, image=None)
Definition: ECLAPI.py:215
def _make_salt(self)
Definition: ECLAPI.py:59
def __init__(self, value)
Definition: ECLAPI.py:32
def setValue(self, name, value)
Definition: ECLAPI.py:194
cet::coded_exception< errors::ErrorCodes, ExceptionDetail::translate > Exception
Definition: Exception.h:66
def __init__(self, url, username=None, password=None, xml_user=True)
Definition: ECLAPI.py:51
def __init__(self, category, tags=[], formname='default', text='', preformatted=False, private=False, textile=False, related=None)
Definition: ECLAPI.py:169
def __str__(self)
Definition: ECLAPI.py:35