Beispiel #1
0
    def post(self: View, request: HttpRequest, slug: str) -> JsonResponse:
        """Add a new message to the specified room."""
        payload = json.loads(request.body.decode())
        content = str(payload.get('content', ''))

        if not 1 <= len(content) <= 256:
            return error('Content length must be between 1 and 256.')

        if not request.session.get('registered'):
            return error('You are not registered.')

        room = Room.objects.filter(slug=slug).first()
        if room is None:
            return error('That room does not exist.')

        message = Message(
            author=request.session.get('username'),
            content=content,
            room=room
        )
        message.save()

        return JsonResponse({
            'success': True,
            'message': {
                'content': message.content,
                'author': message.author
            }
        })
Beispiel #2
0
def checkUpload():
    """
    检查上传截图是否过期
    :return:
    """
    now = datetime.datetime.now()
    start = now - datetime.timedelta(minutes=30)
    #半个小时之外,并且到上传截图这步骤
    oas = OrderApply.objects.filter(update_time__lte=start,finished=0,teacher_willing=2,parent_willing=2)
    for oa in oas:
        try:
            with transaction.atomic():
                #没有上传截图,当做老师拒绝操作
                oa.finished =1
                oa.teacher_willing = 0
                oa.save()
                #给老师发送消息,老师过期
                message_title = u"你的订单已过期,没有在相应的时间内上传截图!"
                message_content = u"你的订单已过期,没有在相应的时间内上传截图!"
                #应该是管理员发送
                message = Message(sender=oa.tea.wechat, receiver=oa.tea.wechat, message_title=message_title, message_content=message_content,status=0)
                message.save()
                #老家长发送消息,审核不通过
                message_title = u"订单审核不通过!"
                message_content = u"订单审核不通过!"
                message = Message(sender=oa.tea.wechat, receiver=oa.pd.wechat, message_title=message_title, message_content=message_content,status=0)
                message.save()
                #推送到微信端
        except Exception,e:
            print e.message
Beispiel #3
0
def remindFeedBack(request):
    """
    提醒某个用户提交反馈
    :param request:
    :return:
    """
    id = request.data.get('id',None)
    userType = request.data.get('user',None)
    user = AuthUser.objects.get(username=request.user.username)
    message_title = u"好学吧家教邀请您填写反馈意见!"
    message_content = u"好学吧家教邀请您填写反馈意见!"
    if userType == "parent":
        objs = ParentOrder.objects.filter(pd_id = id)
    elif userType == "teacher":
        objs = Teacher.objects.filter(tea_id = id)
    else:
        return JsonError(u"输入数据的user值不对")
    if len(objs):
        obj = objs[0]
        now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        message = Message(sender=user, receiver=obj.wechat, message_title=message_title,
                          message_content=message_content,status=0,update_time=now,create_time=now)
        message.save()
        return JsonResponse()
    else:
        return JsonError(u"找不到用户!")
Beispiel #4
0
 def handle(self, *args, **kwargs):
     if len(Message.objects.all()) == 0:
         nowID = Message(stopID=15753)
     else:
         nowID = Message.objects.all()[0]
     tokens = AccessToken.objects.all()
     url = "http://www.ttsh.tp.edu.tw/module.php?i=news&cat_id=2&start=0"
     html = requests.get(url)
     soup = BeautifulSoup(html.text, 'html.parser')
     className = 'list-group-item'
     newsLists = soup.find_all('a', {'class': className})
     newsLists = newsLists[3:]
     for i in range(len(newsLists)):
         x, newsdict = newsLists[i], dict()
         newsdict['link'] = "http://www.ttsh.tp.edu.tw" + x['href'][1:]
         query = urlparse.urlsplit(newsdict['link']).query
         newsdict['id'] = int(urlparse.parse_qs(query)['news_id'][0])
         className = 'title'
         title = x.find('span', {'class': className})
         newsdict['title'] = title.get_text(strip=True)
         newsLists[i] = newsdict
     second = True
     newsLists.reverse()
     for x in newsLists:
         if x['id'] <= nowID.stopID:
             continue
         nowID.message = x['title']
         nowID.stopID = x['id']
         if second:
             tokens = AccessToken.objects.all()
             second = False
         status = self.send_pro(x['title'] + "\n" + x['link'], tokens)
         if status is not None:
             print(status)
     nowID.save()
