Example #1
0
File: auth.py Project: mysoftpro/pc
    def mergeUsers(self, stored_soc_user_doc_res, received_soc_user_ob, user_doc, request):
	"""
	3 cases

	2. has user_doc and pc_cookie match with that doc _id
	   its ok. just write user_ob to request and thats all
	3. has user_doc and pc_cookie DO NOT match with that doc _id
	   write user_ob to request. install found user_doc _id and pc_key
	   to request cookies. return request. separattely merge the carts
	betwwen present pc_cookie and user_doc to user_doc!!!!!!!!!!!!!!!!
	"""
	rows = stored_soc_user_doc_res['rows']
	clean_rows = [row['doc'] for row in rows if 'doc' in row and row['doc'] is not None]
	if len(clean_rows) == 0:
	    # 1. no answer from view. -> new soc user. store soc_user in user_doc
	    self.addNewSockUser(received_soc_user_ob, user_doc)
	else:
	    # just take first doc! oldest one and merge all to it
	    soc_user_doc = sorted(clean_rows, lambda x,y: int(x['_id'], 16)-int(y['_id'],16))[0]
	    if soc_user_doc['_id'] == user_doc['_id']:
                self.installPreviousUser(soc_user_doc, request)
		# its the same doc. all ok.
		# print "cookies are the same for this user and authorized user!"
		pass
	    else:
		# i have 2 different docs here.
		if 'new' in user_doc:
		    # no merge required, because user_doc is not stored yet
		    self.installPreviousUser(soc_user_doc, request)
		    # print "no merge required, because user_doc is not stored yet"
		else:
		    # merge soc user and previously stored user
		    for k,v in user_doc.items():
			if k in ['_id','_rev','pc_key']: continue
			if k not in soc_user_doc:
			    soc_user_doc[k] = v
			    continue
			else:
			    if type(v) is list:
				for el in v:
				    if el in soc_user_doc[k]:continue
				    soc_user_doc[k].append(el)
			    # ??? what about other types? i do not no yet. ATTENTION!
		    if 'merged_docs' in soc_user_doc:
			if user_doc['_id'] not in soc_user_doc['merged_docs']:
			    soc_user_doc['merged_docs'].append(user_doc['_id'])
		    else:
			soc_user_doc['merged_docs'] = [user_doc['_id']]
		    couch.saveDoc(soc_user_doc)
		    # print "SAVE MERGED doc"
		    # print soc_user_doc
		    # print user_doc
		    self.installPreviousUser(soc_user_doc, request)
	self.prepRequest(request)
	request.write(simplejson.dumps(received_soc_user_ob))
	request.finish()
Example #2
0
 def compareItem(self, some, item, sio):
     raw_doc = sio.getvalue()
     sio.close()
     doc = simplejson.loads(raw_doc)
     component_changed = False
     for k,v in doc.items():
         if k in item:
             if doc[k] != item[k]:
                 # TODO - treat changes here!
                 component_changed = True
                 doc[k] = item[k]
     if component_changed:
         couch.saveDoc(doc)
Example #3
0
 def saveDescription(self, doc, description):
     if doc is None: return
     print "save! " + doc["_id"]
     if 'description' in doc:
         # DO NOT STORE description!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         # doc['description'] = description
         return
     else:
         doc.update({'description':description})
     if 'imgs' not in doc['description']:
         couch.saveDoc(doc)
     else:
         self.getImage(doc)
Example #4
0
    def clear(self, result):
        def _sorted(name1,name2):
            return int(name1.split('-')[0])-int(name1.split('-')[0])

        for r in result['rows']:
            doc = r['doc']
            if '_attachments' not in doc:
                continue
            if len(doc['_attachments'].keys()) <= 3:
                continue
            sorted_attachments = sorted([name for name in doc['_attachments'].keys() if 'jpg' not in name], _sorted)
            for a in sorted_attachments[:-3]:
                doc['_attachments'].pop(a)
            couch.saveDoc(doc)
