Beispiel #1
0
def invite(request, activity_id):    
    if request.method == 'GET':
        return render_to_response('share/invite.html', { 'id': activity_id,
                                                 'type': 'activity'},
                          context_instance=RequestContext(request))
    user_from = request.user
    activity = Activity.objects.get(pk=activity_id)
    if not (user_from == activity.invitor or (user_from in activity.person_joined() and activity.allow_invitee_invite)):
        return redirect(u'/error?message=您不能邀请其他人加入次活动')
    recipients_list = []
    for key in request.POST.keys():
        if key.startswith('user_') and request.POST[key] == 'on':
            user_id = key[5:]
            user = User.objects.get(pk=user_id)     
            try:           
                invite = Invite.objects.create(user=user, activity=activity, response='U')
                recipients_list.append(invite.user.email)
            except:
                pass
    if request.POST.get('email_notify', default='off') == 'on':
        title = u'来自' + request.user.profile.real_name + u'的邀请'
        invite_url = SITE_URL + 'activity/reply/' + activity_id
        mail_context = u'您的好友' + user_from.profile.real_name + u'邀请您参加' + activity.name + u'请到' + invite_url + u' 查看'
        
        try:
            send_mail(title, mail_context, request.user.email, recipients_list, html=mail_context)
            #return HttpResponse(recipients_list)
        except:
            return HttpResponse('email server error!')
                
    return redirect('/activity/detail/' + activity_id)
Beispiel #2
0
def invite(request, story_id):    
    if request.method == 'GET':
        tabs = {}
        tabs['好友'] = '/story/friend-candidates/story_id/?page=1'
        return render_to_response('share/invite.html', { 'id': story_id,
                                                 'type': 'story',
                                                 'tabs': tabs,},
                          context_instance=RequestContext(request))
    recipients_list = []
    story = Activity.objects.get(pk=story_id)
    for key in request.POST.keys():
        if key.startswith('user_') and request.POST[key] == 'on':
            user_id = key[5:]
            user = User.objects.get(pk=user_id)   
            try:
                invite = Invite.objects.create(user=user, activity=story, response='U')             
                recipients_list.append(invite.to_user.email)
            except:
                pass
    if request.POST.get('email_notify', default='off') == 'on':
        title = u'来自' + request.user.profile.real_name + u'的邀请'
        invite_url = SITE_URL + 'story/invite/' + story_id
        mail_context = u'您的好友' + request.user.profile.real_name + u'邀请您参加故事' + story.name + u'请到' + invite_url + u' 查看'
        
        try:
            send_mail(title, mail_context, request.user.email, recipients_list, html=mail_context)
            #return HttpResponse(recipients_list)
        except:
            return HttpResponse('email server error!')
                
    return redirect('/story/detail/' + story_id)#('/story/edit/' + story_id)
Beispiel #3
0
 def run(self):
     print 'Staples: run'
     products = Product.objects.filter(website='staples')
     for product in products:
         print product.name
         print 'Before:' + str(product.current_price)
         try:
             p = self.query(product.url)
         except:
             p.error = True
         if str(product.current_price) != str(p['current_price']):
             prev_price = product.current_price
             product.current_price = float(p['current_price'])
             product.save()
             watchlist = Watchlist.objects.filter(product__pk=product.pk)
             to_list = []
             for w in watchlist:
                 user = w.user
                 s = Setting.objects.filter(user=user).get()
                 if float(w.desire_price) >= float(product.current_price):
                     if float(product.original_price) > float(s.amount):
                         if int(product.original_price) != 0:
                             if float(product.original_price) * float(
                                     s.percent) > float(
                                         product.current_price):
                                 to_list.extend(w.email.split(';'))
                         else:
                             to_list.extend(w.email.split(';'))
             send_mail(product, to_list)
             print 'After:' + str(product.current_price)
