Exemplo n.º 1
0
    def delete_msg(cls, mid):
        from models import Share

        msg = cls.get_by(id_=mid)
        sid = msg.shareid
        if msg:
            db.session.delete(msg)
            db.session.commit()
            msg = cls.get_by(shareid=sid)
            if msg is None:  # 当分享没有关联消息时删除
                Share.delete_share(sid)
Exemplo n.º 2
0
 def getShare(self, user, channel, msg):
     share = Share.by_name(msg.lower())
     if share is not None:
         line = "%s: %s" % (share.name, share.private_key)
         if share.read_only:
             line += " (read only)"
         self.display(user, channel, line)
     else:
         self.display(user, channel, "Share not found with name '%s'" % msg.lower())
         searchResults = len(Share.by_search(msg.lower()))
         if 0 < searchResults <= 10:
             self.display(user, channel, "%d similar share(s) found via search" % searchResults)
Exemplo n.º 3
0
def insertShare(request, mid, suname):
    if request.user.is_authenticated():
        try :
            tempUser = User.objects.get(username=suname)
            su = SylvieUser.objects.get(user=tempUser)
            m = Map.objects.get(mid=mid)
            s = Share(mid=m, suid=su)
            s.save()
            return success()
        except:
            return failure()
    return failure()
Exemplo n.º 4
0
def insertData(qiniukey):
    share = Share.query.filter(Share.share_qiniuurl == qiniukey).first()
    if share is None:
        share = Share(None, qiniukey)
        db_session.add(share)
        db_session.commit()
    return share
Exemplo n.º 5
0
def list_directory(request,share,subdir=None):
    if not share.check_path(subdir=subdir):
        return render(request,'error.html', {"message": "Unable to locate the files.  It is possible that the directory has been moved, renamed, or deleted.","share":share,"subdir":subdir})
    files,directories = list_share_dir(share,subdir=subdir,ajax=request.is_ajax())
    print files
    if request.is_ajax():
        return json_response({'files':files,'directories':directories.values()})
    #Find any shares that point at this directory
    for s in Share.user_queryset(request.user).filter(real_path__in=directories.keys()).exclude(id=share.id):
        directories[s.real_path]['share']=s
    share_perms = share.get_user_permissions(request.user)
    PATH = share.get_path()
    subshare = None
    if subdir is not None:
        PATH = os.path.join(PATH,subdir)
        subshare = Share.objects.filter(parent=share,sub_directory=subdir).first()
    owner = request.user == share.owner
    all_perms = share.get_permissions(user_specific=True)
    shared_users = all_perms['user_perms'].keys()
    shared_groups = [g['group']['name'] for g in all_perms['group_perms']]
    emails = sorted([u.email for u in share.get_users_with_permissions()])
    readme = None
    #The following block is for markdown rendering
    if os.path.isfile(os.path.join(PATH,'README.md')):
        import markdown
        input_file = codecs.open(os.path.join(PATH,'README.md'), mode="r", encoding="utf-8")
        text = input_file.read()
        readme = markdown.markdown(text,extensions=['fenced_code','tables','nl2br'])
        download_base = reverse('download_file',kwargs={'share':share.id,'subpath':subdir if subdir else ''})
        readme = re.sub(r'src="(?!http)',r'src="{0}'.format(download_base),readme)
    return render(request,'list.html', {"session_cookie":request.COOKIES.get('sessionid'),"files":files,"directories":directories.values(),"path":PATH,"share":share,"subshare":subshare,"subdir": subdir,'rsync_url':get_setting('RSYNC_URL',None),'HOST':get_setting('HOST',None),'SFTP_PORT':get_setting('SFTP_PORT',None),"folder_form":FolderForm(),"metadata_form":MetaDataForm(), "rename_form":RenameForm(),"request":request,"owner":owner,"share_perms":share_perms,"all_perms":all_perms,"share_perms_json":json.dumps(share_perms),"shared_users":shared_users,"shared_groups":shared_groups,"emails":emails, "readme":readme})