Example #5
0
 def update(res):
     for row in res['rows']:
         model = row['doc']
         model['original_prices'] = {}
         from pc import models
         for name,code in model['items'].items():
             if type(code) is list:
                 code = code[0]
             if code in models.gChoices_flatten:
                 component = models.gChoices_flatten[code]
                 model['original_prices'].update({code:component['price']})
             else:
                 model['original_prices'].update({code:99})
         couch.saveDoc(model)
Example #6
0
    def finish(self, doc, desc, name, img, warranty, articul, catalogs):
        descr = doc.get('description',{})
        descr.update({'comments':desc})
        descr.update({'name':name})

        imgs = descr.get('imgs',[])
        if len(img)>0:
            imgs.insert(0,img)
        descr['imgs'] = imgs

        # TODO get and store image!
        if len(warranty)>0:
            doc['warranty_type'] = warranty
        if len(articul)>0:
            doc['articul'] = articul.replace('\t','')
        if len(catalogs)>0:
            doc['catalogs'] = simplejson.loads(catalogs)
            doc['price'] = doc[self.price_field]
            doc['stock1'] = doc[self.stock_field]


        d = couch.saveDoc(doc)
        if len(img)>0:
            d.addCallback(getNewImage, img)
        return d
Example #7
0
 def storeModel(self, model, to_store, request):
     for k,v in to_store['model'].items():
         if k in model:
             model[k] = v
     d = couch.saveDoc(model)
     d.addCallback(self.finish, request)
     return d
Example #8
0
 def attach(self, attachments, doc):
     atts = {}
     for b,r in attachments:
         for k,v in r.items():
             atts.update({k:v.getvalue()})
     d = couch.addAttachments(doc,atts)
     d.addCallback(lambda _doc:couch.saveDoc(_doc))
Example #9
0
File: faq.py Project: mysoftpro/pc
    def render_POST(self, request):
        txt = request.args.get('txt',[None])[0]
        if txt is None:
            return "ok"
        doc = {'_id':base36.gen_id(),'txt':txt,'date':str(date.today()).split('-')}
        _type = request.args.get('type',[None])[0]
        if _type is None or _type not in self.types:
            _type = 'faq'
        doc.update({'type':_type})

        doc.update({'author':request.getCookie('pc_user')})
        email = request.args.get('email',[None])[0]
        if email is not None:
            doc.update({'email':email})
        name = request.args.get('name',[None])[0]
        if name is not None:
            doc.update({'name':name})
        if name is not None or email is not None:
            u = couch.openDoc(request.getCookie('pc_user'))
            u.addCallback(self.storeNameOrEmail, unicode(name, 'utf-8'), email)
        parent = request.args.get('parent',[None])
        if parent[0] is not None:
            doc['parent'] = parent

        title = request.args.get('title',[None])[0]
        if title is not None:
            doc['title'] = title

        blog = request.args.get('blog', [None])[0]
        if blog is not None:
            return self.storeBlog(doc, request)
        d = couch.saveDoc(doc)
        d.addCallback(self.finish, doc, request)
        return NOT_DONE_YET
Example #10
0
 def store(self, doc, description, request):
     if 'description' in doc:
         doc['description']['comments'] = description
     else:
         doc['description'] = {'comments':description,'imgs':[]}
     d = couch.saveDoc(doc)
     d.addErrback(self.fail, 'fail in store', request)
     d.addCallback(self.finish, request)
Example #11
0
 def addImages(self, images, doc):
     attachments = {}
     for i in images:
         if i[0]:
             attachments.update(i[1])
     d = couch.addAttachments(doc, attachments)
     d.addCallback(lambda _doc:couch.saveDoc(_doc))
     d.addErrback(self.pr)
Example #12
0
 def storeItem(self, res, gen):
     try:
         item = gen.next()
     except StopIteration:
         return
     d = couch.saveDoc(item, docId=item.pop('code'))
     d.addCallback(self.storeItem, gen)
     d.addErrback(self.pr)