Beispiel #4
0
def send_alert(diffs):
    msg = "\n"
    for diff in diffs:
        msg += "%s\t\t%s\n" % (diff[0], diff[1])
    print "Sending e-mail .........."
    helper.send_mail(mail_header, msg.encode('utf-8'))
    return True
Beispiel #5
0
 def run(self):
     print 'Staples: run'
     products = Product.objects.filter(website='staples')
     for product in products:
         print product.name
         print 'Before:' + str(product.current_price)
         try:
             p = self.query(product.url)
         except:
             p.error = True
         if str(product.current_price) != str(p['current_price']):
             prev_price = product.current_price
             product.current_price = float(p['current_price'])
             product.save()
             watchlist = Watchlist.objects.filter(product__pk=product.pk)
             to_list = []
             for w in watchlist:
                 user = w.user
                 s = Setting.objects.filter(user=user).get()
                 if float(w.desire_price) >= float(product.current_price):
                     if float(product.original_price) > float(s.amount):
                         if int(product.original_price) != 0:
                             if float(product.original_price) * float(s.percent) > float(product.current_price):
                                 to_list.extend(w.email.split(';'))
                         else:
                             to_list.extend(w.email.split(';'))
             send_mail(product, to_list)
             print 'After:' + str(product.current_price)
Beispiel #6
0
def suggest(request):
    if request.method == 'POST':
        form = SuggestionForm(request.POST)
        if form.is_valid():
            send_mail(request.user.profile.real_name + 'report',
                      form.cleaned_data['description'],
                      request.user.email,
                      ['*****@*****.**',])
            return render_to_response('home/suggest_suc.html')
    form = SuggestionForm()
    return render_to_response('home/suggest.html', {'form': form,},
                              context_instance=RequestContext(request))
Beispiel #7
0
def cron():
	logging.debug('Start cron')
	
	# Fetch page content
	current_data = helper.fetch_current_data()
	
	if current_data["year_month"] is not None and current_data["current_number"] is not None:
		logging.debug('Have year month and current number')
	
		# Initial house number model
		table = model.house_number()
		
		# Check current data is or not exists
		current_data_total = table.all().filter("subject = ", current_data["year_month"]).count()
		
		if current_data_total <= 0:
			# Insert new record
			table.subject = current_data["year_month"]
			table.current_number = current_data["current_number"]
			table.put()
			
			# Found out history
			history = []
			house_numbers = table.all().order("-create_at")
			for house_number in house_numbers:
				history.append(
					"<strong>%s</strong> at <strong>%s</strong><br />" % (
						house_number.subject, 
						house_number.current_number
					)
				)
			
			# Send mail
			helper.send_mail(
				year_month = current_data["year_month"].encode("utf8"),
				current_number = current_data["current_number"],
				history = (''.join(history)).encode("utf8"),
				to = config.mail_catcher
			)
			
			logging.info('Create new record success: %s, %s', current_data["year_month"].strip(), str(current_data["current_number"]))
		else:
			logging.warning('Create new record failed: not update content found in page')
		
		bottle.redirect('/')
	else:
		logging.error('current data may be None such as year_month and current_number field')
	
	logging.debug('End cron')
Beispiel #8
0
def login():

    # forget any user_id
    session.clear()

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username was submitted
        if not request.form.get("username"):
            return 0  #"username field cannot be blank"

        # ensure password was submitted
        elif not request.form.get("password"):
            return 1  #"password field cannot be blank"

        # query database for username
        rows = db.execute("SELECT * FROM authority WHERE name = :name",
                          name=request.form.get("username"))

        # ensure username exists and password is correct
        if len(rows) != 1 or not pwd_context.verify(
                request.form.get("password"), rows[0]["hash"]):
            return 2  #"password doesn't match"

        global code
        code = send_mail(rows[0]["email"])

        return render_template("code.html")
    else:
        return render_template("index.html")