Exemplo n.º 6
0
 def get(self):
     client_id = self.request.get_range('client_id') or int(
         self.request.headers.get('Client-Id') or 0)
     client = Client.get(client_id)
     if not client:
         self.abort(400)
     shares = Share.query(Share.share_type == INVITATION,
                          Share.sender == client.key).fetch()
     share_dicts = []
     for share in shares:
         share_dict = share.dict()
         shared_ready = 0
         shared_done = 0
         for shared_promo in SharedPromo.query(
                 SharedPromo.sender == client.key).fetch():
             if shared_promo.status == SharedPromo.READY:
                 shared_ready += 1
             elif shared_promo.status == SharedPromo.DONE:
                 shared_done += 1
         share_dict.update({
             'ready_number': shared_ready,
             'done_number': shared_done
         })
         share_dicts.append(share_dict)
     self.render_json({'shares': share_dicts})
Exemplo n.º 7
0
def share():
    share_target = User.query.filter_by(
        username='******').first()  # Now users can share image only with admin
    try:
        path = request.json['path']
        img_id = PATTERN_IMG_ID.match(path).groups()[0]
        image = Image.query.filter_by(owner=current_user, id=img_id).first()
        if image:
            share = Share(image=image, shared_user=share_target)
            db.session.add(share)
            db.session.commit()

            # send_notification_mail(share_target, app.config.get("BASE_URL")+path) # implement before official release
            print(f'[*] share {path}')
            redis.rpush('query', path)
            redis.incr('queued_count')

            return jsonify({'result': 'ok'}), 200
    except IntegrityError as e:
        print(e)
        return jsonify({'error': 'Already shared'}), 400
    except Exception as e:
        print(e)
        return jsonify({'error': 'Internal Server Error'}), 400
    return jsonify({}), 404
Exemplo n.º 8
0
def my_notes():
    user = User.query.filter_by(id=current_user.id).first()

    form = CreateNoteForm(meta={'csrf_context': session})
    if form.validate_on_submit():
        heading = form.heading.data
        title = form.title.data
        body = form.body.data
        public = form.public.data
        note = Note(title=title,
                    heading=heading,
                    body=body,
                    owner=user,
                    public=public)
        db.session.add(note)

        shares_list = {row.strip() for row in form.shares.data.split()}
        for user_name in shares_list:
            share = Share(note=note, user_name=user_name)
            db.session.add(share)

        db.session.commit()

        flash('Notatka została dodana', 'alert alert-success')

    notes = user.notes
    return render_template('my_notes.html', form=form, notes=notes)
Exemplo n.º 9
0
 def listShares(self, user, channel, msg):
     ''' Get shares by creator '''
     shares = Share.by_creator(msg.lower())
     if shares is not None and 0 < len(shares):
         for share in shares:
             self.display(user, channel, str(share))
     else:
         self.display(user, channel, "No shares created by '%s'" % msg.lower())
Exemplo n.º 10
0
Arquivo: home.py Projeto: nickhs/vowel
def _create_share(form):
    article = Article.query.filter_by(url=form.url.data).first()

    if not article:
        article = Article(form.url.data)
        article.save()

    user = User.query.filter_by(email=form.friend.data).first()
    if not user:
        user = User(form.friend.data)
        user.save()

    share = Share(current_user, user, article)
    share.save()

    parse_article(article, share)
    return "Successfully shared to %s" % user.get_name()
Exemplo n.º 11
0
Arquivo: home.py Projeto: nickhs/vowel
def _create_share(form):
    article = Article.query.filter_by(url=form.url.data).first()

    if not article:
        article = Article(form.url.data)
        article.save()

    user = User.query.filter_by(email=form.friend.data).first()
    if not user:
        user = User(form.friend.data)
        user.save()

    share = Share(current_user, user, article)
    share.save()

    parse_article(article, share)
    return "Successfully shared to %s" % user.get_name()
