Esempio n. 1
0
def share(file_id):  #assuming file_id is given
    file = Files.query.filter_by(id=file_id).first()
    # form = dict()
    # form['recipient_email'] = []
    # form['body'] = request.form['message']
    # form['subject'] = request.form['subject']
    # t = request.form['email'].replace(' ','')
    # form['recipient_email'] = t.split(',')
    # print(form)
    # mail_func(form,file.data)
    form_data = ShareForm()
    if form_data.validate_on_submit():
        form = dict()
        form['recipient_email'] = []
        form['body'] = form_data.message.data
        form['subject'] = form_data.subject.data
        t1 = form_data.email.data
        t = t1.replace(' ', '')
        form['recipient_email'] = t.split(',')
        for emailid in form['recipient_email']:
            user = User.query.filter_by(email=emailid).first()
            print(type(user))
            if user is not None:
                file.mapping.append(user)
                db.session.commit()
        print(form)
        mail_func(form, file.data)
        return redirect(url_for('login'))

    return render_template('share.html',
                           title='SHARE',
                           current_user=current_user,
                           data=getdata(current_user.user_id),
                           form_data=form_data)
Esempio n. 2
0
def share(file_id):  # assuming file_id is given
    file = Files.query.filter_by(id=file_id).first()
    form_data = ShareForm()
    if form_data.validate_on_submit():
        form = dict()
        form['recipient_email'] = []
        form['body'] = form_data.message.data
        form['subject'] = form_data.subject.data
        t1 = form_data.email.data
        t = t1.replace(' ', '')
        form['recipient_email'] = t.split(',')
        for emailid in form['recipient_email']:
            user = User.query.filter_by(email=emailid).first()
            print(type(user))
            if user is not None:
                file.mapping.append(user)
                db.session.commit()

        credentials = google.oauth2.credentials.Credentials(
            **flask.session['credentials'])
        service = build('gmail', 'v1', credentials=credentials)
        sendInst = send_email.send_email(service)
        message = sendInst.create_message_with_attachment(form, file.data)
        print(sendInst.send_message('me', message))
        return redirect(url_for('account'))
    return render_template('share.html',
                           title='SHARE',
                           current_user=current_user,
                           data=getdata(current_user.user_id),
                           form_data=form_data)
Esempio n. 3
0
def share(request, slug):
    """
    Share view.
    Allows readers to send a link to a text by Email.
    """
    text = Text.objects.get(identifier=slug)
    
    if request.method == 'POST': # If the form has been submitted...
        form = ShareForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            name      = form.cleaned_data['name']
            sender    = form.cleaned_data['sender']
            to        = form.cleaned_data['to']
            cc_myself = form.cleaned_data['cc_myself']
            
            recipients = [to]
            if cc_myself:
                recipients.append(sender)
            
            subject = u"%s wants to share a text with you from nY" % name
            
            message = u"""
                %s would like to share with you the following text:
            """ % (name)
            
            #from django.core.mail import send_mail
            from django.core.mail import EmailMultiAlternatives
            #send_mail(subject, message, sender, recipients)
            html_content = u'''
                <a style='font-family: "American Typewriter", "Courier New"; font-weight: bold; color: black; font-size: 11em; line-height:0.8em; text-decoration: none;' href='http://test.ny-web.be/'>nY</a>
                <div style="font-family: Georgia; margin-top: 8px; margin-bottom: 20px; width:500px;">
                    <span style="font-weight: bold;">website en tijdschrift voor literatuur, kritiek &amp; amusement, <br />
                    voorheen</span> <span style="font-style: italic;">yang &amp; freespace Nieuwzuid</span>                                
                </div>
                
                <p style="font-family: Georgia; font-size: 14px;">%s would like to share with you the following text: <a href="%s">%s</a>.</p>
            ''' % (name, 'http://test.ny-web.be' + text.get_absolute_url(), text)

            msg = EmailMultiAlternatives(subject, message, sender, recipients)
            msg.attach_alternative(html_content, "text/html")
            msg.content_subtype = "html"
            msg.send()
            
            back2text = """
                        <p><a href='%s'>Return to the text.</a></p>
                        """ % text.get_absolute_url()
            
            return HttpResponse(html_content + back2text )
            # return HttpResponseRedirect('/share/thanks/') # Redirect after POST
    else:
        form = ShareForm() # An unbound form

    return render_to_response('share/share.html', {
        'form': form,
        'text': text,
        'MEDIA_URL': settings.MEDIA_URL,
    }, context_instance=RequestContext(request))