Example #13
0
    def storeWholeCatalog(self, res):
        src = base64.decodestring(res)
        sio = StringIO(src)
        gz = gzip.GzipFile(fileobj=sio)

        tree = etree.parse(gz)
        root = tree.getroot()
        jsroot = xmlToJson(toDict(root.attrib), root)
        d = couch.saveDoc(jsroot, docId="catalog")
        d.addErrback(self.pr)
Example #14
0
 def update(self, doc):
     need_save = False
     for field in ('text','usd_price','soh_stock'):
         value = getattr(self,field)
         if doc[field] != value:
             need_save = True
             doc[field] = value
     retval = None
     if need_save:
         retval = couch.saveDoc(doc)
     return retval
Example #15
0
 def compareNewDocs(self, res, ids):
     deleted = []
     for row in res['rows']:
         if 'doc' in row and row['doc']['_id'] not in ids:
             if not row['doc'].get('stock1',0) ==0 or not row['doc'].get('new_stock',0) == 0:
                 row['doc']['stock1'] = 0
                 row['doc']['new_stock'] = 0
                 deleted.append(row['doc']['_id'])
                 d = couch.saveDoc(row['doc'])
                 d.addErrback(self.f**k, row['doc']['_id'])
     return ','.join(deleted)
Example #16
0
 def compareNewDocs(self, res, ids):
     deleted = []
     for row in res['rows']:
         if 'doc' in row and row['doc']['_id'] not in ids:
             if not row['doc'].get('stock1', 0) == 0 or not row['doc'].get(
                     'new_stock', 0) == 0:
                 row['doc']['stock1'] = 0
                 row['doc']['new_stock'] = 0
                 deleted.append(row['doc']['_id'])
                 d = couch.saveDoc(row['doc'])
                 d.addErrback(self.f**k, row['doc']['_id'])
     return ','.join(deleted)
Example #17
0
 def render_POST(self, request):
     order = request.args.get('order')[0]
     jorder = simplejson.loads(order)
     jorder['date'] = str(date.today()).split('-')
     model = jorder['model']
     if not 'processing' in model:
         model['processing'] = True
         d = couch.saveDoc(model)
         d.addCallback(self.storeOrder, jorder, model, request)
     else:
         d = defer.Deferred()
         d.addCallback(self.storeOrder, jorder, model, request)
         d.callback(None)
     return NOT_DONE_YET
Example #18
0
 def render_POST(self, request):
     order = request.args.get('order')[0]
     jorder = simplejson.loads(order)
     jorder['date']=str(date.today()).split('-')
     model = jorder['model']
     if not 'processing' in model:
         model['processing'] = True
         d = couch.saveDoc(model)
         d.addCallback(self.storeOrder, jorder,model,request)
     else:
         d = defer.Deferred()
         d.addCallback(self.storeOrder, jorder,model,request)
         d.callback(None)
     return NOT_DONE_YET
Example #19
0
 def update(doc):
     need_save = False
     for k, v in c.items():
         if doc[k] != v:
             doc[k] = v
             need_save = True
     if 'price' in doc:
         doc['price'] = c['us_price']
     if 'stock1' in doc:
         doc['stock1'] = c['new_stock']
     if need_save:
         d = couch.saveDoc(doc)
         d.addCallback(lambda x: c['_id'])
         d.addErrback(self.f**k, doc['_id'])
         return d
     else:
         return c['_id']
Example #20
0
 def update(doc):
     need_save = False
     for k,v in c.items():
         if doc[k] != v:
             doc[k] = v
             need_save = True
     if 'price' in doc:
         doc['price'] = c['us_price']
     if 'stock1' in doc:
         doc['stock1'] = c['new_stock']
     if need_save:                
         d = couch.saveDoc(doc)
         d.addCallback(lambda x: c['_id'])
         d.addErrback(self.f**k, doc['_id'])
         return d
     else:
         return c['_id']