Exemplo n.º 12
0
 def addShare(self, user, channel, msg):
     ''' Add a user's shared key to the database '''
     args = self.addShareParser.parse_args(msg.split())
     shareName = ' '.join(args.name).lower()
     shareKey = args.key.upper()
     if Share.by_name(shareName) is None and Share.by_private_key(shareKey) is None:
         share = Share(
             name=shareName,
             creator=user.lower(),
             private_key=shareKey, 
             description=' '.join(args.description)
         )
         dbsession.add(share)
         dbsession.flush()
         returnMessage = "Succesfully added new share '%s' to database" % share.name
     else:
         returnMessage = "Share already exists with that name or key"
     self.display(user, channel, returnMessage)
Exemplo n.º 13
0
def search_files(request):
    from utils import find
    query = request.GET.get('query',None)
    results=[]
    if query:
        shares = Share.user_queryset(request.user)
        for s in shares:
            r=find(s,query,prepend_share_id=False)
            results.append({'share':s,'results':r})
    return render(request, 'search/search_files.html', {'query':query,'results':results})
Exemplo n.º 14
0
def search_files(request):
    from utils import find
    query = request.GET.get('query',None)
    results=[]
    if query:
        shares = Share.user_queryset(request.user)
        for s in shares:
            r=find(s,query,prepend_share_id=False)
            results.append({'share':s,'results':r})
    return render(request, 'search/search_files.html', {'query':query,'results':results})
Exemplo n.º 15
0
    def addshare(self, issuerID):
        """
        Adds share details of specified share to database to database.

        Args:
            issuerID (str): ASX issued code of share to add.
        Returns:
            bool: True if sucessful, false if share doesn't exist or is
                  already present.

        """
        # Initialse session
        with self.sessionmanager() as session:
            # Check that share isn't already added to database
            share = session.query(Share).filter(
                Share.issuerID == issuerID).first()
            if share is not None:
                return False
            # Get share data from ASX
            address = ("https://www.asx.com.au/asx/1/company/"
                       f"{issuerID}?fields=primary_share")
            asxdata = requests.get(address).json()
            # Check if share data was not retrieved successfully
            if asxdata.get('error_code'):
                return False
            # Create new share record
            share = Share(
                issuerID=asxdata['code'],
                fullname=asxdata['name_full'],
                abbrevname=asxdata['name_abbrev'],
                shortname=asxdata['name_short'],
                description=asxdata['principal_activities'],
                industrysector=asxdata['sector_name'],
                currentprice=float(
                    asxdata['primary_share']['last_price']),
                marketcapitalisation=int(
                    asxdata['primary_share']['market_cap']),
                sharecount=int(
                    asxdata['primary_share']['number_of_shares']),
                daychangepercent=float(
                    asxdata['primary_share']['change_in_percent'].
                    strip('%'))/100,
                daychangeprice=float(
                    asxdata['primary_share']['change_price']),
                daypricehigh=float(
                    asxdata['primary_share']['day_high_price']),
                daypricelow=float(
                    asxdata['primary_share']['day_low_price']),
                dayvolume=int(
                    asxdata['primary_share']['volume'])
            )
            # Add share to share table
            session.add(share)
        # Return true for success
        return True
Exemplo n.º 16
0
def ajax_share(request):
    user_id = request.user_id
    share_uuid = request.POST.get('share_uuid', '')
    last_share_uuid = request.POST.get('last_share_uuid', '')
    job_uuid = request.POST.get('job_uuid', '')
    recommend_uuid = request.POST.get('recommend_uuid', '')
    data = ""
    if job_uuid:  # 分享职位详情
        job_details = Job.objects.filter(uuid=job_uuid)[:1]
        if job_details:
            if last_share_uuid:
                shares = Share.objects.filter(uuid=last_share_uuid)[:1]
                if not shares:
                    return HttpResponse("十分抱歉,获取上个人推荐信息失败,请重试。重试失败请联系客服人员")
                last_share_id = shares[0].id
            else:
                last_share_id = 0

            job_share = Share(user_id=user_id,
                              uuid=share_uuid,
                              job_id=job_details[0].id,
                              last_share_id=last_share_id)
            job_share.save()
            data = "ok"
        else:
            log.error("uid(%s) try to get not exsit job(%s), maybe attack" %
                      (user_id, job_uuid))
            return HttpResponse("十分抱歉,获取职位信息失败,请重试。重试失败请联系客服人员")

    if recommend_uuid:  # 分享带录音的职位详情
        recommends = MyRecommend.objects.filter(uuid=recommend_uuid)[:1]
        if recommends:
            if last_share_uuid:
                shares = Share.objects.filter(uuid=last_share_uuid)[:1]
                if not shares:
                    return HttpResponse("十分抱歉,获取上个人推荐信息失败,请重试。重试失败请联系客服人员")
                last_share_id = shares[0].id
            else:
                last_share_id = 0

            job_share = Share(user_id=user_id,
                              uuid=share_uuid,
                              recommend_id=recommends[0].id,
                              last_share_id=last_share_id)
            job_share.save()
            data = "ok"
        else:
            log.error(
                "uid(%s) try to get not exsit recommend(%s), maybe attack" %
                (user_id, recommend_uuid))
            return HttpResponse("十分抱歉,获取推荐信息失败,请重试。重试失败请联系客服人员")
    return HttpResponse(data, content_type='application/json')