Esempio n. 4
0
def add():
    form = ShareForm()
    if form.validate_on_submit():
        ticker = form.ticker.data
        quantity = form.quantity.data
        dividends = form.dividends.data
        bm = Userownedshare(user=current_user.username, quantity=quantity, ticker=ticker, dividends=dividends)
        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())
Esempio n. 5
0
def sharesetup(user):
    form = ShareForm()
    if request.form.get('bar', None) == 'Share/Unshare':
    	if form.validate_on_submit():
    	    shareuser = form.shareuser.data
	    if shareuser != user.nickname:
    	    	sharepath = settings.WORKING_DIR + shareuser
	    	shareuserdb = User.query.filter_by(nickname=shareuser).first()
    	    	sharedname = user.nickname + "Repo"
    
    	    	currentRepo = shareuserdb.repos.filter_by(repourl="/" + sharedname + "/").first()
    	    	if currentRepo is None:
	    	    existing = False
    	    	    for sub in os.listdir(sharepath):
	                if sub == sharedname:
	    	    	    existing = True
    	    	    if not existing:
	    	        repo = Repo(settings.REMOTE_DIR + user.nickname)
	    	        os.system("sudo mkdir " + sharepath + "/" + sharedname)
		        working_repo = repo.clone(sharepath + "/" + sharedname , False, False, "origin")
            	        p = subprocess.Popen(["sudo", "git", "remote", "add", "origin", "file:///" + settings.REMOTE_DIR + user.nickname + "/"], cwd=sharepath + "/" + sharedname)
	    	        p.wait()
	    	    newrepo = Rpstry(repourl="/" + sharedname + "/", owner=shareuserdb)
            	    db.session.add(newrepo)
            	    db.session.commit()

	    	    password = ''
	    	    searchfile = open(settings.REMOTE_DIR + shareuser + "/.htpasswd", "r")
	    	    for line in searchfile:
		        exactuser = re.compile("^" + shareuser + ":(.)*$")
                        if exactuser.match(line):
   	            	    password = line
	            searchfile.close()
                    open(settings.REMOTE_DIR + user.nickname + "/.htpasswd", 'a').writelines(password)
                    flash("Shared with: " + shareuser, 'info')
	        else:
	    	    searchfile = open(settings.REMOTE_DIR + user.nickname + "/.htpasswd", "r")
	    	    lines = searchfile.readlines()
	    	    searchfile.close()
	    	    f = open(settings.REMOTE_DIR + user.nickname + "/.htpasswd","w")
	    	    for line in lines:
		        exactuser = re.compile("^" + shareuser + ":(.)*$")
		        if not exactuser.match(line):
		    	    f.write(line)
	            f.close()
	            db.session.delete(currentRepo)
	            db.session.commit()
		    flash("Unshared with: " + shareuser, 'info')
        else:
	    flash("User does not exist", 'error')
    return form
Esempio n. 6
0
def edit_share(request,share):
    if share.owner != request.user and not request.user.is_superuser:
        return HttpResponseForbidden('Only share owners or admins may edit a share')
    if request.method == 'POST':
        form = ShareForm(request.user,request.POST,instance=share)
        if form.is_valid():
            share = form.save(commit=False)
            share.set_tags(form.cleaned_data['tags'].split(','))
            return HttpResponseRedirect(reverse('list_directory',kwargs={'share':share.slug_or_id}))
    else:
        tags = ','.join([tag.name for tag in share.tags.all()])
        form = ShareForm(request.user,instance=share)
        form.fields['tags'].initial = tags
    return render(request, 'share/edit_share.html', {'form': form})