Beispiel #5
0
def sendPhone(request):
    """
    发送联系方式给某个老师
    :param request:{"tea_id":1,"tel":18812345678,"oa_id":3}
    :return:
    """
    tea_id = request.data.get('tea_id',None)
    oa_id = request.data.get('oa_id',None)
    tel = request.data.get('tel',None)
    teas = Teacher.objects.filter(tea_id=tea_id)
    oas = OrderApply.objects.filter(oa_id=oa_id)
    user = AuthUser.objects.get(username=request.user.username)
    if len(teas) and len(oas):
        tea = teas[0]
        oa = oas[0]
        pd_name  = oa.pd.name
        message_title = u"向您发送了" + pd_name +u"家长的联系方式!"
        message_content = pd_name + u"家长的联系方式是" + str(tel)
        now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        message = Message(sender=user, receiver=tea.wechat, message_title=message_title,
                          message_content=message_content,status=0,update_time=now,create_time=now)
        message.save()
        oa.tel = str(tel)
        oa.finished = 1
        oa.save()
        return JsonResponse()
    else:
        return JsonError(u"输入数据有误")
Beispiel #6
0
def messages(request):
    if request.method == 'GET':
        return JsonResponse([message.serialize() for message in Message.objects.all()], safe=False)
    else:
        data = request.POST
        message = Message(author=data['author'], content=data['content'])
        message.save()
        return JsonResponse(message.serialize(), safe=False)
Beispiel #7
0
    def create_message(id, user_id, date, text):
        message = Message()
        message.id = id
        message.user_id = user_id
        message.date = date
        message.text = text

        message.save()
        return message
Beispiel #8
0
def messages(request):
    if request.method == 'GET':
        return JsonResponse(
            [message.serialize() for message in Message.objects.all()],
            safe=False)
    else:
        data = request.POST
        message = Message(author=data['author'], content=data['content'])
        message.save()
        return JsonResponse(message.serialize(), safe=False)
Beispiel #9
0
    def create(self, request, *args, **kwargs):
        """
        parameters: 'recipientID', 'textFirstMessage'
        """
        for parameter in ['recipientID', 'textFirstMessage']:
            if parameter not in request.data:
                print(3333)
                return Response(status=status.HTTP_400_BAD_REQUEST)

        recipientID = request.data['recipientID']
        textFirstMessage = request.data['textFirstMessage']

        querysetDialogsUser = list()
        querysetDialogsRecipient = list()

        #exist dialog?
        for item in DialogOwners.objects.filter(owner=request.user):
            querysetDialogsUser.append(item.dialog)
        for item in DialogOwners.objects.filter(owner=User.objects.get(id=recipientID)):
            querysetDialogsRecipient.append(item.dialog)
        
        #if dialog exist
        for item in querysetDialogsUser:
            if querysetDialogsRecipient.count(item) != 0:
                return Response(status=status.HTTP_400_BAD_REQUEST)

        dialog = Dialog()
        dialog.save()

        message = Message()
        message.owner = request.user
        message.ownerDialog = dialog
        message.text = textFirstMessage
        message.date = timezone.now()
        message.save()

        dialog.textLastMessage = textFirstMessage
        dialog.dateLastMessage = message.date
        dialog.idLastMessage = message.id

        dialog.save()

        dialogOwner1 = DialogOwners()
        dialogOwner2 = DialogOwners()

        dialogOwner1.owner = request.user
        dialogOwner1.dialog = dialog
        dialogOwner2.owner = User.objects.get(id=recipientID)
        dialogOwner2.dialog = dialog

        dialogOwner1.save()
        dialogOwner2.save()

        #data = [{ 'id':dialog.id }]
        return Response(status=status.HTTP_201_CREATED)