Exemplo n.º 17
0
def verify_share():
    fid = request.args.get('fid')
    nonce = request.args.get('nonce')
    # 查询分享数据库中是否有该文件
    f = Share.get_by(fid = fid, nonce = nonce)
    if(not f):
        return 404
    else:
        f = File.get_by(fileid = fid)
        fname = f.filename
        uid = f.uid
        name = User.get_by(usrid = uid).usrname
        return render_template('unlock.html', form=EnsureForm(fid=fid, nonce=nonce), \
            fname=fname, name=name)
Exemplo n.º 18
0
    def get(self):
        client_id = int(self.request.headers.get('Client-Id') or 0)
        if not client_id:
            self.abort(400)
        client = Client.get(client_id)
        if not client:
            self.abort(400)

        if not config.SHARE_INVITATION_ENABLED:
            self.abort(403)
        share = Share.query(Share.sender == client.key, Share.status == Share.ACTIVE,
                            Share.share_type == branch_io.INVITATION).get()
        logging.info('Found share: %s' % share)
        if share and not share.promo_code and not share.channel_urls:
            self.abort(412)
        if not share:
            share = Share(share_type=branch_io.INVITATION, sender=client.key)
            share.put()  # need share id

            if 'iOS' in self.request.headers["User-Agent"]:
                user_agent = 'ios'
            elif 'Android' in self.request.headers["User-Agent"]:
                user_agent = 'android'
            else:
                user_agent = 'unknown'
            urls = [{
                'url': branch_io.create_url(share.key.id(), branch_io.INVITATION, channel, user_agent),
                'channel': channel
            } for channel in branch_io.CHANNELS]
            share.channel_urls = [ChannelUrl(url=url['url'], channel=url['channel']) for url in urls]
            group_promo_codes = PromoCodeGroup()
            group_promo_codes.put()
            promo_code = PromoCode.create(group_promo_codes, KIND_SHARE_INVITATION, 100000, title=u'Переход по совету друга')
            share.promo_code = promo_code.key
            share.put()

        self.render_json({
            'text': config.SHARE_INVITATION_MODULE.invitation_text,
            'urls': [channel_url.dict() for channel_url in share.channel_urls],
            'image': config.SHARE_INVITATION_MODULE.invitation_image,
            'promo_code': share.promo_code.id()
        })
Exemplo n.º 19
0
def post_share():
    import random, string
    from config import domain_name, sy_public_key

    user = current_user
    fid = request.form['fid']
    choice = request.form['choice']
    nonce = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8))
    ShareKey = secret.new_symmetric_key()
    sym_key = secret.new_symmetric_key()
    # 先对称解密再用新的分享密钥对称加密
    Share.decrypt_and_encrypt(fid, user, sym_key)
    # 分享码对对称密钥加密
    enc_key = secret.symmetric_encrypt(ShareKey, sym_key)
    # 慢速哈希分享码
    hashShareKey = argon2.using(rounds=256, memory_cost=1024).hash(ShareKey)
    # 使用服务器公钥加密分享码
    enc_ShareKey = secret.encrypt(bytes.fromhex(sy_public_key), ShareKey)
    sid = Share.add_share(fid, hashShareKey, enc_ShareKey, nonce, enc_key)
    # 向指定用户发送分享消息
    choice = choice.split(',')
    for u in choice:
        Message.create_msg(User.get_by(mail=u).usrid, user.usrname, sid, File.get_by(fileid=fid).filename)
    return '分享成功!'