Example #21
0
    def storePayment(self, payment_user, raw_payment, answer, request):
        if payment_user[0][0] and payment_user[1][0]:

            _payment = payment_user[1][1]
            _user = payment_user[0][1]
            # has payments
            if 'payments' in _user:
                stored = False
                for their_id,li in _user['payments'].items():
                    # same payment again
                    if their_id == raw_payment['paymentid']:
                        li.append(_payment['id'])
                        stored = True
                        break
                # new payment
                if not stored:
                    _user['payments'].update({raw_payment['paymentid']:[_payment['id']]})
            else:
                _user['payments'] = {raw_payment['paymentid']:[_payment['id']]}
            d = couch.saveDoc(_user)
            answer.find('code').text = 'YES'
            answer.find('id').text = _payment['id']
            d.addCallback(self.finish, answer, request)
            send_email('*****@*****.**',
                       u'Совершен платеж',
                       _payment['id']+' '+_user['_id'],
                       sender=u'Компьютерный магазин <*****@*****.**>')
            return d
        else:
            answer.find('code').text = 'NO'
            # payment is stored, but no user
            if payment_user[1][0]:
                answer.find('id').text = payment_user[1][1]['id']
                answer.find('comment').text = u'No such user '+raw_payment['userid']
                d = defer.Deferred()
                d.addCallback(self.finish, answer, request)
                d.callback(None)
                return d
            else:                
                answer.find('comment').text = u'Cant store payment '+raw_payment['paymentid']
                d = defer.Deferred()
                d.addCallback(self.finish, answer, request)
                d.callback(None)
                return d
Example #22
0
    def addImage(self, image, doc, request):
        name = [k for k in image.keys()][0]
        # GOOGLE IMAGES
        goog = 'q=tbn:'
        if goog in name:
            new_name = name.split(goog).pop()+'.jpg'
            image[new_name] = image[name]
            image.pop(name)
            name = new_name

        if name.endswith('.jpg'):
            name = name.split('.jpg')[0]
        d = couch.addAttachments(doc, image)#image is a dictionary
        if not 'description' in doc:
            doc.update({'description':{'imgs':[]}})
        imgs = doc['description'].get('imgs',[])
        imgs.insert(0,name)
        doc['description']['imgs'] = imgs
        d.addCallback(lambda _doc:couch.saveDoc(_doc))
        d.addCallback(self.finish, request)
Example #23
0
    def addImage(self, image, doc, request):
        name = [k for k in image.keys()][0]
        # GOOGLE IMAGES
        goog = 'q=tbn:'
        if goog in name:
            new_name = name.split(goog).pop() + '.jpg'
            image[new_name] = image[name]
            image.pop(name)
            name = new_name

        if name.endswith('.jpg'):
            name = name.split('.jpg')[0]
        d = couch.addAttachments(doc, image)  #image is a dictionary
        if not 'description' in doc:
            doc.update({'description': {'imgs': []}})
        imgs = doc['description'].get('imgs', [])
        imgs.insert(0, name)
        doc['description']['imgs'] = imgs
        d.addCallback(lambda _doc: couch.saveDoc(_doc))
        d.addCallback(self.finish, request)
Example #24
0
    def render_POST(self, request):
        # userid_extra = request.args.get('userid_extra',[None])[0]
        amount = request.args.get('amount',[None])[0]
        userid = request.args.get('userid',[None])[0]
        userid_extra = request.args.get('userid_extra',[None])[0]
        paymentid = request.args.get('paymentid',[None])[0]
        key = request.args.get('key',[None])[0]
        paymode = request.args.get('paymode',[None])[0]
        orderid = request.args.get('orderid',[None])[0]
        serverid = request.args.get('serverid',[None])[0]

        ha = hashlib.md5()
        def up(some):
            if some is None: return
            ha.update(some)
        # amount + userid + paymentid + секретный ключ произвольного вида (до 35 символов).
        up(amount)
        up(userid)
        up(paymentid)
        up(do_key)

        di = ha.hexdigest()

        answer = deepcopy(self.xml)

        if key is not None and di == key:
            payment = {'userid':userid,'userid_extra':userid_extra,'paymentid':paymentid,'key':key,
                       'paymode':paymode,'orderid':orderid,'serverid':serverid,'amount':amount,
                       'type':'do_payment'}
            d = couch.openDoc(userid)
            d1 = couch.saveDoc(payment)
            li = defer.DeferredList([d,d1])
            li.addCallback(self.storePayment,payment,answer,request)
            li.addErrback(self.fail, answer, request)
            return NOT_DONE_YET
        else:
            answer.find('code').text = 'No'
            answer.find('comment').text = u'Invalid key'
            return etree.tostring(answer, encoding='utf-8', xml_declaration=True)