def __uploadhelper(request):
    if request.FILES is None or request.FILES['original_file'] is None:
        raise Exception('No file sent.')
    # Get uploaded file.
    origFile = request.FILES['original_file']
    # Apply reverse reverb (aka "creepify")?
    soxCreepify = True if request.POST['creepify'] == 'yes' else False
    # Check that this is a wav file.
    if origFile.content_type not in settings.ALLOWABLE_INPUT_FILE_TYPES:
        raise Exception('You can only upload WAV files!')
    # TODO: Eventually, extract file extention and check for a list of supported file types.
    # Create unique user path.
    fileRoot = settings.MEDIA_ROOT + settings.VOICE_FILES_DIR
    urlRoot = settings.MEDIA_URL + settings.VOICE_FILES_DIR
    uniqueId = str(uuid.uuid4())
    userDir = os.path.join(fileRoot, uniqueId)
    userUrl = '/'.join([urlRoot, uniqueId])
    os.makedirs(userDir)
    # origFilePath = os.path.join(userDir, origFile.name) # Removed the input file name since it will be passed to a shell script command.
    origFilePath = os.path.join(userDir, settings.ORIG_FILE_NAME)
    origFileUrl = '/'.join([userUrl, settings.ORIG_FILE_NAME])
    # Save uploaded file.                
    __handle_uploaded_file(origFile, origFilePath)
    # Now generate altered file.
    altFilePath = os.path.join(userDir, settings.ALT_FILE_NAME)
    altFileUrl = '/'.join([userUrl, settings.ALT_FILE_NAME])
    # Temp files.
    soxTmpFilePath = os.path.join(userDir, 'tmp.wav')
    soxTmpFileRevPath = os.path.join(userDir, 'tmprev.wav')
    if soxCreepify:
        # Example: sox original.wav tmp.wav norm vad gain -7 pitch -600 overdrive 20 pad .25; sox tmp.wav tmprev.wav reverse reverb -w reverse; sox -m tmp.wav tmprev.wav altered.mp3
        # First create temp file with standard voice mods.
        soxCmd = ' '.join([settings.SOX_PATH, origFilePath, soxTmpFilePath, 'norm vad gain', settings.SOX_GAIN, 'pitch', settings.SOX_PITCH, 'overdrive', settings.SOX_OVERDRIVE, 'pad', settings.SOX_PAD])
        subprocess.call(soxCmd, shell=True)
        # Then add the reverse reverb (two shell commands).
        soxCmd = ' '.join([settings.SOX_PATH, soxTmpFilePath, soxTmpFileRevPath, 'reverse reverb -w reverse'])
        subprocess.call(soxCmd, shell=True)
        soxCmd = ' '.join([settings.SOX_PATH, '-m', soxTmpFilePath, soxTmpFileRevPath, altFilePath])
        subprocess.call(soxCmd, shell=True)
        # Then delete the temp files.
        os.remove(soxTmpFilePath)
        os.remove(soxTmpFileRevPath)
    else:
        # Example: sox original.wav altered.wav norm vad gain -7 pitch -600 overdrive 20 pad .25
        soxCmd = ' '.join([settings.SOX_PATH, origFilePath, altFilePath, 'norm vad gain', settings.SOX_GAIN, 'pitch', settings.SOX_PITCH, 'overdrive', settings.SOX_OVERDRIVE, 'pad', settings.SOX_PAD])
        subprocess.call(soxCmd, shell=True)
    newMsg = Message(
                     unique_id=uniqueId,
                     original_file=origFileUrl,
                     altered_file=altFileUrl
                    )
    newMsg.save()
    # Return the Message object that you just created.
    return newMsg
Beispiel #11
0
 def post(self, request):
     data = parsers.JSONParser().parse(request)
     try:
         jwt.decode(data['auth_token'], 'secret', algorithm='HS256')
     except jwt.InvalidSignatureError:
         return HttpResponse('Unathorized', status=401)
     message = Message(
         user_id=UserAuthen.objects.get(token=data['auth_token']).user_id,
         text=data['text'])
     try:
         message.save()
     except db.IntegrityError:
         return HttpResponse('Conflict', status=409)
     return HttpResponse('OK', status=200)
Beispiel #12
0
class MessageModelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create(username="******")
        self.message = Message(body='message body', author=self.user)

    def test_create_message(self):
        old_count = Message.objects.count()
        self.message.save()
        new_count = Message.objects.count()
        self.assertEqual(new_count - old_count, 1)
        self.assertNotEqual(new_count, old_count)

    def test_str_representation(self):
        self.assertEqual(unicode(self.message), self.message.body)
