Ejemplo n.º 1
0
def index(request):
    """
    Generate the front page of spamlibs. This shows the 10 most recent spam
    email messages, and allows users to seed and view them.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    limit = 10

    qry = Email.all().order('-date')
    recent_spams = qry.fetch(limit)

    count = qry.count(limit=limit + 1)

    qry = Email.all().order('-views')
    viewed_spams = qry.fetch(limit)

    qry = Email.all().order('-rating')
    popular_spams = qry.fetch(limit)

    ctx = RequestContext(
        request, {
            'recent_spams': recent_spams,
            'viewed_spams': viewed_spams,
            'popular_spams': popular_spams,
            'more': count == limit + 1
        })

    return render_to_response('index.html', context_instance=ctx)
Ejemplo n.º 2
0
def index(request):
    """
    Generate the front page of spamlibs. This shows the 10 most recent spam
    email messages, and allows users to seed and view them.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    limit = 10
    
    qry = Email.all().order('-date')
    recent_spams = qry.fetch(limit)
    
    count = qry.count(limit=limit+1)
    
    qry = Email.all().order('-views')
    viewed_spams = qry.fetch(limit)
    
    qry = Email.all().order('-rating')
    popular_spams = qry.fetch(limit)
    
    ctx = RequestContext(request, {
        'recent_spams':recent_spams,
        'viewed_spams':viewed_spams,
        'popular_spams':popular_spams,
        'more':count==limit+1
    })    
    
    return render_to_response('index.html', context_instance=ctx)
Ejemplo n.º 3
0
def list(request, page):
    """
    List all the spams in the system, using a paging output.
    
    :param HttpRequest request: A web request.
    :param integer page: The page to view.
    :rtype: An HttpResponse object.
    """
    pagesize = 10
    maxfwd = pagesize * 5 + 1

    order = 'date'
    if 'order' in request.GET:
        tmpo = request.GET['order']
        if tmpo[0] == '-':
            tmpo = tmpo[1:]
        if tmpo in Email.properties():
            order = request.GET['order']

    page = int(page)

    qry = Email.all().order(order)
    nspams = qry.count(offset=(page - 1) * pagesize, limit=maxfwd)
    spams = qry.fetch(pagesize, offset=(page - 1) * pagesize)

    ctx = RequestContext(
        request, {
            'spams': spams,
            'count': maxfwd,
            'pager': _pager(page, (page - 1) * pagesize + nspams, 10),
            'order': order,
            'page': page
        })

    return render_to_response('list.html', context_instance=ctx)
Ejemplo n.º 4
0
def list(request, page):
    """
    List all the spams in the system, using a paging output.
    
    :param HttpRequest request: A web request.
    :param integer page: The page to view.
    :rtype: An HttpResponse object.
    """
    pagesize = 10
    maxfwd = pagesize * 5 + 1
    
    order = 'date'
    if 'order' in request.GET:
        tmpo = request.GET['order']
        if tmpo[0] == '-':
            tmpo = tmpo[1:]
        if tmpo in Email.properties():
            order = request.GET['order']
    
    page = int(page)
        
    qry = Email.all().order(order)
    nspams = qry.count(offset=(page-1)*pagesize, limit=maxfwd)
    spams = qry.fetch(pagesize, offset=(page-1)*pagesize)
    
    ctx = RequestContext(request, {
        'spams':spams,
        'count':maxfwd,
        'pager':_pager(page, (page-1)*pagesize + nspams, 10),
        'order':order,
        'page':page
    })
    
    return render_to_response('list.html', context_instance=ctx)
Ejemplo n.º 5
0
 def find_existing(cls, email):
     hash = hashlib.md5(email).hexdigest()
     found = Account.all().filter("hash =", hash).get()
     if not found:
         found = Account.all().filter("hashes =", hash).get()
     if not found:
         found = Email.all().filter("email =", email).get()
     return found
Ejemplo n.º 6
0
 def find_existing(cls, email):
     hash = hashlib.md5(email).hexdigest()
     found = Account.all().filter('hash =', hash).get()
     if not found:
         found = Account.all().filter('hashes =', hash).get()
     if not found:
         found = Email.all().filter('email =', email).get()
     return found