Beispiel #9
0
def invite_by_mail(request):
    if request.method == 'POST':
        name = request.POST.get('name', '')
        email = request.POST.get('email', '')
        link = request.POST.get('link', '')
        if name == '':
            return HttpResponse('请输入好友姓名')
        if email == '':
            return HttpResponse('请输入正确邮件地址')
        if link == '':
            return HttpResponse('活动链接错误,请联系开发人员')
        mail_context = name + u', 您的好友' + request.user.profile.real_name + u'邀请你参加活动' + '\n' + link
        recipients_list = []
        recipients_list.append(email)
        send_mail(u'活动邀请', mail_context, request.user.email, recipients_list, html=mail_context)
        return HttpResponse('邮件已发送,请通知您的好友查收')
    return redirect(u'/error?message=此方法不支持GET操作')
Beispiel #10
0
def forget_password(request):
    if request.method == 'POST':
        email = request.POST['email']
        try:
            password = User.objects.get(username=email).password
        except:
            return redirect(u'/error?message=此账户不存在!')
        title = u'myactivity密码找回'
        mail_context = u'您的密码是' + password

        try:
            send_mail(title, mail_context, email, [email], html=mail_context)
        except:
            return HttpResponse('email server error!')
        return render_to_response('accounts/get_password_ok.html')
    else:
        return render_to_response('accounts/get_password.html', context_instance=RequestContext(request))
Beispiel #11
0
def test_mail(client, test_user):
    ''' sending mail through webform '''
    recipients = [test_user['email']]
    subject = 'Testsubject'
    body = 'Testbody'

    with MAIL.record_messages() as outbox:
        login(client, test_user['email'], test_user['password'])
        rv = send_mail(client, '/mail/profile/{}'.format(test_user['id']),
                       'Testsubject', 'Testbody')

        assert rv.status_code == 200
        assert 'Email gesendet!' in rv.data
        assert outbox[0].sender == '{} {} <{}>'.format(
            unidecode(test_user['vorname'].decode('utf-8')),
            unidecode(test_user['name'].decode('utf-8')), test_user['email'])
        assert outbox[0].recipients == recipients
        assert outbox[0].subject == subject
        assert body in outbox[0].body
Beispiel #12
0
def register():
    """Register user."""

    # if user reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        # ensure username was submitted
        if not request.form.get("username"):
            return render_template("login.html")

        # ensure email was submitted
        if not request.form.get("email"):
            return render_template("login.html")

        # ensure password was submitted
        elif not request.form.get("password"):
            return render_template("login.html")

        # ensure re-password was submitted
        elif not request.form.get("re-password"):
            return render_template("login.html")

        global code_reg
        code_reg = send_mail(request.form.get("email"))

        #insert into database the details of the new user
        #rows = db.execute("INSERT INTO miner (user, hash) VALUES(:username, :hash_val)", username=request.form.get("username"), hash_val=pwd_context.hash(request.form.get("password")))

        #if not rows:
        #    return render_template("login.html")

        return render_template("code_reg.html")

    # else if user reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")
Beispiel #13
0
def send_alert(msg):
    print "Sending e-mail ........"
    helper.send_mail(mail_header, msg)