Beispiel #13
0
def message_on_save(message):
    try:
        room = Room.objects.get(name=message.content['room'])
    except Room.DoesNotExist:
        room = Room.objects.create(name=message.content['room'])

    try:
        user = User.objects.get(username=message.content['username'])
    except User.DoesNotExist:
        return

    message = Message(author=user, room=room, body=message.content['text'])
    message.save()
    print "Saving message: %s from %s for room %s" % (
        message.body, message.author.username, message.room.name)
Beispiel #14
0
def handleUserOrder(request):
    """
    管理员处理订单
    :param request:
    {
     "oa_id": 1         订单ID
     "user":teacher/parent,           修改老师还是家长的意愿
     "willing": 0/1/2      0/1/2  0:拒绝 1:待处理 2:接受
     }
    :return:
    """
    user = AuthUser.objects.get(username=request.user.username)
    oa_id = int(request.data.get('oa_id',0))
    userType = request.data.get('user',None)
    willing = request.data.get('willing',None)
    try:
        oa = OrderApply.objects.get(oa_id = oa_id)
        if userType == 'teacher':
            #TODO:管理员暂时无法处理老师的订单
            if willing == 0:
                oa.teacher_willing = 0
                oa.finished = 1
            if willing == 2:
                oa.teacher_willing = 2
        if userType == 'parent':
            #将家长意愿修改为拒绝
            if willing == 0:
                oa.parent_willing = 0
                oa.finished = 1
                message_title = oa.pd.name + u"拒绝了你的报名!"
                message_content = oa.pd.name +  u"拒绝了你的报名!请到“我的家长”处查看详细信息!"

            if willing == 2:
                oa.parent_willing = 2
                oa.finished = 0
                message_title = oa.pd.name + u"接受了你的报名!"
                message_content = oa.pd.name +  u"接受了你的报名!请到“我的家长”处查看详细信息!"

            now = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            message = Message(sender=user, receiver=oa.tea.wechat, message_title=message_title,
                              message_content=message_content,status=0,update_time=now,create_time=now)
            oa.save()
            message.save()
        return JsonResponse()
    except Exception,e:
        print 'traceback.print_exc():'; traceback.print_exc()
        return JsonError(e.message)
Beispiel #15
0
    def log(webhook_data, client=None, order=None):
        if webhook_data:
            if not client:
                client = Client.objects.filter(
                    token=webhook_data.sender_id,
                    source=webhook_data.source.upper()
                    if webhook_data.source else None).first()

            message = Message(action=webhook_data.action,
                              content=webhook_data.message,
                              source=webhook_data.source,
                              session=webhook_data.session_id,
                              client=client,
                              order=order,
                              notify=webhook_data.action
                              in NOTIFICATION_ACTIONS)
            message.save()
            return message
        return False
    def receive(self, text_data=None, bytes_data=None):
        room_name = self.scope['url_route']['kwargs']['room_name']
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        msg_obj = Message(content=message)
        msg_obj.save()

        # Save it as a post on the group for later retrieval
        group = Group.objects.get(id=room_name)
        group.posts.add(msg_obj)
        group.save()

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {
                'type': 'chat_message',
                'message': message,
                'group': room_name,
                'user': self.scope['user'].id
            })
Beispiel #17
0
 def test_basic(self):
     prj = Project(name="TestProject")
     prj.save()
     prj.set_property("testing.tests.a.timeout", 3600)
     prj.set_property("testing.tests.a.enabled", True)
     prj.set_property("testing.tests.a.script", "#!/bin/bash\ntrue")
     prj.set_property("testing.tests.a.requirements", "")
     prj.set_property("testing.tests.a.users", "")
     prj.set_property("testing.tests.a.tester", "")
     msg = Message(project=prj,
                   date=datetime.datetime.now(),
                   is_series_head=True,
                   is_patch=True)
     msg.save()
     msg.set_property("git.repo", "dummy repo")
     msg.set_property("git.tag", "dummy tag")
     msg.set_property("git.base", "dummy base")
     self.api_login()
     td = self.api_call("testing-get",
                        project="TestProject",
                        tester="dummy tester",
                        capabilities=[])
     self.assertIn("head", td)