Exemplo n.º 20
0
 def search(self, user, channel, msg):
     ''' Search for shares in the database '''
     logging.info("Searching for '%s'" % msg)
     if len(msg) <= 2:
         self.display(user, channel, "Search term too short") 
     else:
         shares = Share.by_search(msg)
         if shares is None or 0 == len(shares):
             self.display(user, channel, "No results found")
         elif len(shares) <= 10:
             self.display(user, channel, " [Creator] Share Name : Share Private Key")
             self.display(user, channel, "------------------------------------------")
             for share in shares:
                 self.display(user, channel, str(share))
         else:
             self.display(user, channel, "Too many results, narrow your search")
Exemplo n.º 21
0
def post_share(user, obj):
	'''
	'''
	v = Share.objects.filter(user=user, object_id=obj.id)
	if v:
		return v[0]
	if user == obj.user:
		return True
	
	d = Dynamic(column=user.userprofile.get_column(),
	            content_object=obj)
	
	share = Share(user=user, content_object=obj)
	
	if isinstance(obj, Link):
		d.way = WAY_LINK_SHARE
		share.way = 'l'
	elif isinstance(obj, Discuss):
		d.way = WAY_DISCUSS_SHARE
		share.way = 'd'
	elif isinstance(obj, Comment):
		share.way = 'c'
		share.comment_object = obj.content_object
		if isinstance(obj.content_object, Link):
			d.way = WAY_LINK_COMMENT_SHARE
			d.comment_object = obj.content_object
		elif isinstance(obj.content_object, Discuss):
			d.way = WAY_DISCUSS_COMMENT_SHARE
			d.comment_object = obj.content_object
		else:
			return False
	else:
		return False
	
	d.save()
	
	obj.n_share += 1
	obj.save()
	
	UserData.objects.filter(user=user).update(n_shares=F('n_shares') + 1)
	
	share.save()
	
	return share
Exemplo n.º 22
0
def download_shared():
    from config import shared_path
    from flask import make_response
    from collections import OrderedDict
    import unicodedata
    from werkzeug.urls import url_quote

    form = EnsureForm()
    fid = form.fid.data
    nonce = form.nonce.data
    sharekey = form.sharekey.data
    f = Share.get_by(fid=fid, nonce=nonce)
    if f is None:
        return 404
    else:
        # 验证分享码是否正确
        sharekey = bytes.fromhex(sharekey)
        saved = f.sharekey
        success = argon2.verify(sharekey, saved)
        if not success:
            flash('分享码不正确!')
            return redirect('/msg_box')
        # 用分享码解密获得对称密钥
        enc_key = f.enc_key
        sym_key = secret.symmetric_decrypt(sharekey, enc_key)
        f = File.get_by(fileid=fid)
        uid = f.uid
        hash_value = f.sha256
        PublicKey = User.get_by(usrid=uid).pubkey
        # 对称解密
        path = shared_path + str(uid) + '/' + hash_value
        with open(path, 'rb') as f_:
            content = f_.read()
            decrypted_content = secret.symmetric_decrypt(sym_key, content)
        response = make_response(decrypted_content)
        filename = f.filename
        filenames = OrderedDict()
        try:
            filename = filename.encode('latin-1')
        except UnicodeEncodeError:
            filenames['filename'] = unicodedata.normalize('NFKD', filename).encode('latin-1', 'ignore')
            filenames['filename*']:"UTF-8''{}".format(url_quote(filename))
        else:
            filenames['filename'] = filename
        response.headers.set('Content-Disposition', 'attachment', **filenames)
        return response
