Esempio n. 1
0
def create_debate(req):
    if req.method == "POST":
        form = CreateDebateForm(req.POST)
        if form.is_valid():
            deb = Debate(title = form.cleaned_data['title'], 
                         summary = form.cleaned_data['summary'], 
                         instigator = req.user,
                         challenged_users = form.cleaned_data['challenged_users'])
            deb.save()
            
            if not deb.accept_all_challengers():
                # add message for each challenged user.
                for uname in deb.get_challenged_usernames():
                    u = User.objects.get(username=uname)
                    msg = UserMessage(recipient=u,
                                      message="new challenge: %s" % deb.title,
                                      sender=deb.instigator)
                    msg.save()
            
            return HttpResponseRedirect('/')
    else:
        form = CreateDebateForm()

    return render_to_response("create_debate.html", 
                              RequestContext(req, {"form": form}))
Esempio n. 2
0
def send_msg(request):
    response = {}
    info = ""
    try:
        if request.method == 'POST':
            req = request.POST
            recv_user = req.get('recv_user')
            send_user = req.get('send_user')
            title = req.get('title')
            content = req.get('content')
            msg = Message(title=title, content=content)
            # 发送者ID为1则是系统信息
            if send_user == 1:
                msg.category = 1
            msg.save()
            user_msg = UserMessage(recv_user=recv_user,send_user=send_user,message=msg)
            user_msg.save()
            response['status'] = user_msg.status

    except:
        info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
        return HttpResponse(info)

    response_json = simplejson.dumps(response)
    return HttpResponse(response_json)
Esempio n. 3
0
def create_debate(req):
    if req.method == "POST":
        form = CreateDebateForm(req.POST)
        if form.is_valid():
            deb = Debate(
                title=form.cleaned_data['title'],
                summary=form.cleaned_data['summary'],
                instigator=req.user,
                challenged_users=form.cleaned_data['challenged_users'])
            deb.save()

            if not deb.accept_all_challengers():
                # add message for each challenged user.
                for uname in deb.get_challenged_usernames():
                    u = User.objects.get(username=uname)
                    msg = UserMessage(recipient=u,
                                      message="new challenge: %s" % deb.title,
                                      sender=deb.instigator)
                    msg.save()

            return HttpResponseRedirect('/')
    else:
        form = CreateDebateForm()

    return render_to_response("create_debate.html",
                              RequestContext(req, {"form": form}))
 def saveUserMessage(userId, message, messageType):
     um = UserMessage(userId=userId,
                      eventTime=datetime.now(),
                      message=message[:200],
                      messageType=str(messageType))
     db.session.add(um)
     db.session.commit()
Esempio n. 5
0
def update_notice(novel):
    favs = UserFavorite.select().where((UserFavorite.novel_id == novel.id)
                                       & (UserFavorite.notice_enable > 0))

    for fav in favs:
        user = UserProfile.get_by_id(fav.user_id)
        if user.email:
            subject = "小说更新通知"
            utils.send_update_online_email(subject, user.email,
                                           novel.novel_name)
        elif user.mobile:
            utils.send_update_sms(user.mobile, novel.novel_name)
        else:
            try:
                message = "您收藏的小说({0})已经有更新了, 请前往阅读.".format(novel.novel_name)
                UserMessage.create(message=message, user_id=user.id)
                logger.info("发送小说[{0}]更新消息给用户[{1}]成功".format(
                    novel.novel_name, user.username))
            except Exception as e:
                logger.error("发送小说[{0}]更新消息给用户[{1}]失败, 原因:{2}".format(
                    novel.novel_name, user.username, e))
Esempio n. 6
0
def send_message():

    if request.method == 'POST':
        sender = current_user.username
        receiver = request.form.get('receiver')
        text = request.form.get('message')

        newMessage = UserMessage(sender=sender,
                                 receiver=receiver,
                                 message=text)
        db_session.add(newMessage)
        db_session.commit()

        flash('Wiadomość wysłana!')
        return redirect(url_for('messages_menu'))

    return render_template('map_neigh/send_message.html')
Esempio n. 7
0
def handle_message_like(msg_id):

    form = LikeMessageForm()

    msg = Message.query.get(msg_id)

    if form.validate_on_submit():
        if (msg not in g.user.liked_messages) and (msg not in g.user.messages):
            liked_message = UserMessage(user_liking_id=g.user.id,
                                        message_liked=msg_id)
            db.session.add(liked_message)
            db.session.commit()

        else:
            UserMessage.query.filter(
                msg.id == UserMessage.message_liked).delete()

            db.session.commit()

    return redirect('/')
Esempio n. 8
0
    def create_by_postulation(self, request, postulation_pk):
        """Create a message from postulation"""
        if not request.user.is_employer:
            content = {'unauthorized': '401 - only employer can send message'}
            return Response(content, status=status.HTTP_401_UNAUTHORIZED)

        serializer = UserMessageSerializer(data=request.data)
        if serializer.is_valid():
            postulation = JobPostulation(id=postulation_pk)
            user_message = UserMessage()
            user_message.employer = postulation.job.owner
            user_message.postulant = postulation.user
            user_message.message = request.data['message']
            user_message.save()
            user_message.postulant.send_usermessage_email(user_message)
            return Response({'status': _('Mensaje enviado')})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 9