Beispiel #18
0
    def create(self, validated_data):
        owners = validated_data.get('owners', None)

        if owners is None:
            raise serializers.ValidationError('Вы не задали владельцев диалога!')

        if len(owners) != 2:
            raise serializers.ValidationError('Участников диалога должно быть два!')

        user1 = owners[0]
        user2 = owners[1]

        if user1 != self.user and user2 != self.user:
            raise serializers.ValidationError('Вы не можете создать не свой диалог!')

        if user1 == user2:
            if Dialog.objects.annotate(owners_count=Count('owners')).filter(owners_count=1, owners=user1).exists():
                raise serializers.ValidationError('Такой диалог уже существует!')
        elif Dialog.objects.filter(owners=user1).filter(owners=user2).exists():
            raise serializers.ValidationError('Такой диалог уже существует!')

        dialog = Dialog()
        dialog.save()
        dialog.owners.add(user1)

        if user1 != user2:
            dialog.owners.add(user2)

        message = Message(text=self.message, owner=self.user, dialog=dialog)
        message.save()
        dialog.last_message = message

        dialog.save()

        send_event('new_dialog', owners, DialogSerializer(dialog).data)

        return dialog
Beispiel #19
0
    def create(self, validated_data):
        text = validated_data.get('text', None)
        dialog = validated_data.get('dialog', None)

        if text is None or text == '':
            raise serializers.ValidationError('Отсутствуют необходимые параметры!')

        owners = dialog.owners.all()

        if self.user not in owners:
            raise PermissionDenied

        message = Message()
        message.owner = self.user
        message.dialog = dialog
        message.text = text
        message.save()

        dialog.last_message = message
        dialog.save()

        send_event('new_message', owners, MessageSerializer(message).data)

        return message
Beispiel #20
0
def home(request):
    if request.method == 'POST':
        message_split = request.POST['message'].split('&|!')
        mobile_number = request.POST['mobile_number']

        channel_name = message_split[0]
        latitude = message_split[1]
        longitude = message_split[2]
        description = message_split[3]
        contents = message_split[4]

        channel = Channel.objects.filter(name=channel_name)

        if not channel:
            channel = Channel(name=channel_name)
            channel.save()
        else:
            channel = channel[0]

        sentiment = int(requests.get('%s?message=%s' % (settings.SENTIMENT_ANALYSIS_URL, contents)).text)

        message = Message(
            channel=channel,
            latitude=float(latitude),
            longitude=float(longitude),
            description=description,
            message=contents,
            mobile_number=mobile_number,
            sentiment=sentiment,
        )

        message.save()
        return HttpResponse('Accepted')

    else:
        return JsonResponse(User.objects.all()[0].email, safe=False)
Beispiel #21
0
    def create(self, request, *args, **kwargs):
        """
        parameters POST: 'dialogID', 'text'
        """
        for parameter in ['dialogID', 'text']:
            if parameter not in request.data:
                return Response(status=status.HTTP_400_BAD_REQUEST)

        dialog = Dialog.objects.get(pk=request.data['dialogID'])
        message = Message()
        message.owner = request.user
        message.ownerDialog = dialog
        message.text = request.data['text']
        message.date = timezone.now()
        message.save()

        if dialog.dateLastMessage < message.date:
            dialog.dateLastMessage = message.date
            dialog.textLastMessage = message.text
            dialog.idLastMessage = message.id
            dialog.save()

        #data = [{ 'id':message.id }, { 'date':message.date }]
        return Response(status=status.HTTP_201_CREATED)
Beispiel #22
0
    def send_email(self, bcc=False):
        # send email using the self.cleaned_data dictionary

        # get this message
        old_message = self.instance

        # get this thread
        thread = old_message.thread
        house_id = ""
        try:
            house_id = thread.messages[
                0].receiver.home_owner_profile.house.all()[0].pk
        except:
            pass
            # Create a new message instance
        message = Message(text="",
                          sender=old_message.receiver,
                          receiver=old_message.sender,
                          thread=thread)
        message.save()

        text_with_header = insert_response_url_header(
            key=message.key, text=self.cleaned_data['text'])
        message.text = text_with_header

        message.save()

        # send
        bcc_email = None
        if bcc:
            bcc_email = old_message.receiver.email

        try:
            con = SMTPConnection()
            success = con.send_email(
                recipient_address=message.receiver.email,
                subject="Greendoors Communications [House {0}]".format(
                    house_id),
                body=message.text,
                bcc=bcc_email)
        except SMTPRecipientsRefused:
            logger.error("Email sending refused for message {0}".format(
                message.pk))
        if success:
            message.sent = True
            message.save()