Esempio n. 7
0
def create_share(request):
    if not request.user.has_perm('bioshareX.add_share'):
        return render(request,'index.html', {"message": "You must have permissions to create a Share.  You may request access from the <a href=\"mailto:[email protected]\">webmaster</a>."})
    if request.method == 'POST':
        form = ShareForm(request.user,request.POST)
        if form.is_valid():
            share = form.save(commit=False)
            share.owner=request.user
            try:
                share.save()
                share.set_tags(form.cleaned_data['tags'].split(','))
            except Exception, e:
                share.delete()
                return render(request, 'share/new_share.html', {'form': form, 'error':e.message})
            return HttpResponseRedirect(reverse('list_directory',kwargs={'share':share.slug_or_id}))
Esempio n. 8
0
def wishlist(userid):
    # file_folder = app.config['UPLOAD_FOLDER']
    form = NewItemForm()
    form2 = ShareForm()
    form3 = LoginForm()

    if request.method == "POST":
        if form.validate_on_submit():
            # generate item id
            id = str(uuid.uuid4().fields[-1])[:8]

            # get data from form
            title = form.title.data
            description = form.description.data
            webaddress = form.webaddress.data
            thumbnail = request.form['thumbnail']

            # retrieve item from database
            item = WishlistItem.query.filter_by(
                title=title, owner=current_user.get_id()).first()

            # if the item already exists then flash error message and redirect back to the wishlist page
            if item is not None:
                flash('' + title + ' already exists in your wishlist',
                      'danger')
                return redirect(
                    url_for('wishlist', userid=current_user.get_id()))

            # create wishlist object
            item = WishlistItem(id=id,
                                owner=current_user.get_id(),
                                title=title,
                                description=description,
                                webaddress=webaddress,
                                thumbnail=thumbnail)

            # insert item into WishlistItem
            db.session.add(item)
            db.session.commit()

            flash('' + title + ' was added to your wishlist', 'success')

            # redirect user to their wishlist page
            return redirect(url_for("wishlist", userid=current_user.get_id()))
        else:
            # flash message for failed item addition
            flash('Invalid item data, please try again', 'danger')

            # redirect user to their wishlist page
            return redirect(url_for("wishlist", userid=current_user.get_id()))
    else:
        # retrieve user wishlist items from database
        items = WishlistItem.query.filter_by(owner=current_user.get_id()).all()
    return render_template("wishlist.html",
                           userid=current_user.get_id(),
                           form=form,
                           form2=form2,
                           form3=form3,
                           items=items)
Esempio n. 9
0
def add_ad(request):
    """
    >>> a = 'a'
    >>> a
    a
    """
    if request.method == "POST":
        form = ShareForm(request.POST, request.FILES)
        if form.is_valid():
            new_ad = form.save(commit=False)
            new_ad.user = request.user.profile
            new_ad.status = "A"
            new_ad.save()
            return HttpResponseRedirect("/ads/")
    else:
        form = ShareForm()
    return render_to_response("share/add_ad.html", {"form": form}, context_instance=RequestContext(request))