Ejemplo n.º 7
0
    def post(self):
        user = users.get_current_user()
        if user:
            # find if we're already bound to an email
            email_query = Email.all()
            email_query.filter("user ="******"Notice", "Already bound to an email")
                self.redirect("/")
                return
            # handle the email input
            email_addr = normalize_email(self.request.get("email"))
            if not(email_addr):
                add_notify("Notice", "Not a correct UNI format")
                self.redirect("/")
                return
            # find the email by the email address
            email_key = generate_hash(email_addr)[:10]
            email, made = get_or_make(Email, email_key)
            if not(email.email):
                email.id = email_key
                email.email = email_addr
                email.put()
            # user already tied, don't allow transfers through this interface
            if email.user_enable:
                add_notify("Notice", "User is already enabled")
                self.redirect("/")
                return
            if not(email.user):
                email.user = user
            # generate a new key
            email.user_request_key = generate_random_hash(str(email))
            email.user_request_time = datetime.today()
            email.put()

            # send a verification email
            domain = "http://%s.appspot.com" % get_application_id()
            verify_addr = domain + "/link/email/%s" % email.user_request_key
            msg = mail.EmailMessage()
            fromaddr = "noreply@%s.appspotmail.com" % get_application_id()
            msg.sender  = "Flyer Guy <%s>" % fromaddr
            msg.to      = email.email
            msg.subject = "[Flyer] Verify your email address"
            msg.html    = template.render("templates/email_verify.html",
                                          {'verify_addr':verify_addr})
            try:
                msg.send()
            except apiproxy_errors.OverQuotaError, (message,):
                # Log the error
                add_notify("Error", "Could not send email")
                logging.error("Could not send email")
                logging.error(message)
            self.redirect("/")
Ejemplo n.º 8
0
 def sendnext(self):
     query = Email.all()
     query.filter("emailupdated = ", False)
     p = None
     for p in query.run(limit=1):
         senderemailid = str(p.senderemailid)
         receiveremailid = str(p.receiveremailid)
         subject = str(p.subject)
         body = str(p.body)
         filename = str(p.filename)
         attachment = None
         # if filename:
         # 	googledriveservice = GoogleDriveService()
         # 	fileresource = googledriveservice.getfile(filename)
         # 	if fileresource:
         # 		filecontents = googledriveservice.getfilecontents(fileresource, constants.GOOGLE_DRIVE_EMAIL_ATTACHMENT_PDF_CONTENT_TYPE)
         # 		filetitle = googledriveservice.getfiletitle(fileresource)
         # 		fileroot, ext = os.path.splitext(filetitle)
         # 		filetitle = fileroot + '.pdf'
         # 		if filecontents:
         # 			attachment = mail.Attachment(filetitle, filecontents)
         try:
             message = mail.EmailMessage(sender=senderemailid,
                                         subject=subject)
             message.to = receiveremailid
             message.html = body
             if attachment:
                 message.attachments = [attachment]
             message.send()
             logging.info('sent email senderemailid=' + str(senderemailid) \
              + ', toaddress=' + str(receiveremailid) \
              + ', with subject=' + str(subject))
         except:
             logging.error('error sending email to ' + str(receiveremailid))
             sys_err = sys.exc_info()
             logging.error(sys_err[1])
         try:
             p.emailupdated = True
             p.put()
         except:
             logging.error('error updating Email.emailupdated ' +
                           str(receiveremailid))
             sys_err = sys.exc_info()
             logging.error(sys_err[1])
     return 0
Ejemplo n.º 9
0
 def get(self, token):
     # find the email with the token
     email_query = Email.all()
     email_query.filter("user_request_key =", token)
     email = email_query.get()
     # no email, die
     if not(email):
         self.error(404)
     # check the date, if it's late wipe it
     if datetime.today() - email.user_request_time > timedelta(days=2):
         email.user = None
         email.user_request_key = None
         email.user_request_time = None
         email.put()
         self.error(404)
     # enable
     email.user_enable = True
     email.user_request_key = None
     email.user_request_time = None
     email.put()
     add_notify("Notice", "Emails linked!")
     self.redirect("/")
Ejemplo n.º 10
0
 def post(self):
     # check there's someone signed in
     user = users.get_current_user()
     if not(user):
         add_notify("Error", "You do not have the appropriate permissions")
         self.redirect("/")
         return
     # get associated email
     email_query = Email.all()
     email_query.filter("user = "******"Error", "You do not have the appropriate permissions")
         self.redirect("/")
         return
     # basic sanity check
     clubname = self.request.get("name")
     if not(clubname):
         add_notify("Error", "Please enter a club name")
         self.redirect("/")
         return
     # convert to slug
     clubslug = slugify(clubname)
     # basics of get_or_insert, with insertion
     club, made = get_or_make(Club, clubslug)
     if not(made):
         # generate an error
         add_notify("Error", "That particular club name is taken. Sorry!")
         self.redirect("/")
         return
     # make a club, add current user as an admin
     club.name = clubname
     club.slug = clubslug
     club.put()
     join = EmailToClub(email=email, club=club, admin=True)
     join.put()
     club_url = "/club/%s" % clubslug
     self.redirect(club_url)