Beispiel #23
0
def inviteTeacher(request):
    """
    家长邀请老师,取消邀请
    :param request:
    {
        "tea_id":2,
        "type":1/0
    }
    :return:
    """
    #TODO:消息提醒
    #获取老师id
    tea_id = int(request.data.get("tea_id", -1))
    method = int(request.data.get("type", -1))
    user = AuthUser.objects.get(username=request.user.username)
    parentorders = user.parentorder_set.all()  #查找家长订单
    teachers = Teacher.objects.filter(tea_id=tea_id)  #查找教师
    if len(parentorders) and len(teachers):
        parentorder = parentorders[0]
        teacher = teachers[0]
        if method == 1:
            #家长邀请老师
            #如果家长已经邀请了其他老师,并且未完全,返回错误
            oa = OrderApply.objects.filter(apply_type=2,
                                           pd=parentorder,
                                           finished__in=[0, 2])
            if len(oa) != 0:
                return JsonError(u"您有未完成处理的订单!")
            #如果老师已经报名了该家长
            orders = OrderApply.objects.filter(apply_type=1,
                                               pd=parentorder,
                                               tea=teacher,
                                               finished__in=[0, 2])
            if len(orders):
                return JsonError(u"该老师已经向您报名了!")
            #老师之前拒绝了该家长,家长再次报名老师
            orders = OrderApply.objects.filter(apply_type=2,
                                               pd=parentorder,
                                               tea=teacher,
                                               finished=1)
            if len(orders):
                order = orders[0]
                order.finished = 0
                order.parent_willing = 2
                order.teacher_willing = 1
                order.update_time = timezone.now()
            else:
                order = OrderApply(apply_type=2,
                                   pd=parentorder,
                                   tea=teacher,
                                   parent_willing=2,
                                   teacher_willing=1,
                                   pass_not=1,
                                   update_time=timezone.now(),
                                   finished=0)
            #事务
            try:
                with transaction.atomic():
                    #新建订单
                    order.save()
                    now = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(time.time()))
                    message_title = parentorder.name + u"向您发起了邀请!"
                    message_content = parentorder.name + u"向您发起了邀请!请到“我的家长”处查看详细信息!"
                    #新建消息
                    message = Message(sender=user,
                                      receiver=teacher.wechat,
                                      message_title=message_title,
                                      message_content=message_content,
                                      status=0,
                                      update_time=now,
                                      create_time=now)
                    message.save()
                    #TODO:推送到微信端
                    sendTemplateMessage(
                        teacher,
                        settings.DOMAIN + 'tutor_web/view/myList.html',
                        message_title, message_content, parentorder.name, now)
            except Exception, e:
                return JsonError(e.message)
            return JsonResponse()
        elif method == 0:
            try:
                with transaction.atomic():
                    #取消订单,管理员审核中不能取消
                    orders = OrderApply.objects.filter(apply_type=2,
                                                       pd=parentorder,
                                                       tea=teacher,
                                                       finished=0)
                    if len(orders):
                        order = orders[0]
                        order.delete()
                        now = time.strftime('%Y-%m-%d %H:%M:%S',
                                            time.localtime(time.time()))
                        message_title = parentorder.name + u"取消了邀请!"
                        message_content = parentorder.name + u"取消了邀请!"
                        #新建消息
                        message = Message(sender=user,
                                          receiver=teacher.wechat,
                                          message_title=message_title,
                                          message_content=message_content,
                                          status=0,
                                          update_time=now,
                                          create_time=now)
                        message.save()
                        #TODO:推送到微信端
                        sendTemplateMessage(
                            teacher,
                            settings.DOMAIN + 'tutor_web/view/myList.html',
                            message_title, message_content, parentorder.name,
                            now)
                    else:
                        return JsonError(u"找不到订单!")
            except Exception, e:
                return JsonError(e.message)
            return JsonResponse()