Esempio n. 10
0
def sharewishlist(userid):
    import smtplib
    form = ShareForm()
    form2 = LoginForm()

    if request.method == "POST":
        if form.validate_on_submit() and form2.validate_on_submit():
            from_addr = current_user.email
            to_addr = form.recipientemail.data
            from_name = current_user.first_name + ' ' + current_user.last_name
            to_name = form.name.data
            subject = 'My Wishlist!'
            message = """
            From: {} <{}>
            To: {} <{}>
            Subject: {}

            {}
            """
            # gets item form database
            items = WishlistItem.query.filter_by(
                owner=current_user.get_id()).all()

            message_body = 'This is my wishlist'
            for item in items:
                message_body += "\n-->" + item.title

            message_to_send = message.format(from_name, from_addr, to_name,
                                             to_addr, subject, message_body)
            # Credentials (if needed)
            username = form2.email.data
            password = form2.password.data

            # The actual mail send
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(username, password)
            server.sendmail(from_addr, to_addr, message_to_send)
            server.quit()

            flash('Wishlist was Shared to ' + to_name, 'success')
        else:
            flash('Invalid sharing data, please try again', 'danger')
        return redirect(url_for("wishlist", userid=current_user.get_id()))
    return redirect(url_for("wishlist", userid=current_user.get_id()))
Esempio n. 11
0
def create_share(request,group_id=None):
    if not request.user.has_perm('bioshareX.add_share'):
        return render(request,'index.html', {"message": "You must have permissions to create a Share.  You may request access from the <a href=\"mailto:[email protected]\">webmaster</a>."})
    group = None if not group_id else Group.objects.get(id=group_id)
    if request.method == 'POST':
        form = ShareForm(request.user,request.POST)
        if form.is_valid():
            share = form.save(commit=False)
            if not getattr(share, 'owner',None):
                share.owner=request.user
            try:
                share.save()
                share.set_tags(form.cleaned_data['tags'].split(','))
            except Exception, e:
                share.delete()
                return render(request, 'share/new_share.html', {'form': form,'group':group, 'error':e.message})
            if group:
                assign_perm(Share.PERMISSION_VIEW,group,share)
                assign_perm(Share.PERMISSION_DOWNLOAD,group,share)
            return HttpResponseRedirect(reverse('list_directory',kwargs={'share':share.slug_or_id}))
Esempio n. 12
0
def edit_share(request,share):
    if share.owner != request.user and not request.user.is_superuser:
        return HttpResponseForbidden('Only share owners or admins may edit a share')
    if request.method == 'POST':
        form = ShareForm(request.user,request.POST,instance=share)
        if form.is_valid():
            share = form.save(commit=False)
            share.set_tags(form.cleaned_data['tags'].split(','))
            return HttpResponseRedirect(reverse('list_directory',kwargs={'share':share.slug_or_id}))
    else:
        tags = ','.join([tag.name for tag in share.tags.all()])
        form = ShareForm(request.user,instance=share)
        form.fields['tags'].initial = tags
    return render(request, 'share/edit_share.html', {'form': form})
Esempio n. 13
0
def edit_ad(request, pk):
    ad = Share.objects.get(pk=pk)
    if request.method == 'POST':
        form = ShareForm(request.POST, request.FILES, instance = ad)
        if form.is_valid():
            form.save()               
            user = Userprofile.objects.get(user = request.user)
            user_adds = user.share_set.all()
            return render_to_response('userprofile/index.html', 
                             {'user' : user,
                              'user_adds': user_adds,
                              },
                             context_instance=RequestContext(request))
    else:
        form = ShareForm(instance = ad)
    return render_to_response(
        'share/add_ad.html',
        {'form': form}, 
        context_instance=RequestContext(request)
    )
Esempio n. 14
0
def add_ad(request):
    """
    >>> a = 'a'
    >>> a
    a
    """
    if request.method == 'POST':
        form = ShareForm(request.POST, request.FILES)
        if form.is_valid():
            new_ad = form.save(commit=False)
            new_ad.user = request.user.profile
            new_ad.status = 'A'
            new_ad.save()
            return HttpResponseRedirect('/ads/')
    else:
        form = ShareForm()
    return render_to_response('share/add_ad.html', {'form': form},
                              context_instance=RequestContext(request))