Ejemplo n.º 11
0
    def get(self):
        user = users.get_current_user()
        if user:
            email_query = Email.all()
            email_query.filter('user = '******'re not already linked...
            if not(email):
                # display the email-linking page
                self.response.out.write(template.render(
                        "templates/user_link.html", {}))
                return
            # !!! remove this eventually?
            if DEBUG:
                email.user_enable = True
                email.put()
            if not(email.user_enable):
                values = {}
                if email.email:
                    values['email'] = email.email
                # handle notifications
                session = get_current_session()
                if session:
                    values['notifications'] = session.get("notify", None)
                    session["notify"] = None
                # display the email-linking page
                self.response.out.write(template.render(
                        "templates/user_link.html", values))
                return

            # otherwise, serve up the listing page
            clubrefs = email.clubs.fetch(20) # 20 chosen arbitrarily
            clubs = [c.club
                     for c in prefetch_refprop(clubrefs, EmailToClub.club)
                     if check_admin(c.club.slug)]
            club_hash = []
            for c in clubs:
                query = c.flyer_set
                query.filter("active =", True)
                flyer_objs = query.fetch(10)
                # and go fetch all the jobs
                flyers = [{"id": f.id,
                           "name": f.name,
                           "date": f.event_date,
                           "jobs": [j for j in f.jobs if j.active],
                           "dl_jobs": [j for j in f.jobs
                                       if j.active and j.state==DOWNLOADED],
                           "done_jobs": [j for j in f.jobs
                                         if j.active and j.state==DONE]}
                          for f in flyer_objs]
                club_hash.append({"name": c.name, "slug": c.slug,
                                  "flyers": flyers})
            values = {"clubs": club_hash}
            # try getting notifications
            session = get_current_session()
            if session:
                values['notifications'] = session.get("notify", None)
                session["notify"] = None
            self.response.out.write(template.render("templates/orgs.html",
                                                    values))            
        else:
            # otherwise, just display the frontpage
            admin_contact = "support@%s.appspotmail.com" % get_application_id()
            values = {"affiliation": AFFILIATION,
                      "contact_info": admin_contact,
                      "login_url": users.create_login_url(self.request.uri)}
            self.response.out.write(template.render("templates/index.html",
                                                    values))
Ejemplo n.º 12
0
def get_email(user):
    """Get email object associated with user"""
    email_query = Email.all()
    email_query.filter("user = ", user)
    return email_query.get()
Ejemplo n.º 13
0
    def get(self):
        timestamp = time.mktime(datetime.now().timetuple())-24*3600
        yesterday = datetime.fromtimestamp(timestamp)
        # count how many flyers are going out
        current_date = datetime.now(CurrentTimeZone())
        day = current_date.weekday() # starts 0=monday... 6=sunday
        if day < 5:
            job_query = Job.all()
            job_query.filter("active =", True)
            job_query.filter("state !=", DONE)
            flyer_count = job_query.count()
        else:
            flyer_count = 0
        # get new clubs
        club_query = Club.all()
        club_query.filter("created_at >", yesterday)
        new_clubs = club_query.fetch(20)
        # get new emails
        email_query = Email.all()
        email_query.filter("created_at >", yesterday)
        new_emails = email_query.fetch(100)
        # get new flyers
        flyer_query = Flyer.all()
        flyer_query.filter("created_at >", yesterday)
        new_flyers = flyer_query.fetch(50)
        # get new EmailToClub
        joint_query = EmailToClub.all()
        joint_query.filter("created_at >", yesterday)
        new_joints = joint_query.fetch(100)
        # and get the newly disabled links
        joint_query = EmailToClub.all()
        joint_query.filter("updated_at >", yesterday)
        joint_query.filter("enable =", False)
        dead_joints = joint_query.fetch(100)

        if (not(new_clubs) and not(new_emails) and not(new_flyers)
            and not(new_joints)):
            self.response.out.write("Nothing to email")
            return

        # email sending pre-computation
        fromaddr = "noreply@%s.appspotmail.com" % get_application_id()
        date = time.strftime("%Y/%m/%d")

        # send the emails
        msg = mail.EmailMessage(sender = "Flyer Guy <%s>" % fromaddr,
                                to = ADMIN_EMAIL)
        msg.subject = "[Flyer] Admin stats (%s)" % date
        msg.html    = template.render("templates/email_stats.html",
                                      {"flyer_count": flyer_count,
                                       "clubs": new_clubs,
                                       "emails": new_emails,
                                       "flyers": new_flyers,
                                       "joints": new_joints,
                                       "dead_joints": dead_joints})
        try:
            msg.send()
        except apiproxy_errors.OverQuotaError, (message,):
            # Log the error.
            logging.error("Could not send email")
            logging.error(message)