Example #25
0
 def storeNameOrEmail(self, user_doc, name=None, email=None):
     need_to_store = False
     if name is not None:
         if 'names' in user_doc:
             if name not in user_doc['names']:
                 user_doc['names'].append(name)
                 need_to_store = True
         else:
             user_doc['names'] = [name]
             need_to_store = True
     if email is not None:
         if 'emails' in user_doc:
             if email not in user_doc['emails']:
                 user_doc['emails'].append(email)
                 need_to_store = True
         else:
             user_doc['emails'] = [email]
             need_to_store = True
     d = None
     if need_to_store:
         d = couch.saveDoc(user_doc)
     return d
Example #26
0
    def finish(self, doc, desc, name, img, warranty, articul, catalogs):
        descr = doc.get('description', {})
        descr.update({'comments': desc})
        descr.update({'name': name})

        imgs = descr.get('imgs', [])
        if len(img) > 0:
            imgs.insert(0, img)
        descr['imgs'] = imgs

        # TODO get and store image!
        if len(warranty) > 0:
            doc['warranty_type'] = warranty
        if len(articul) > 0:
            doc['articul'] = articul.replace('\t', '')
        if len(catalogs) > 0:
            doc['catalogs'] = simplejson.loads(catalogs)
            doc['price'] = doc[self.price_field]
            doc['stock1'] = doc[self.stock_field]

        d = couch.saveDoc(doc)
        if len(img) > 0:
            d.addCallback(getNewImage, img)
        return d
Example #27
0
    def addNewSockUser(self, received_soc_user_ob, user_doc):
	if 'new' in user_doc:
	    # there are no user in db
	    user_doc.pop('new')
	    user_doc['soc_users'] = [received_soc_user_ob]
	    # print "save new user_doc!"
	    # print user_doc
	    couch.saveDoc(user_doc)
	else:
	    if 'soc_users' in user_doc:
		# user was authorized before by soc network
		if received_soc_user_ob['uid'] in [ob['uid'] for ob in user_doc['soc_users']]:
		    # print "pass"
		    pass
		else:
		    # just append new soc network to existing user
		    user_doc['soc_users'].append(received_soc_user_ob)
		    # print "save OLD user_doc 1!"
		    # print user_doc
		    couch.saveDoc(user_doc)
	    else:
		# just add soc user to previously stored user
		user_doc['soc_users'] = [received_soc_user_ob]
		couch.saveDoc(user_doc)
Example #28
0
 def render_POST(self, request):
     proc = request.args.get('proc')[0]
     jproc = simplejson.loads(proc)
     d = couch.saveDoc(jproc)
     d.addCallback(self.finish, request)
     return NOT_DONE_YET
Example #29
0
 def st(fail):
     c = couch.saveDoc(item, docId=item_code)
     c.addErrback(self.pr)
Example #30
0
 def zerostock(_doc):            
     _doc['stock1'] = 0
     couch.saveDoc(_doc)
Example #31
0
 def add(self, fail):
     return couch.saveDoc({'_id':self._id,
                           'text':self.text,
                           'usd_price':self.usd_price,
                           'soh_stock':self.soh_stock})
Example #32
0
 def storeWi(self, doc, ne):
     doc['map_to_ne'] = ne
     return couch.saveDoc(doc)
Example #33
0
 def storeOrder(self, model_res, order, model, request):
     if model_res is not None:
         model['_rev'] = model_res['rev']
         order['model'] = model
     d = couch.saveDoc(order)
     d.addCallback(self.finish, model['_rev'], request)
Example #34
0
 def store(err):
     d = couch.saveDoc(c)
     d.addCallback(lambda x: c['_id'])
     d.addErrback(self.f**k, c['_id'])
     return d