Esempio n. 15
0
def share(request):
	response = HttpResponse()
	user = request.user
	#User's manually saved tabs.
	try:
		#first of all, try to fetch the user's manually synced tabs.
		synced = Sync.objects.filter(user=user)
		#print "Synced = " + str(len(synced))
		if not synced:					#If it doesn't filter anything
			synced = None
	except Sync.DoesNotExist:				#If this user hasn't synced anything yet.
		synced = None
	#Get user's all devices:
	try:
		users_devices = UsersDevice.objects.filter(user=user)
		#print "Users device = " + str(len(users_devices))
		if not users_devices:
			users_devices = None
	except UsersDevice.DoesNotExist:
		users_devices = None
	
	#User's all synced bookmarks from all devices
	try:
		synced_bookmarks = Bookmark.objects.filter(owner=user)
		#print "Synced bookmarks = " + str(len(synced_bookmarks))
		if not synced_bookmarks:
			synced_bookmarks = None
	except Bookmarks.DoesNotExist:
		synced_bookmarks = None
	#User's all synced history from all devices.
	try:
		synced_history = History.objects.filter(owner=user)
		#print "Synced history = " + str(len(synced_history))
		if not synced_history:
			synced_history = None
	except History.DoesNotExist:
		synced_history = None
	#User's all synced tabs from all devices	
	try:
		synced_tabs = Tab.objects.filter(owner=user)
		#print "Synced tabs = " + str(synced_tabs.count())
		if not synced_tabs:
			synced_tabs = None
	except Tab.DoesNotExist:
		synced_tabs = None		
	try:
		#Now just try to see if this user belongs to any group.
		ug = UserGroup.objects.get(user=user)	
		groups = ug.groups.all()			#ManyToManyField groups.
		##print groups
		for g in groups:				#Iterate every group
			#sharedObjects = g.share_set.all()	#See what this group has shared.
			#print sharedObjects			
			title = ""
			thisGroupsMembers = g.members.all()
			for m in thisGroupsMembers:
				title = title + m.email + "\r\n"
			#print title
	except UserGroup.DoesNotExist:				#If this user hasn't created any group yet
		groups = None
	if (request.method == 'POST'):				#User has sent the form
		form = ShareForm(request.POST, request=request)	#The request object is passed to validate the form
		#print request.POST
		if form.is_valid():				#If the form is valid or not
			cd = form.cleaned_data			#Cleaned data
			#print cd
			toShare = cd['toShare']			#These are the objects that are going to be shared 
			shareBookmarks = cd['shareBookmarks']
			shareHistory = cd['shareHistory']
			shareTabs = cd['shareTabs']
			uid = uuid.uuid4()
			uid = str(uid)
			saveShared = Share(shared_from=user,unique=uid)#Create a new entry for the share
			saveShared.save()
			for checked in toShare:			#Save all the checked objects
				#print checked
				try:
					shared = Sync.objects.get(unique=checked)	#Get it from the synced object and add it
					#check_if_exist(shared,request.user)
					saveShared.shared.add(shared)
				except Sync.DoesNotExist:
					pass
			for checked in shareBookmarks:
				try:
					s_b = Bookmark.objects.get(unique=checked)
					saveShared.shared_bookmarks.add(s_b)
				except Bookmarks.DoesNotExist:
					pass
			for checked in shareHistory:
				try:
					s_h = History.objects.get(unique=checked)
					saveShared.shared_history.add(s_h)
				except History.DoesNotExist:
					pass
			for checked in shareTabs:
				try:
					s_t = Tab.objects.get(unique=checked)
					saveShared.shared_tabs.add(s_t)
				except Tab.DoesNotExist:
					pass
			selectFrom = cd['selectFrom']		#What type of sharing with was selected
			if (selectFrom == '1'):		
				#Share by email address:
				byEmail = cd['friends_email']	#Friends email
				saveShared.typeOf_share = 'email'#Share is by email
				saveShared.save()		
				for u in byEmail:		#Add all those with whom to share
					shareWithUser = User.objects.get(email=u)
					saveShared.shared_with_emails.add(shareWithUser)
			elif (selectFrom == '2'):		
				#Create a group and share:
				byEmail = cd['friends_email']
				group_name = cd['group_name']	
				saveShared.typeOf_share = 'group'
				saveShared.save()
				#Create the group:
				savedGroup = save_group(request.user,group_name,byEmail)	#create the group with the povided friends email addresses
				saveShared.shared_with_group.add(savedGroup)				
			elif (selectFrom == '3'):
				#Share with existing group:
				existingGroups = cd['existingGroups']
				saveShared.typeOf_share = 'group'
				saveShared.save()
				for checked in existingGroups:
					savedGroup = MyGroup.objects.get(unique=checked)
					saveShared.shared_with_group.add(savedGroup)	
			rendered = render(request, 'shareCorrect.html',context_instance = RequestContext(request))			
			return rendered
	else:
		
		# What has this user shared:
		#thisShare = Share.objects.filter(shared_from=request.user)
		form = ShareForm()
		for field in form:
			if (field.name == 'toShare'):
				try:
					if not (synced == None):
						for s in synced:
							aux = (s.unique,s.title)
							field.field.widget.choices.append(aux)
						#print field.field.widget.choices
				except AttributeError:
					pass
			elif (field.name == 'existingGroups'):
				try:
					if not (groups == None):
						for e in groups:
							aux = (e.unique,e.groupName)
							field.field.widget.choices.append(aux)
				except AttributeError:
					pass
			elif (field.name == 'shareBookmarks'):
				try:
					if not (synced_bookmarks == None):
						for b in synced_bookmarks:
							#unique_value = str(b.device.deviceId+str(b.itemId))
							aux = (b.unique,b.title)
							field.field.widget.choices.append(aux)
				
				except AttributeError:
					pass
			elif (field.name == 'shareHistory'):
				try:
					if not (synced_history == None):
						for h in synced_history:
							#unique_value = str(h.device.deviceId+h.url)
							aux = (h.unique,h.title)
							field.field.widget.choices.append(aux)
				
				except AttributeError:
					pass
			
			elif (field.name == 'shareTabs'):
				try:
					if not (synced_tabs == None):
						for t in synced_tabs:
							#unqiue_value = str(t.device.deviceId+t.url)
							aux = (t.unique,t.title)
							field.field.widget.choices.append(aux)
				except AttributeError:
					pass
	if (synced == None and synced_bookmarks == None and synced_tabs == None and synced_history == None):
		rendered = render(request, 'noShare.html',context_instance = RequestContext(request))
	else:
		rendered = render(request, 'share.html', {'form': form,'synced':synced,'groups':groups,'devices':users_devices},context_instance = RequestContext(request))			
	return rendered
Esempio n. 16
0
        if form.is_valid():
            share = form.save(commit=False)
            if not getattr(share, 'owner',None):
                share.owner=request.user
            try:
                share.save()
                share.set_tags(form.cleaned_data['tags'].split(','))
            except Exception, e:
                share.delete()
                return render(request, 'share/new_share.html', {'form': form,'group':group, 'error':e.message})
            if group:
                assign_perm(Share.PERMISSION_VIEW,group,share)
                assign_perm(Share.PERMISSION_DOWNLOAD,group,share)
            return HttpResponseRedirect(reverse('list_directory',kwargs={'share':share.slug_or_id}))
    else:
        form = ShareForm(request.user)
    return render(request, 'share/new_share.html', {'form': form,'group':group})

@safe_path_decorator(path_param='subdir')
@share_access_decorator(['admin'])
def create_subshare(request,share,subdir):
    path = os.path.join(share.get_path(),subdir)
    if not os.path.exists(path):
        return render(request,'index.html', {"message": "Unable to create share.  The specified path does not exist."})
    if request.method == 'POST':
        form = SubShareForm(request.POST)
        if form.is_valid():
            subshare = form.save(commit=False)
            subshare.owner = request.user
            subshare.link_to_path = path
            subshare.sub_directory = subdir