Beispiel #24
0
def handleOrder(request):
    """
    处理订单的各种情况,接受或者拒绝老师的报名或者家长的邀请
    :param request:
     {
     "type": 0/1        0:老师处理家长 1:家长处理老师
     "id":1,            如果是老师处理家长,则填对应的pd_id,如果家长处理老师,则填对应的tea_id
     "accept": 0/1      0/1  0:拒绝 1:接受
     }
    :return:
    """
    type = request.data.get('type', None)
    id = request.data.get('id', None)
    accept = request.data.get('accept', None)
    if (type != None and id != None and accept != None):
        user = AuthUser.objects.get(username=request.user.username)
        #家长处理老师
        if (type):
            parentorders = user.parentorder_set.all()
            teas = Teacher.objects.filter(tea_id=id)
            if (len(parentorders) and len(teas)):
                pd = parentorders[0]
                tea = teas[0]
                orders = OrderApply.objects.filter(tea=tea, pd=pd, finished=0)
                if len(orders):
                    order = orders[0]
                    #对订单进行处理
                    if (accept):
                        order.parent_willing = 2
                        message_title = pd.name + u"接受了你的报名!"
                        message_content = pd.name + u"接受了你的报名!请到“我的家长”处查看详细信息!"
                    else:
                        order.parent_willing = 0
                        order.finished = 1
                        message_title = pd.name + u"拒绝了你的报名!"
                        message_content = pd.name + u"拒绝了你的报名!请到“我的家长”处查看详细信息!"
                    #新建消息
                    now = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(time.time()))
                    message = Message(sender=user,
                                      receiver=tea.wechat,
                                      message_title=message_title,
                                      message_content=message_content,
                                      status=0,
                                      update_time=now,
                                      create_time=now)
                    try:
                        with transaction.atomic():
                            message.save()
                            order.update_time = timezone.now()
                            order.save()
                            #TODO:消息推送到微信端
                            sendTemplateMessage(
                                tea,
                                settings.DOMAIN + 'tutor_web/view/myList.html',
                                message_title, message_content, pd.name, now)
                    except Exception, e:
                        return JsonError(e.message)
                    return JsonResponse()
                else:
                    return JsonError(u"处理错误,请确定数据无误!")
            else:
                return JsonError(u"处理错误,请确定数据无误!")
        else:
            #老师处理家长
            #finished为0
            # 第一种情况:老师处理家长的邀请
            # 第二种情况:老师报名家长后,家长同意后,老师再次处理同意
            #finished为1
            #老师拒绝了家长,再次接受邀请,tea=tea,pd=pd,finished=1,type=2
            teas = user.teacher_set.all()
            parentorders = ParentOrder.objects.filter(pd_id=id)
            if (len(parentorders) and len(teas)):
                pd = parentorders[0]
                tea = teas[0]
                orders = OrderApply.objects.filter(tea=tea, pd=pd, finished=0)
                if len(orders):
                    order = orders[0]
                    result = {}
                    #对订单进行处理
                    if (accept):
                        #老师同意,不应该设为2,应该在获取支付信息的时候改变??
                        order.teacher_willing = 2
                        message_title = tea.name + u"接受了你的邀请!"
                        message_content = tea.name + u"接受了你的邀请!请到“我的老师”处查看详细信息!"
                        payAmount = 50  #支付金额
                        payAccount = 18812341235  #支付账号
                        result = {payAccount: payAccount, payAmount: payAmount}
                    else:
                        order.teacher_willing = 0
                        order.finished = 1
                        message_title = tea.name + u"拒绝了你的邀请!"
                        message_content = tea.name + u"拒绝了你的邀请!请到“我的老师”处查看详细信息!"
                    now = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(time.time()))
                    message = Message(sender=user,
                                      receiver=pd.wechat,
                                      message_title=message_title,
                                      message_content=message_content,
                                      status=0,
                                      update_time=now,
                                      create_time=now)
                    try:
                        with transaction.atomic():
                            message.save()
                            order.update_time = timezone.now()
                            order.save()
                            sendTemplateMessage(
                                pd,
                                settings.DOMAIN + 'tutor_web/view/myList.html',
                                message_title, message_content, tea.name, now)
                        #消息推送到微信端
                    except Exception, e:
                        return JsonError(e.message)
                    return JsonResponse(result)

                else:
                    return JsonError(u"处理错误,请确定数据无误!")
            else:
