[fix] problem in o2m
[odoo/odoo.git] / addons / auction / wizard / auction_aie_send.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 #
23 # Does not properly work concurrently !!!
24 #
25 from osv import fields,osv
26 from tools.translate import _
27 import base64
28 import httplib
29 import mimetypes
30 import netsvc
31 import threading
32
33 class auction_lots_send_aie(osv.osv_memory):
34     _name = 'auction.lots.send.aie'
35     _descritption = 'Send to website'
36     
37     def _date_get(self, cr, uid, context=None):
38         selection = context and context.get('selection')
39         if selection:
40             return [('','')] + selection
41         return [('','')]
42
43     _columns = {
44         'uname': fields.char('Login', size=64),
45         'password': fields.char('Password', size=64),
46         'objects': fields.integer('# of objects', readonly=True),
47         'lang': fields.selection([('fr','fr'),('ned','ned'),('eng','eng'),('de','de')],'Language'),
48         'numerotation': fields.selection([('prov','Provisoire'),('definite','Definitive (ordre catalogue)')],'Numerotation'),
49         'dates': fields.selection(_date_get,'Auction Date'),
50         'img_send': fields.boolean('Send Image also ?'),   
51     }
52     
53     def default_get(self, cr, uid, fields, context=None):
54         """ 
55          To get default values for the object.
56          @param self: The object pointer.
57          @param cr: A database cursor
58          @param uid: ID of the user currently logged in
59          @param fields: List of fields for which we want default values 
60          @param context: A standard dictionary 
61          @return: A dictionary which of fields with values. 
62         """
63         if context is None: 
64             context = {}
65         res = super(auction_lots_send_aie, self).default_get(cr, uid, fields, context=context)
66         if 'uname' in fields and context.get('uname',False):
67             res['uname'] = context.get('uname')
68         if 'password' in fields and context.get('password',False):
69             res['password'] = context.get('password')
70         return res
71     
72     def _catalog_send(uname, passwd, lang, did, catalog):
73         def post_multipart(host, selector, fields, files):
74             def encode_multipart_formdata(fields, files):
75                 BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
76                 CRLF = '\r\n'
77                 L = []
78                 for (key, value) in fields:
79                     L.append('--' + BOUNDARY)
80                     L.append('Content-Disposition: form-data; name="%s"' % key)
81                     L.append('')
82                     L.append(value)
83                 for (key,value) in files:
84                     L.append('--' + BOUNDARY)
85                     L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, key+'.pickle'))
86                     L.append('Content-Type: application/octet-stream')
87                     L.append('')
88                     L.append(value)
89                 L.append('--' + BOUNDARY + '--')
90                 L.append('')
91                 body = CRLF.join(L)
92                 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
93                 return content_type, body
94             content_type, body = encode_multipart_formdata(fields, files)
95             import httplib
96     
97             headers = {"Content-type": content_type, "Accept": "*/*"}
98             conn = httplib.HTTPConnection(host)
99             conn.request("POST", '/bin/catalog.cgi', body, headers = headers)
100             response = conn.getresponse()
101             val = response.status
102             conn.close()
103             return val
104         return post_multipart('auction-in-europe.com', "/bin/catalog.cgi", (('uname',uname),('password',passwd),('did',did),('lang',lang)),(('file',catalog),))
105     
106     def _photo_bin_send(uname, passwd, ref, did, photo_name, photo_data):
107         def get_content_type(filename):
108             return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
109     
110         def post_multipart(host, selector, fields, files):
111             def encode_multipart_formdata(fields, files):
112                 BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
113                 CRLF = '\r\n'
114                 L = []
115                 for (key, value) in fields:
116                     L.append('--' + BOUNDARY)
117                     L.append('Content-Disposition: form-data; name="%s"' % key)
118                     L.append('')
119                     L.append(value)
120                 for (key, filename, data) in files:
121                     L.append('--' + BOUNDARY)
122                     L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
123                     L.append('Content-Type: %s' % get_content_type(filename))
124                     L.append('')
125                     L.append(data)
126                 L.append('--' + BOUNDARY + '--')
127                 L.append('')
128                 body = CRLF.join(L)
129                 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
130                 return content_type, body
131             content_type, body = encode_multipart_formdata(fields, files)
132     
133             headers = {"Content-type": content_type, "Accept": "*/*"}
134             conn = httplib.HTTPConnection(host)
135             conn.request("POST", '/bin/photo.cgi', body, headers = headers)
136             response = conn.getresponse()
137             val = response.status
138             conn.close()
139             return val
140         return post_multipart('auction-in-europe.com', "/bin/photo.cgi", (('uname',uname),('ref',ref),('passwd',passwd),('did',did)),(('file',photo_name,photo_data),))
141     
142     
143     def _photos_send(cr, uid, uname, passwd, did, ids):
144         for (ref,id) in ids:
145             datas = self.pool.get('auction.lots').read(cr, uid, [id], ['name','image'])
146             if len(datas):
147                 bin = base64.decodestring(datas[0]['image'])
148                 fname = datas[0]['name']
149                 self._photo_bin_send(uname, passwd, ref, did, fname, bin)
150     
151     def get_dates(self, cr, uid, ids, context=None):
152         if context is None: 
153             context = {}
154         import httplib
155         data_obj = self.pool.get('ir.model.data')
156         conn = httplib.HTTPConnection('www.auction-in-europe.com')
157         datas = self.read(cr, uid, ids[0],['uname','password'])
158         conn.request("GET", "/aie_upload/dates_get.php?uname=%s&passwd=%s" % (datas['uname'], datas['password']))
159         response = conn.getresponse()
160         if response.status == 200:
161             def _date_decode(x):
162                 return (x.split(' - ')[0], (' - '.join(x.split(' - ')[1:]).decode('latin1','replace').encode('utf-8','replace')))
163             context['selection'] = map(_date_decode, response.read().split('\n'))
164             self._date_get(cr, uid, context=context)
165         else:
166             raise osv.except_osv(_('Error'), _("Connection to WWW.Auction-in-Europe.com failed !"))
167         id1 = data_obj._get_id(cr, uid, 'auction', 'view_auction_lots_send')
168         res_id = data_obj.browse(cr, uid, id1, context=context).res_id
169         context.update(datas)
170         return {
171             'view_type': 'form',
172             'view_mode': 'form',
173             'res_model': 'auction.lots.send.aie',
174             'views': [(res_id,'form')],
175             'type': 'ir.actions.act_window',
176             'target':'new',
177             'context': context
178         }
179     
180     def _send(self, cr, uid, ids, context=None):
181         import pickle, thread, sql_db
182         cr.execute('select name,aie_categ from auction_lot_category')
183         vals = dict(cr.fetchall())
184         cr.close()
185         if context is None: 
186             context = {}
187     
188         lots = self.pool.get('auction.lots').read(cr, uid, context.get('active_ids',[]), ['obj_num','lot_num','obj_desc','bord_vnd_id','lot_est1','lot_est2','artist_id','lot_type','aie_categ'])
189         lots_ids = []
190         datas = self.read(cr, uid, ids[0],['uname','login','lang','numerotation','dates'])
191         for l in lots:
192             if datas['numerotation']=='prov':
193                 l['ref']='%s%03d' % (l['bord_vnd_id'][1],l['lot_num'])
194                 l['ref2']='%s%03d' % (l['bord_vnd_id'][1],l['lot_num'])
195             else:
196                 l['ref']='%04d' % (l['obj_num'],)
197                 l['ref2']='%s%03d' % (l['bord_vnd_id'][1],l['lot_num'])
198             if l['artist_id']:
199                 l['artist_id'] = l['artist_id'][1]
200             else:
201                 l['artist_id'] = ''
202             for n in ('obj_desc','artist_id','lot_type'):
203                 try:
204                     l[n]=l[n].decode('utf-8','replace').encode('latin1','replace')
205                 except:
206                     l[n]=''
207             del l['lot_num']
208             del l['obj_num']
209             del l['bord_vnd_id']
210             l['aie_categ'] = vals.get(l['lot_type'], False)
211             lots_ids.append((l['ref'], l['id']))
212         args = pickle.dumps(lots)
213         thread.start_new_thread(_catalog_send, (datas['uname'],datas['password'],datas['lang'],datas['dates'], args))
214         if(datas['form']['img_send']==True):
215             thread.start_new_thread(_photos_send, (cr.dbname, uid, datas['uname'], datas['password'],datas['dates'], lots_ids))
216         return {}
217     
218     def send_pdf(self, cr, uid, ids, context=None):
219         threaded_calculation = threading.Thread(target=self._send, args=(cr, uid, ids, context))
220         threaded_calculation.start()
221         return {'type': 'ir.actions.act_window_close'}
222
223 auction_lots_send_aie()
224
225 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
226