0
def messages_show(message_id):
    """Show a message."""

    msg = Message.query.get(message_id)

    form = LikeMessageForm()

    if form.validate_on_submit():
        if (msg not in g.user.liked_messages) and (msg not in g.user.messages):
            liked_message = UserMessage(user_liking_id=g.user.id,
                                        message_liked=message_id)
            db.session.add(liked_message)
            db.session.commit()
            return redirect(f'/messages/{message_id}')

        else:
            UserMessage.query.filter(
                msg.id == UserMessage.message_liked).delete()

            db.session.commit()
            return redirect(f'/messages/{message_id}')

    else:
        return render_template('messages/show.html', form=form, message=msg)
Esempio n. 10
0
    def create_by_cvrequest(self, request, cvrequest_pk):
        """Create a message from cvrequest"""
        if not request.user.is_employer:
            content = {'unauthorized': '401 - only employer can send message'}
            return Response(content, status=status.HTTP_401_UNAUTHORIZED)

        serializer = UserMessageSerializer(data=request.data)
        if serializer.is_valid():
            cvrequest = CVRequest.objects.filter(id=cvrequest_pk,
                                                 status=CVREQUEST_ACCEPTED)
            if not cvrequest:
                return Response(status=status.HTTP_400_BAD_REQUEST)

            cvrequest = cvrequest[0]
            user_message = UserMessage()
            user_message.employer = cvrequest.employer.user
            user_message.postulant = cvrequest.user
            user_message.message = request.data['message']
            user_message.save()
            user_message.postulant.send_usermessage_email(user_message)
            return Response({'status': _('Mensaje enviado')})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 11
0
	def sendmsg(user, message):
		""" Send a User Message to the user """
		msg = UserMessage(um_user = user, um_contents = message)
		msg.save()
Esempio n. 12
0
import os
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

from bot.db import db
# from models import app
from models import UserMessage
# from flask_sqlalchemy import SQLAlchemy
# create all

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', None)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
db.create_all()

# insert data
db.session.add(
    UserMessage(id_='test_id', type='text', user_token="token_1", text="hey"))

#
# commit the changes
db.session.commit()
Esempio n. 13
0
def register(request):
    if request.method == 'GET':
        form = RegistForm()
        return render_to_response("register.html", RequestContext(request, {'form': form}))
    else:         
        form = RegistForm(request.POST)
        register_flag = True
        username_tips = False
        password_tips = False
        email_tips = False
        tips_message = ''

        if form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            password_again = request.POST.get('password_again', '')
            email = request.POST.get('email', '')
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                pass
            else:
                tips_message = u'用户名已存在'
                username_tips = True
                register_flag = False

            if register_flag == True and password != password_again:
                tips_message = u'两次密码不一致'
                password_tips = True
                register_flag = False
                
            sendEmail = dict()
            sendEmail['from'] = '*****@*****.**'
            with open('media/email/register.txt') as f:
                allEmail = f.read().split('\n')
                sendEmail['subject'] = allEmail[0]
                sendEmail['text'] = ''.join(allEmail[1:]) % username.encode('utf-8')
            
            emailReturnNo = send_mail(sendEmail['subject'], sendEmail['text'], sendEmail['from'], [email], fail_silently=False)
            if 0 == emailReturnNo:
                tips_message = u'邮箱有误'
                email_tips = True
                register_flag = False

            if register_flag:
                user = User.objects.create_user(username=username,
                                                password=password,
                                                email=email)

                user.save()
                usermessage = UserMessage()
                print type(request.user)
                usermessage.user = user
                usermessage.save()

                return HttpResponseRedirect('/accounts/login/')
            
        return render_to_response(
            'register.html',
            RequestContext(request, {'form': form,
                                     'tips': True,
                                     'tips_title': u'错误!',
                                     'tips_message': tips_message,
                                     'username_tips': username_tips,
                                     'password_tips': password_tips,
                                     'email_tips': email_tips}))
Esempio n. 14
0
    def create(self, request, message_pk):
        """Create a response for a message"""
        if not self.user.is_postulant:
            content = {
                'unauthorized': '401 - only postulant can send response'
            }
            return Response(content, status=status.HTTP_401_UNAUTHORIZED)

        message = UserMessage(id=message_pk, postulant=request.user)

        if not message:
            content = {'badrequest': '400 - message not found'}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

        serializer = UserMessageSerializer(data=request.data)
        if serializer.is_valid():
            # XXX use request.data because when get from serializer.data raise
            # KeyError for some fields.

            # make the response message
            response = UserMessage()
            response.message = request.data['message']
            response.employer = message.employer
            response.postulant = message.postulant

            if message.postulation:
                response.postulation = message.postulation

            elif message.cvrequest:
                response.cvrequest = message.cvrequest

            response.save()

            # make relation between message and response
            message.response = response
            message.save()

            # Send email to employer if the preference is set, this setting
            # depend if the message generated by spontaneous cv or by
            # postulation
            if (response.postulation
                    and response.postulation.job.send_cvs_by_mail):
                response.employer.send_usermessage_email(response)

            elif response.employer.cv_spontany:
                response.employer.send_usermessage_email(response)

            return Response({'status': _('Mensaje enviado')})

        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 15
0
 def read(self, request, message_pk):
     """Mark readed a message"""
     user_message = UserMessage(id=message_pk)
     user_message.readed_at = timezone.now()
     user_message.save()
     return Response({'status': _('Mensaje marcado como leído')})
Esempio n. 16
0
def user_messages():
    return { 'user_messages': UserMessage.unread_messages() }
from django.test import TestCase
from models import UserMessage

# Create your tests here.
tables = UserMessage()
print "get datatable:"
print "access datatable:", tables.name, tables.email
Esempio n. 18
0
 def sendmsg(user, message):
     """ Send a User Message to the user """
     msg = UserMessage(um_user=user, um_contents=message)
     msg.save()