Exemplo n.º 23
0
def list_directory(request,share,subdir=None):
    if not share.check_path():
        return render(request,'index.html', {"message": "Unable to locate the files for this share.  Please contact the site administrator."})
    from os import listdir, stat
    from os.path import isfile, join, getsize, normpath
    import time, datetime
    PATH = share.get_path()
    subshare = None
    if subdir is not None:
        PATH = join(PATH,subdir)
        subshare = Share.objects.filter(parent=share,sub_directory=subdir).first()
    share_perms = share.get_user_permissions(request.user)
    if not share.secure:
        share_perms = list(set(share_perms+['view_share_files','download_share_files']))
    file_list=[]
    directories={}
    regex = r'^%s[^/]+/?' % '' if subdir is None else normpath(subdir)+'/'
    metadatas = {}
    for md in MetaData.objects.filter(share=share,subpath__regex=regex):
        metadatas[md.subpath]= md if not request.is_ajax() else md.json()    
    for name in listdir(PATH):
        path = join(PATH,name)
        subpath= name if subdir is None else join(subdir,name)
#         metadata = MetaData.get_or_none(share=share,subpath=subpath)
        metadata = metadatas[subpath] if metadatas.has_key(subpath) else {}
        if isfile(path):
            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = stat(path)
            file={'name':name,'extension':name.split('.').pop() if '.' in name else None,'size':sizeof_fmt(size),'bytes':size,'modified':datetime.datetime.fromtimestamp(mtime).strftime("%m/%d/%Y %I:%M %p"),'metadata':metadata,'isText':istext(path)}
            file_list.append(file)
        else:
            (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = stat(path)
            dir={'name':name,'size':getsize(path),'metadata':metadata,'modified':datetime.datetime.fromtimestamp(mtime).strftime("%m/%d/%Y %I:%M %p")}
            directories[os.path.realpath(path)]=dir
    if request.is_ajax():
        return json_response({'files':file_list,'directories':directories.values()})
    #Find any shares that point at this directory
    print directories.keys()
    for s in Share.user_queryset(request.user).filter(real_path__in=directories.keys()).exclude(id=share.id):
        directories[s.real_path]['share']=s
    
    owner = request.user == share.owner
    all_perms = share.get_permissions(user_specific=True)
    shared_users = all_perms['user_perms'].keys()
    shared_groups = [g['group']['name'] for g in all_perms['group_perms']]
    ftp_user = ShareFTPUser.objects.filter(share=share,user__isnull=True).first() or ShareFTPUser.objects.filter(share=share,user=request.user).first()
    return render(request,'list.html', {"session_cookie":request.COOKIES.get('sessionid'),"files":file_list,"directories":directories.values(),"path":PATH,"share":share,"subshare":subshare,"subdir": subdir,'rsync_url':get_setting('RSYNC_URL',None),'HOST':get_setting('HOST',None),'SFTP_PORT':get_setting('SFTP_PORT',None),"folder_form":FolderForm(),"metadata_form":MetaDataForm(), "rename_form":RenameForm(),"request":request,"owner":owner,"share_perms":share_perms,"all_perms":all_perms,"share_perms_json":json.dumps(share_perms),"shared_users":shared_users,"shared_groups":shared_groups,'ftp_user':ftp_user})
Exemplo n.º 24
0
def submit_code():
    if request.method == 'POST':
        title = request.form.get('title')
        code = request.form.get('code')
        code_id = randint(100000, 99999999)
        find = Share.query.filter_by(code_id=str(code_id)).first()

        while find:
            code_id = randint(100000, 999999)
            find = Share.query.filter_by(code_id=str(code_id)).first()

        new_code = Share(title=title, code=code, code_id=code_id)
        db.session.add(new_code)
        db.session.commit()
        return jsonify(msg=True, code_id=code_id)
    else:
        return redirect(url_for('index'))
Exemplo n.º 25
0
def show_msg_detail():
    from config import domain_name, sy_private_key
    from flask import jsonify
    from models import Share
    import secret, traceback

    try:
        shareid = request.form['sid']
        msgid = request.form['mid']
        share = Share.get_by(id_=shareid)
        Message.set_readed(msgid)
        link = 'http://' + domain_name + '/share/verify?fid=' + str(
            share.fid) + '&nonce=' + share.nonce
        # 使用服务器私钥解密分享码
        sk = secret.decrypt(bytes.fromhex(sy_private_key), share.enc_sharekey)
        return jsonify(link=link, sharekey=sk.hex())
    except Exception as e:
        return e.args
Exemplo n.º 26
0
def add():
    form = AddShareForm()
    if form.validate_on_submit():
        ticker = form.ticker.data
        quantity = form.quantity.data
        dividends = form.dividends.data
        portfolioid = form.portfolioid.data

        if not Share.exists(ticker):

            sharedata = share_data.JSONSharePrice(ticker)
            sharename = sharedata['query']['results']['quote']['Name']

            newshare = Share(ticker=ticker, name=sharename)
            db.session.add(newshare)
           # db.session.commit()

        bm = Userownedshare(user=current_user.username, quantity=quantity, ticker=ticker, dividends=dividends, portfolioid=portfolioid)
        db.session.add(bm)
        db.session.commit()
        flash("Added share '{}'".format(ticker))
        return redirect(url_for('index'))
    return render_template('add.html', form=form, portfolioids = Userownedshare.listportfolios())
Exemplo n.º 27
0
 def success(self, sender, gift, promo_code, sender_phone, sender_email, reciptient_name, recipient_phone):
     share = Share(share_type=branch_io.GIFT, sender=sender.key)
     share.put()
     if 'iOS' in self.request.headers["User-Agent"]:
         user_agent = 'ios'
     elif 'Android' in self.request.headers["User-Agent"]:
         user_agent = 'android'
     else:
         user_agent = 'unknown'
     recipient = {
         'name': reciptient_name,
         'phone': recipient_phone
     }
     url = branch_io.create_url(share.key.id(), branch_io.INVITATION, branch_io.SMS, user_agent, recipient=recipient)
     share.channel_urls = [ChannelUrl(channel=SMS, url=url)]
     share.put()
     gift.share_id = share.key.id()
     gift.put()
     text = u'Вам подарок от %s в приложении %s! Установите его: %s или введите в нем промо-код %s' % \
            (sender_phone, config.APP_NAME, url, promo_code.key.id())
     self.render_json({
         'success': True,
         'sms_text': text
     })
Exemplo n.º 28
0
    def generatetestshare(self,
                          issuerID=None,
                          fullname=None,
                          shortname=None,
                          abbrevname=None,
                          description=None,
                          industrysector=None,
                          currentprice=None,
                          marketcapitalisation=None,
                          sharecount=None,
                          daychangepercent=None,
                          daychangeprice=None,
                          daypricehigh=None,
                          daypricelow=None,
                          dayvolume=None):
        """
        Helper method for creating a test share with specified attributes.
        If a share attribute is not defined, a random value will be generated
        and assigned instead.

        Args:
            All attributes of Share object, all default to none and will
                be generated for the Share unless assigned a value.
        Returns:
            A Share object with the given and generated attributes.

        """
        # Generate values for each attribute if one is not assigned.
        if not issuerID:
            issuerID = ''.join(random.choices(string.ascii_uppercase, k=3))
        if not fullname:
            fullname = ''.join(random.choices(string.ascii_lowercase, k=10))
        if not shortname:
            shortname = ''.join(random.choices(string.ascii_lowercase, k=10))
        if not abbrevname:
            abbrevname = ''.join(random.choices(string.ascii_lowercase, k=10))
        if not description:
            description = ''.join(random.choices(string.ascii_lowercase, k=50))
        if not industrysector:
            industrysector = ''.join(
                random.choices(string.ascii_lowercase, k=10))
        if not currentprice:
            currentprice = round(random.uniform(1.0, 1000.0), 2)
        if not marketcapitalisation:
            marketcapitalisation = random.randint(1000000, 1000000000)
        if not sharecount:
            sharecount = random.randint(1000000, 1000000000)
        if not daychangepercent:
            daychangepercent = round(random.uniform(-1.0, 1.0), 2)
        if not daychangeprice:
            daychangeprice = round(random.uniform(1.0, 100.0), 2)
        if not daypricehigh:
            daypricehigh = round(random.uniform(currentprice, 1000.0), 2)
        if not daypricelow:
            daypricelow = round(random.uniform(1.0, currentprice), 2)
        if not dayvolume:
            dayvolume = random.randint(1000, 10000000)
        # Create share
        share = Share(issuerID=issuerID,
                      fullname=fullname,
                      abbrevname=abbrevname,
                      shortname=shortname,
                      description=description,
                      industrysector=industrysector,
                      currentprice=currentprice,
                      marketcapitalisation=marketcapitalisation,
                      sharecount=sharecount,
                      daychangepercent=daychangepercent,
                      daychangeprice=daychangeprice,
                      daypricehigh=daypricehigh,
                      daypricelow=daypricelow,
                      dayvolume=dayvolume)
        # Return generated share
        return share
Exemplo n.º 29
0
def repost_fam(content,author,poet):
    """Repost an api quote"""
    quote = Quote.handle_api_quote(content=content,author=author)
    share = Share(poet_id=poet.id, quote_id=quote.id,is_user_quote=False)
    db.session.add(share)
    db.session.commit()
Exemplo n.º 30
0
def repost_user(quote_id,poet_id):
    """Repost a user quote"""
    share = Share(poet_id=poet.id, quote_id=quote_id, is_user_quote=True)
    db.session.add(share)
    db.session.commit()
Exemplo n.º 31
0
def has_write_permission(myuser_key, parent):
    query = Share.ancestor_query().filter(Share.user == myuser_key)
    share = query.filter(Share.folder == parent.key).get()
    return share.permission == 'rw'
Exemplo n.º 32
0
def share(request):
    """
    点击分享,分享包括代码,当前结果(指数,图表), ajax方法,成功后返回生成的唯一url
    :param request:
        strategy_id   策略id
        svg_content   svg dom元素 <svg>...</svg>
        result_params  table dom元素 <table>...</table>
        title   分享帖子的标题
        comment_content   分享帖子的content
    :return:
    """
    if request.method == 'POST':
        account_info = request.session.get('account')
        account = Account.objects.get(id=account_info['id'])

        strategy_id = request.POST.get("strategy_id")
        strategy = Strategy.objects.get(id=strategy_id)

        #生成唯一url
        # /share/<identifier>
        # identifier由account id strategy id time hash 成
        date = datetime.now()

        share_code = md5('_'.join([
            str(account_info['id']), strategy_id,
            date.strftime("%Y%m%d%H%M%S")
        ])).hexdigest()
        result_params = request.POST.get('result_params')
        svg_content = request.POST.get('svg_content')

        #保存分享时代码
        share_code_path = store_share_code(account_info['id'], strategy_id,
                                           strategy.file_path, share_code)

        if share_code_path is None:
            return HttpResponse(
                json.dumps({
                    'status': 'error',
                    'data': u'分享失败'
                }))

        share = Share(account_id=account,
                      strategy_id=strategy,
                      url=share_code,
                      date=date,
                      share_code_path=share_code_path,
                      result_params=result_params,
                      svg_content=svg_content)

        try:
            share.save()

            #分享链接成功后调接口发帖
            title = request.POST.get('title', u'策略分享')
            comment_content = request.POST.get('comment_content', '')

            content = concat_comment(
                comment_content, {
                    'code': get_share_code(share_code_path),
                    'result_params': result_params,
                    'svg_content': svg_content
                })

            comment_id, flag = post_comment(account_id=account_info['id'],
                                            title=title,
                                            content=content)
            if not flag:
                return HttpResponse(
                    json.dumps({
                        'status': 'error',
                        'data': '分享链接失败'
                    }))
            return HttpResponse(
                json.dumps({
                    'status': 'ok',  #TODO
                    'data': u'分享成功,快去社区看看吧'
                }))
        except Exception, e:
            social_log.error("==========Social Error", e)
            return HttpResponse(
                json.dumps({
                    'status': 'error',
                    'data': u'生成分享链接失败'
                }))