Beispiel #14
0
def process_basic_xml(xml_to_read):
    check = False
    file_xml = os.path.basename(xml_to_read)
    try:
        opta_id = ''
        som_offset = '00:00:00:00'
        house_id = None
        response = move_xml_to_process(xml_file=xml_to_read,
                                       folder=settings.PROCESSING_FOLDER_NAME)
        if response[0] == True:
            message = "File moved to processing folder"
            logger.info(message)
            xml_to_read = settings.PATH_TO_PROCESSING_FOLDER + '/' + response[1]
            xmldoc = xml.dom.minidom.parse(
                xml_to_read)  # Open XML document using minidom parser
            doc_root = xmldoc.documentElement
            if doc_root.getElementsByTagName('asset').length == 0:
                helper.send_mail(house_id=True,
                                 error_fields=False,
                                 check=False,
                                 file_name=file_xml,
                                 basic_xml_id=None)
                ingest_basic_xml(xml_file=xml_to_read,
                                 folder=settings.ERROR_FOLDER_NAME,
                                 house_id=False,
                                 record=False)
            else:
                parent = doc_root.getElementsByTagName('asset')[0]
                try:
                    parent.removeAttribute('asset-id')
                except Exception as ex:
                    pass
                if parent.getElementsByTagName(
                        'custom-metadata'
                ).length == 0 or parent.getElementsByTagName(
                        'basic-metadata').length == 0:
                    helper.send_mail(house_id=True,
                                     error_fields=False,
                                     check=False,
                                     file_name=file_xml,
                                     basic_xml_id=None)
                    ingest_basic_xml(xml_file=xml_to_read,
                                     folder=settings.ERROR_FOLDER_NAME,
                                     house_id=False,
                                     record=False)
                else:
                    child = parent.getElementsByTagName('custom-metadata')[0]
                    child.setAttribute('set-standard-id',
                                       settings.SET_STANDARD_ID)
                    count = len(child.childNodes)

                    # Parse xml to get opta_id & som_offset
                    for index in range(0, count):
                        try:
                            field = child.getElementsByTagName('field')[index]
                            if som_offset == '00:00:00:00':
                                if str(field.getAttribute(
                                        "standard-id")) == settings.SOM_ID:
                                    som_offset = str(field.childNodes[0].data)
                            if not opta_id:
                                if str(field.getAttribute(
                                        "standard-id")) == settings.OPTA_ID:
                                    opta_id = str(field.childNodes[0].data)
                            if str(field.getAttribute(
                                    "standard-id")) == settings.CONTENTTYPE:
                                if settings.CONTENTTYPE and str(
                                        field.childNodes[0].data).lower(
                                        ).strip() == 'program':
                                    field.childNodes[0].data = 'Magazine Shows'
                        except Exception as ex:
                            pass
                    # Parse xml to get house_id
                    for index in range(0, count):
                        try:
                            field = child.getElementsByTagName('field')[index]
                            # if str(field.getAttribute("standard-id")).lower().find('house') >= 0:
                            if str(field.getAttribute(
                                    "standard-id")) == settings.HOUSE_ID:
                                house_id = str(field.childNodes[0].data)
                                break
                        except Exception as ex:
                            continue
                    try:
                        # House_id doesn't exits send error email ...
                        if house_id == None:
                            logger.error(
                                "House_id doesn't exists in XML, moving xml to error folder."
                            )
                            ingest_basic_xml(xml_file=xml_to_read,
                                             folder=settings.ERROR_FOLDER_NAME,
                                             house_id=False,
                                             record=False)
                            helper.send_mail(house_id=False,
                                             error_fields=False,
                                             check=False,
                                             file_name=file_xml,
                                             basic_xml_id=None)
                        else:

                            ingest_action = 'create-new-asset'
                            file_name = parent.getAttribute('file-name')
                            try:
                                res = check_media_asset(file_name, house_id)
                                xml_obj = BasicXml.objects.get(
                                    house_id=house_id)
                                if xml_obj.asset_id == '':  # Record exits with null asset_id
                                    logger.error(
                                        "Moving file back to watch folder. Asset_id corresponding to this House_id is not received yet."
                                        "In case error is reported on eMAM dashboard then you need to delete that particular record & place"
                                        " it again in watch folder after fixing it."
                                    )
                                    move_xml_to_process(
                                        xml_file=xml_to_read,
                                        folder=settings.XML_WATCH_FOLDER_NAME)
                                else:  # Record exits with some asset_id
                                    if opta_id:
                                        xml_obj.opta_id = opta_id
                                        xml_obj.save()
                                    ingest_action = 'associate-metadata'

                                    asset_id = xml_obj.asset_id
                                    check = True
                            except BasicXml.DoesNotExist:  # Record doesn't exits with house_id
                                #file_name = parent.getAttribute('file-name')

                                if res[0] == True:
                                    xml_obj = BasicXml(
                                        house_id=house_id,
                                        opta_id=opta_id,
                                        som=som_offset
                                    )  # Creation of new record with house_id
                                    '''
                                            if not opta_id:
                                                xml_obj = BasicXml(house_id=house_id)  # Creation of new record with house_id
                                            else:
                                                xml_obj = BasicXml(house_id=house_id, opta_id=opta_id, som=som_offset)  # Creation of new record with house_id & opta_id
                                            '''
                                    xml_obj.save()
                                    check = True
                                elif res[0] == False:
                                    logger.info(
                                        "Moving file back to watch folder.")
                                    move_xml_to_process(
                                        xml_file=xml_to_read,
                                        folder=settings.XML_WATCH_FOLDER_NAME)
                            if check == True:
                                xml_obj = BasicXml.objects.get(
                                    house_id=house_id)
                                xml_logs_obj = BasicXmlLogs(
                                    basic_xml=xml_obj,
                                    status=BasicXmlLogs.Status.PROCESSING.value
                                )  # Entry in BasicXmlLogs table with processing status
                                xml_logs_obj.save()
                                log_message = '[{0}] Started reading XML for house id : {1}'.format(
                                    get_current_formatted_datetime(), house_id)
                                helper.update_logs(record=xml_logs_obj,
                                                   log_message=log_message)
                                doc_root.setAttribute('user-key',
                                                      settings.USER_KEY)
                                if ingest_action == 'create-new-asset':
                                    parent.setAttribute('file-path', res[1])
                                parent.setAttribute('file-action',
                                                    settings.FILE_ACTION)
                                parent.setAttribute('file-name', res[2])
                                parent.setAttribute('ingest-action',
                                                    ingest_action)
                                if ingest_action == 'associate-metadata':
                                    parent.setAttribute('asset-id', asset_id)
                                full_validation_and_ingest_process(
                                    count=count,
                                    child=child,
                                    xml_file=xml_to_read,
                                    xmldoc=xmldoc,
                                    house_id=house_id,
                                    ingest_action=ingest_action,
                                    basic_xml_id=xml_logs_obj,
                                    file_name=file_xml,
                                    asset_tag=parent)

                    except BasicXml.DoesNotExist:
                        logger.exception(BasicXml.DoesNotExist)
                    except Exception as ex:
                        logger.exception(ex)
        else:
            sys.exit(0)
    except Exception as ex:
        helper.send_mail(house_id=True,
                         error_fields=ex,
                         check=False,
                         file_name=file_xml,
                         basic_xml_id=None)
        ingest_basic_xml(xml_file=xml_to_read,
                         folder=settings.ERROR_FOLDER_NAME,
                         house_id=False,
                         record=False)
        logger.exception(ex)
Beispiel #15
0
                ):
                    invalid_operation = False
                    with open('email.html', 'r') as html_file:
                        data = html_file.read().replace('\n', '')
                        loop_card = helper.get_card_by_id(c_id)
                        mail_to_list = []
                        for resource in loop_card.share_list.resources:
                            if type(resource) is Group:
                                mail_to_list.append(resource.id)
                        # if direct message, there is no group so mail_to_list will be empty
                        if not mail_to_list:
                            for resource in loop_card.share_list.resources:
                                if type(resource) is User:
                                    mail_to_list.append(resource.email)
                            status_code = helper.send_mail(
                                "User", c_id, STATUS_MAIL_SUBJECT, data,
                                mail_to_list)
                            if status_code == 201:
                                messages.send_message_to_chat_card(
                                    "Done, check your inbox.", c_id,
                                    helper.BOT_ID)
                            else:
                                messages.send_message_to_chat_card(
                                    "Ooops, something went wrong.", c_id,
                                    helper.BOT_ID)

                        else:
                            #send to group
                            status_code = helper.send_mail(
                                "Group", c_id, STATUS_MAIL_SUBJECT, data,
                                mail_to_list)