Example #35
0
 def add(doc):
     d = couch.addAttachments(doc, image)  #image is a dictionary
     d.addCallback(lambda _doc: couch.saveDoc(_doc))
     d.addErrback(pr)
Example #36
0
 def storeWi(self, doc, ne):
     doc['map_to_ne'] = ne
     return couch.saveDoc(doc)
Example #37
0
 def storeHow(self, how, description):
     how['html'] = description
     return couch.saveDoc(how)
Example #38
0
 def render_POST(self,request):
     doc = request.args.get('doc',[None])[0]
     d = couch.saveDoc(simplejson.loads(doc))
     d.addCallback(self.finish, request)
     return NOT_DONE_YET
Example #39
0
 def render_POST(self, request):
     doc = request.args.get('doc', [None])[0]
     d = couch.saveDoc(simplejson.loads(doc))
     d.addCallback(self.finish, request)
     return NOT_DONE_YET
Example #40
0
 def deleteNe(self, doc):
     if 'map_to_wi' in doc:
         doc.pop('map_to_wi')
     return couch.saveDoc(doc)
Example #41
0
 def render_POST(self, request):
     video = request.args.get('video')[0]
     jvideo = simplejson.loads(video)
     d = couch.saveDoc(jvideo)
     d.addCallback(self.finish, request)
     return NOT_DONE_YET
Example #42
0
 def render_POST(self, request):
     mother = request.args.get('mother')[0]
     jmother = simplejson.loads(mother)
     d = couch.saveDoc(jmother)
     d.addCallback(self.finish, request)
     return NOT_DONE_YET
Example #43
0
 def st(fail):
     c = couch.saveDoc(item, docId=item_code)
     c.addErrback(self.pr)
Example #44
0
    def updateModelsAuthor(self, res, user_doc):
	for r in res['rows']:
	    if r['doc']['author'] != user_doc['_id']:
		r['doc']['author'] = user_doc['_id']
		couch.saveDoc(r['doc'])
Example #45
0
 def _storeBlog(self, doc, request):
     d = couch.saveDoc(doc)
     d.addCallback(self.finish, doc, request)
     return d
Example #46
0
 def storeNe(self, doc, wi):
     doc['map_to_wi'] = wi
     # destroy catalogs. it will need catalogs again!
     if 'catalogs' in doc:
         doc.pop('catalogs')
     return couch.saveDoc(doc)
Example #47
0
 def storeNe(self, doc, wi):
     doc['map_to_wi'] = wi
     # destroy catalogs. it will need catalogs again!
     if 'catalogs' in doc:
         doc.pop('catalogs')
     return couch.saveDoc(doc)
Example #48
0
 def add(doc):
     d = couch.addAttachments(doc, image)#image is a dictionary
     d.addCallback(lambda _doc:couch.saveDoc(_doc))
     d.addErrback(pr)
Example #49
0
 def deleteWi(self, doc):
     if 'map_to_ne' in doc:
         doc.pop('map_to_ne')
     return couch.saveDoc(doc)
Example #50
0
 def zerostock(_doc):
     _doc['stock1'] = 0
     couch.saveDoc(_doc)
Example #51
0
 def deleteNe(self, doc):
     if 'map_to_wi' in doc:
         doc.pop('map_to_wi')
     return couch.saveDoc(doc)
Example #52
0
 def store(err):
     d = couch.saveDoc(c)
     d.addCallback(lambda x: c['_id'])
     d.addErrback(self.f**k, c['_id'])
     return d
Example #53
0
 def createHow(self, fail, _id, descr):
     how = {'_id': _id, 'html': descr}
     return couch.saveDoc(how)
Example #54
0
 def deleteWi(self, doc):
     if 'map_to_ne' in doc:
         doc.pop('map_to_ne')
     return couch.saveDoc(doc)
Example #55
0
 def render_POST(self, request):
     note = request.args.get('note')[0]
     jnote = simplejson.loads(note)
     d = couch.saveDoc(jnote)
     d.addCallback(self.finish, request)
     return NOT_DONE_YET