Beispiel #25
0
def applyParent(request):
    """
    老师报名家长,取消报名
    :param request:
    {
        "pd_id":2,
        "type": 1/0,
        "expectation":""
    }
    :return:
    """
    #获取家长id
    temp = request.data.dict() if (
        type(request.data) != type({})) else request.data
    pd_id = int(temp.get("pd_id", -1))
    method = int(temp.get("type", -1))
    expectation = temp.get("expectation", None)

    user = AuthUser.objects.get(username=request.user.username)
    #查找教师
    teachers = user.teacher_set.all()
    #查找家长订单
    pds = ParentOrder.objects.filter(pd_id=pd_id)
    if len(pds) and len(teachers):
        teacher = teachers[0]
        pd = pds[0]
        if method == 1:
            #老师报名家长,老师可以报名多个家长!!

            #检查家长是否已经邀请该老师,是否已经存在两个人的对应订单
            orders = OrderApply.objects.filter(apply_type=2,
                                               pd=pd,
                                               tea=teacher,
                                               finished__in=[0, 2])
            if len(orders):
                return JsonError(u"该家长已经邀请了您!")

            #家长之前拒绝了该老师,老师再次报名家长
            orders = OrderApply.objects.filter(apply_type=1,
                                               pd=pd,
                                               tea=teacher)
            if len(orders):
                order = orders[0]
                order.finished = 0
                order.parent_willing = 1
                order.teacher_willing = 1
                order.update_time = timezone.now()
                order.expectation = expectation
            else:
                order = OrderApply(apply_type=1,
                                   pd=pd,
                                   tea=teacher,
                                   parent_willing=1,
                                   teacher_willing=1,
                                   pass_not=1,
                                   update_time=timezone.now(),
                                   expectation=expectation,
                                   finished=0)
            #事务
            try:
                with transaction.atomic():
                    #新建订单
                    order.save()
                    message_title = teacher.name + u"向您报名!"
                    message_content = teacher.name + u"向您报名!请到“我的老师”处查看详细信息!"
                    now = time.strftime('%Y-%m-%d %H:%M:%S',
                                        time.localtime(time.time()))
                    #新建消息
                    message = Message(sender=user,
                                      receiver=pd.wechat,
                                      message_title=message_title,
                                      message_content=message_content,
                                      status=0,
                                      update_time=now,
                                      create_time=now)
                    message.save()
                    sendTemplateMessage(
                        pd, settings.DOMAIN + 'tutor_web/view/myList.html',
                        message_title, message_content, teacher.name, now)
                    #TODO:推送到微信端

            except Exception, e:
                return JsonError(e.message)
            return JsonResponse()

        elif method == 0:
            #老师取消报名家长
            try:
                with transaction.atomic():
                    #删除订单
                    orders = OrderApply.objects.filter(apply_type=1,
                                                       pd=pd,
                                                       tea=teacher,
                                                       finished=0)
                    if len(orders):
                        order = orders[0]
                        order.delete()
                        message_title = teacher.name + u"取消了报名!"
                        message_content = teacher.name + u"取消了报名!"
                        now = time.strftime('%Y-%m-%d %H:%M:%S',
                                            time.localtime(time.time()))
                        #新建消息
                        message = Message(sender=user,
                                          receiver=pd.wechat,
                                          message_title=message_title,
                                          message_content=message_content,
                                          status=0,
                                          update_time=now,
                                          create_time=now)
                        message.save()
                        sendTemplateMessage(
                            pd, settings.DOMAIN + 'tutor_web/view/myList.html',
                            message_title, message_content, teacher.name, now)
                    else:
                        return JsonError(u"找不到该订单")
                        #TODO:推送到微信端

            except Exception, e:
                return JsonError(e.message)
            return JsonResponse()
Beispiel #26
0
def create_temperature_message(temperature):
    message = Message()
    message.type = "AC_temperature"
    message.value = temperature
    message.save()
Beispiel #27
0
def create_time_message(time):
    message = Message()
    message.type = "AC_timer"
    message.value = time
    message.save()
Beispiel #28
0
def create_AC_enabled_message(enabled):
    message = Message()
    message.type = "AC_enabled"
    message.value = enabled
    message.save()