コード例 #1
0
def miniprogram_announcement_announcementId_delete(announcementId):
    # 根据announcementId删除announcement和相关的pushMessage
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    announcement = db_session.query(orm.Announcement_db).filter(orm.Announcement_db.id == announcementId).one_or_none()
    pushMessage = db_session.query(orm.PushMessage_db).filter(orm.PushMessage_db.id == announcement.pushMessageId).one_or_none()
    try:
        if announcement.initiatorId == learner.id or learner.isAdmin:
            db_session.delete(announcement)
            db_session.commit()
            if pushMessage:
                db_session.delete(pushMessage)
        else:
            return {'code': -1007, 'message': '需要管理员权限', 'detail': '只有管理员或该活动创建人可以删除该活动'}, 200
        db_session.commit()
        db_session.remove()
        return {'code': 0, 'message': '成功'}, 200
    except Exception as e:
        db_session.remove()
        return {'code': -3005, 'message': '删除通知失败', 'log': str(e)}, 200
コード例 #2
0
def miniprogram_booking_roomCode_get(roomCode, monthToLoad):  # noqa: E501
    # 按房间信息和月份(query中)获取所有的预约信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    responseList = []
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    try:
        room_account = Account(
            primary_smtp_address=('*****@*****.**' % roomCode),
            credentials=credentials,
            config=config
        )
    except Exception as e:
        db_session.remove()
        return {'code': -2002, 'message': '代理用的Office Account初始化失败', "log": str(e)}, 200
    monthToLoad_year = int(monthToLoad.split("-")[0])
    monthToLoad_month = int(monthToLoad.split("-")[1])
    if monthToLoad_month == 1:
        start = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year - 1, 12, 1))
    else:
        start = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year, monthToLoad_month - 1, 1))
    if monthToLoad_month == 11:
        end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year + 1, 1, 1))
    elif monthToLoad_month == 12:
        end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year + 1, 2, 1))
    else:
        end = room_account.default_timezone.localize(EWSDateTime(monthToLoad_year, monthToLoad_month + 2, 1))
    try:
        for item in room_account.calendar.view(start=start, end=end).all().order_by('start'):
            notes = db_session.query(orm.BookingNotes_db).filter(orm.BookingNotes_db.changekey == item.changekey).one_or_none()
            localizedStart = item.start.astimezone(get_localzone())
            localizedEnd = item.end.astimezone(get_localzone())
            bookedByID = getattr(notes, "bookedByID", 0)
            bookedByName = getattr(notes, "bookedByName", "")
            responseList.append({
                'startDate': ("%d-%0*d-%0*d" % (localizedStart.year, 2, localizedStart.month, 2, localizedStart.day)),
                'endDate': ("%d-%0*d-%0*d" % (localizedEnd.year, 2, localizedEnd.month, 2, localizedEnd.day)),
                'startTime': ("%0*d:%0*d" % (2, localizedStart.hour, 2, localizedStart.minute)),
                'endTime': ("%0*d:%0*d" % (2, localizedEnd.hour, 2, localizedEnd.minute)),
                'subject': item.subject,
                'changekey': item.changekey,
                'bookedByID': bookedByID,
                'bookedByName': bookedByName,
                'description': '' if not getattr(item, 'text_body') else getattr(item, 'text_body'),
                'type': 'appointment'
            })
    except Exception as e:
        db_session.remove()
        return {'code': -2003, 'message': '获取房间事件列表失败', 'log': str(e)}, 200
    db_session.remove()
    return {'code': 0, 'data': responseList, 'message': '成功'}, 200
コード例 #3
0
def miniprogram_learner_get():
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    result_list = []
    query: List[orm.Learner_db] = db_session.query(orm.Learner_db).filter(orm.Learner_db.validated == True).all()
    for learner in query:
        result_list.append({
            "id": learner.id,
            "givenName": learner.givenName,
            "familyName": learner.familyName,
            "isMentor": learner.isMentor,
            "role": learner.role,
            "branch": learner.branch
        })
    db_session.remove()
    return {'code': 0, 'data': result_list, 'message': '成功'}, 200
コード例 #4
0
def miniprogram_pushMessage_get(isGetAll: bool = False):
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    response = []
    if isGetAll:
        pushMessageList = db_session.query(orm.PushMessage_db).all()
    else:
        pushMessageList = db_session.query(orm.PushMessage_db).filter(orm.PushMessage_db.expireDateTime > datetime.datetime.utcnow()).all()
    for pushMessage in pushMessageList:
        if util.isRecipient(learner, json.loads(pushMessage.recipients)):
            response.append({
                "id": pushMessage.id,
                "messageType": pushMessage.messageType,
                "entityId": pushMessage.entityId,
                "senderId": pushMessage.senderId,
                "recipients": json.loads(pushMessage.recipients),
                "rsvp": json.loads(pushMessage.rsvp),
                "sentDateTime": EWSDateTime.from_datetime(tzinfo.localize(pushMessage.sentDateTime)).ewsformat(),
                "modifiedDateTime": EWSDateTime.from_datetime(tzinfo.localize(pushMessage.modifiedDateTime)).ewsformat(),
                "expireDateTime": EWSDateTime.from_datetime(tzinfo.localize(pushMessage.expireDateTime)).ewsformat(),
                "content": json.loads(pushMessage.content)
            })
    db_session.remove()
    return {'code': 0, 'data': response, 'message': '成功'}, 200
コード例 #5
0
def miniprogram_announcement_announcementId_get(announcementId):
    # 获取通知的详情
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    announcement = db_session.query(orm.Announcement_db).filter(orm.Announcement_db.id == announcementId).one_or_none()
    try:
        response = {
            "id": announcement.id,
            "initiatorId": announcement.initiatorId,
            "initiatorDisplayName": announcement.initiatorDisplayName,
            "recipients": json.loads(announcement.recipients),
            "sentDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.sentDateTime)).ewsformat(),
            "modifiedDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.modifiedDateTime)).ewsformat(),
            "thumbnail": json.loads(announcement.thumbnail),
            "title": announcement.title,
            "description": announcement.description,
            "body": json.loads(announcement.body),
            "attachment": json.loads(announcement.attachment),
        }
        db_session.remove()
        return {'code': 0, 'data': response, 'message': '成功'}, 200
    except Exception as e:
        db_session.remove()
        return {'code': -5003, 'message': '获取通知详情失败', 'log': str(e)}, 200
コード例 #6
0
def miniprogram_picture_get(uid, pictureType):  # noqa: E501
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    if pictureType not in [
            "event", "announcement", "project", "course", "club"
    ]:
        return {'code': -4001, "message": "图片类别不支持"}, 200
    img_local_path = os.path.join(os.environ["STORAGEURL"], pictureType, uid)
    img_stream = ''
    try:
        with open(img_local_path, 'rb') as img_f:
            img_stream = img_f.read()
            response = make_response(img_stream)
            response.headers['Content-Type'] = 'image'
    except Exception as e:
        db_session.remove()
        return {'code': -4004, 'message': '图片文件读取失败', 'log': str(e)}, 200
    db_session.remove()
    return response, 200
コード例 #7
0
def miniprogram_notification_get(isGetAll: bool = False):
    def constructContent(notification: Notification_db):
        if notification.notificationType == "活动日程":
            event: Event_db = db_session.query(orm.Event_db).filter(
                orm.Event_db.id == notification.entityId).one_or_none()
            return {
                "startDateTime": json.loads(event.eventInfo)["startDateTime"],
                "endDateTime": json.loads(event.eventInfo)["endDateTime"],
                "initiatorId": event.initiatorId,
                "initiatorDisplayName": event.initiatorDisplayName
            }

    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    response = []
    if isGetAll:
        notificationList: List[Notification_db] = db_session.query(
            orm.Notification_db).filter(
                orm.Notification_db.learnerId == learner.id).all()
    else:
        notificationList = db_session.query(orm.Notification_db).filter(
            orm.Notification_db.learnerId == learner.id).filter(
                orm.Notification_db.expireDateTime >
                datetime.datetime.utcnow()).all()
    for notification in notificationList:
        response.append({
            "notificationType":
            notification.notificationType,
            "entityId":
            notification.entityId,
            "createdDateTime":
            EWSDateTime.from_datetime(
                tzinfo.localize(notification.createdDateTime)).ewsformat(),
            "expireDateTime":
            EWSDateTime.from_datetime(
                tzinfo.localize(notification.expireDateTime)).ewsformat(),
            "status":
            notification.status,
            "title":
            notification.title,
            "description":
            notification.description,
            "content":
            constructContent(notification)
        })
    db_session.remove()
    return {'code': 0, 'data': response, 'message': '成功'}, 200
コード例 #8
0
def miniprogram_booking_roomCode_post(roomCode, appointment):  # noqa: E501
    # 添加预约信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    room_account = Account(
        primary_smtp_address=('*****@*****.**' % roomCode),
        credentials=credentials,
        config=config
    )
    startDateTime = room_account.default_timezone.localize(EWSDateTime(
        appointment['startYear'],
        appointment['startMonth'],
        appointment['startDay'],
        appointment['startHour'],
        appointment['startMinute']
    ))
    endDateTime = room_account.default_timezone.localize(EWSDateTime(
        appointment['endYear'],
        appointment['endMonth'],
        appointment['endDay'],
        appointment['endHour'],
        appointment['endMinute']
    ))
    try:
        item = CalendarItem(
            account=room_account,
            folder=room_account.calendar,
            start=startDateTime,
            end=endDateTime,
            subject=appointment['subject'],
            body=appointment['description'],
        )
        item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY)
        db_session.add(orm.BookingNotes_db(
            changekey=item.changekey,
            bookedByID=learner.id,
            bookedByName=learner.familyName + learner.givenName
        ))
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {'code': -2004, 'message': '房间预约失败', 'log': str(e)}, 200
    db_session.remove()
    return {'code': 0, 'message': 'success'}, 200
コード例 #9
0
def miniprogram_announcement_post(announcementPostBody):
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    announcementPostBody_dict = connexion.request.get_json()
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    # 自定义鉴权
    if not learner.isAdmin:
        db_session.remove()
        return {'code': -1007, 'message': '需要管理员权限', "detail": "只有管理员有权限发送通知"}, 200
    try:
        newAnnouncement = orm.Announcement_db(
            initiatorId=learner.id,
            initiatorDisplayName=announcementPostBody_dict['initiatorDisplayName'],
            recipients=json.dumps(announcementPostBody_dict['recipients']),
            sentDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())),
            modifiedDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())),
            expireDateTime=util.EWSDateTimeToDateTime(EWSDateTime.from_string(announcementPostBody_dict["expireDateTime"])),
            thumbnail=json.dumps(announcementPostBody_dict['thumbnail']),
            title=announcementPostBody_dict['title'],
            description=announcementPostBody_dict['description'],
            body=json.dumps(announcementPostBody_dict['body']),
            attachment=json.dumps(announcementPostBody_dict['attachment']),
        )
        db_session.add(newAnnouncement)
        db_session.commit()
        newPushMessage = orm.PushMessage_db(
            messageType="Announcement",
            entityId=newAnnouncement.id,
            senderId=learner.id,
            senderDisplayName=announcementPostBody_dict['initiatorDisplayName'],
            recipients=json.dumps(announcementPostBody_dict['recipients']),
            sentDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())),
            modifiedDateTime=util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())),
            expireDateTime=util.EWSDateTimeToDateTime(EWSDateTime.from_string(announcementPostBody_dict["expireDateTime"])),
            content=json.dumps(announcementPostBody_dict["content"])
        )
        db_session.add(newPushMessage)
        db_session.commit()
        newAnnouncement.pushMessageId = newPushMessage.id
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {'code': -5001, 'message': '创建通知失败', 'log': str(e)}, 200
    response = {'pushMessage_id': newPushMessage.id, 'announcment_id': newAnnouncement.id}
    return {'code': 0, 'data': response, 'message': '成功'}, 200
コード例 #10
0
def miniprogram_picture_post(pictureType: str):  # noqa: E501

    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])

    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.',
                                                   1)[1] in ALLOWED_EXTENSIONS

    def create_uuid():  # 生成唯一的图片的名称字符串,防止图片显示时的重名问题
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
        randomNum = random.randint(0, 100)  # 生成的随机整数n,其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        return uniqueNum

    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    if pictureType not in [
            "event", "announcement", "project", "course", "club"
    ]:
        return {'code': -4001, "message": "图片类别不支持"}, 200
    img = connexion.request.files.get('picture')
    extension = os.path.splitext(img.filename)[-1]
    uid = create_uuid()
    if not allowed_file(img.filename):
        db_session.remove()
        return {'code': -4002, 'message': '文件类型不支持'}, 200
    path = os.path.join(os.environ["STORAGEURL"], pictureType)
    if not os.path.exists(path):
        os.makedirs(path)
    try:
        file_path = os.path.join(path, uid + extension)
        url = uid + extension
        img.save(file_path)
    except Exception as e:
        db_session.remove()
        return {'code': -4003, 'message': '文件储存失败', 'log': str(e)}, 200
    db_session.remove()
    return {'code': 0, 'data': {"url": url}, 'message': '成功'}, 200
コード例 #11
0
def miniprogram_announcement_announcementId_patch(announcementId, announcementPatchBody):
    # 修改通知接口
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    announcementPatchBody_dict = connexion.request.get_json()
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    announcement = db_session.query(orm.Announcement_db).filter(orm.Announcement_db.id == announcementId).one_or_none()
    pushMessage = db_session.query(orm.PushMessage_db).filter(orm.PushMessage_db.id == announcement.pushMessageId).one_or_none()
    try:
        for itemKey in announcementPatchBody_dict:
            if itemKey == "initiatorDisplayName":
                announcement.initiatorDisplayName = announcementPatchBody_dict[itemKey]
            if itemKey == "recipients":
                announcement.recipients = json.dumps(announcementPatchBody_dict[itemKey])
            if itemKey == "thumbnail":
                announcement.thumbnail = json.dumps(announcementPatchBody_dict[itemKey])
            if itemKey == "content":
                pushMessage.content = json.dumps(announcementPatchBody_dict[itemKey])
            if itemKey == "body":
                announcement.body = json.dumps(announcementPatchBody_dict[itemKey])
            if itemKey == "attachment":
                announcement.attachment = json.dumps(announcementPatchBody_dict[itemKey])
            if itemKey == "title":
                announcement.title = announcementPatchBody_dict[itemKey]
            if itemKey == "description":
                announcement.description = announcementPatchBody_dict[itemKey]
            if itemKey == "expireDateTime":
                newExpireDateTime = util.EWSDateTimeToDateTime(EWSDateTime.from_string(announcementPatchBody_dict[itemKey])),
                setattr(pushMessage, itemKey, newExpireDateTime)
        newModifiedDateTime = util.EWSDateTimeToDateTime(account.default_timezone.localize(EWSDateTime.now())),
        pushMessage.modifiedDateTime = newModifiedDateTime
        db_session.commit()
        db_session.remove()
        return {'code': 0, 'message': '成功'}, 200
    except Exception as e:
        db_session.remove()
        return {'code': -5002, 'message': '更新通知失败', 'log': str(e)}, 200
コード例 #12
0
def miniprogram_event_eventId_get(eventId):
    # 获取活动的详情以及相关的rsvp详情
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    event = db_session.query(
        orm.Event_db).filter(orm.Event_db.id == eventId).one_or_none()
    pushMessage = db_session.query(orm.PushMessage_db).filter(
        orm.PushMessage_db.id == event.pushMessageId).one_or_none()
    try:
        response = {
            "id":
            event.id,
            "initiatorId":
            event.initiatorId,
            "initiatorDisplayName":
            event.initiatorDisplayName,
            "eventInfo":
            json.loads(event.eventInfo),
            "invitee":
            json.loads(event.invitee),
            "thumbnail":
            json.loads(event.thumbnail),
            "rsvp":
            json.loads(pushMessage.rsvp),
            "expireDatetime":
            EWSDateTime.from_datetime(tzinfo.localize(
                event.expireDateTime)).ewsformat()
        }
        db_session.remove()
        return {'code': 0, 'data': response, 'message': '成功'}, 200
    except Exception as e:
        db_session.remove()
        return {'code': -3004, 'message': '获取活动详情失败', 'log': str(e)}, 200
コード例 #13
0
def miniprogram_event_eventId_delete(eventId):
    # 根据eventId删除event和相关的pushMessage
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    event = db_session.query(
        orm.Event_db).filter(orm.Event_db.id == eventId).one_or_none()
    pushMessage = db_session.query(orm.PushMessage_db).filter(
        orm.PushMessage_db.id == event.pushMessageId).one_or_none()
    try:
        if event.initiatorId == learner.id or learner.isAdmin:
            db_session.delete(event)
            db_session.commit()
            if pushMessage:
                db_session.delete(pushMessage)
        else:
            return {
                'code': -1007,
                'message': '需要管理员权限',
                'detail': '只有管理员或该活动创建人可以删除该活动'
            }, 200
        db_session.commit()
        notificationToDelete = db_session.query(orm.Notification_db).filter(
            orm.Notification_db.learnerId == learner.id).filter(
                orm.Notification_db.notificationType == "活动日程").filter(
                    orm.Notification_db.entityId == event.id).one_or_none()
        if notificationToDelete:
            db_session.delete(notificationToDelete)
            db_session.commit()
        db_session.remove()
        return {'code': 0, 'message': '成功'}, 200
    except Exception as e:
        db_session.remove()
        return {'code': -3005, 'message': '删除活动失败', 'log': str(e)}, 200
コード例 #14
0
def miniprogram_booking_roomCode_delete(roomCode, monthToLoad, deleteInfo):  # noqa: E501
    # 按照月份、changekey、房间号删除预约信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    changekey = deleteInfo['changekey']
    try:
        room_account = Account(
            primary_smtp_address=('*****@*****.**' % roomCode),
            credentials=credentials,
            config=config
        )
    except Exception as e:
        db_session.remove()
        return {'code': -2002, 'message': '代理用的Office Account初始化失败', "log": str(e)}, 200
    start_year = int(monthToLoad.split("-")[0])
    start_month = int(monthToLoad.split("-")[1])
    start = room_account.default_timezone.localize(EWSDateTime(start_year, start_month, 1))
    if start_month == 12:
        end = room_account.default_timezone.localize(EWSDateTime(start_year + 1, 1, 1))
    else:
        end = room_account.default_timezone.localize(EWSDateTime(start_year, start_month + 1, 1))
    try:
        for item in room_account.calendar.filter(start__range=(start, end)).all().order_by('start'):
            if item.changekey == changekey:
                notes = db_session.query(orm.BookingNotes_db).filter(orm.BookingNotes_db.changekey == item.changekey).one_or_none()
                if notes.bookedByID == learner.id:
                    db_session.delete(notes)
    except Exception as e:
        db_session.remove()
        return {'code': -2005, 'message': '房间预约删除失败', 'error': str(e)}, 200
    db_session.remove()
    return {'code': 0, 'message': 'success'}, 200
コード例 #15
0
def miniprogram_booking_get():
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    if not weapp.getLearner():
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    response = []
    roomLists = json.loads(db_session.query(orm.Config_db).filter(orm.Config_db.name == 'roomLists').one_or_none().value)
    roomDescriptions = json.loads(db_session.query(orm.Config_db).filter(orm.Config_db.name == 'roomDescriptions').one_or_none().value)
    try:
        for roomList in roomLists:
            roomsEWS = GetRooms(protocol=account.protocol).call(
                roomlist=RoomList(
                    email_address=roomList['email'])
            )
            rooms = []
            for room in roomsEWS:
                roomCode = room.email_address.split("@")[0]
                rooms.append({
                    'name': room.name,
                    'roomCode': roomCode,
                    'email': room.email_address,
                    'description': roomDescriptions.get(roomCode, "")
                })
            entry = {
                'listname': roomList['name'],
                'rooms': rooms
            }
            response.append(entry)
    except Exception as e:
        db_session.remove()
        return {'code': -2001, 'message': '获取房间列表失败', "log": str(e)}, 200
    db_session.remove()
    return {'code': 0, 'data': response, 'message': '成功'}, 200
コード例 #16
0
def miniprogram_announcement_get():
    # 获取通知列表,目前暂时默认为返回全部条目
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    try:
        announcementList = db_session.query(orm.Announcement_db).all()
        response = []
        for announcement in announcementList:
            response.append({
                "id": announcement.id,
                "pushMessageId": announcement.pushMessageId,
                "initiatorId": announcement.initiatorId,
                "initiatorDisplayName": announcement.initiatorDisplayName,
                "recipients": json.loads(announcement.recipients),
                "sentDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.sentDateTime)).ewsformat(),
                "modifiedDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.modifiedDateTime)).ewsformat(),
                "expireDateTime": EWSDateTime.from_datetime(tzinfo.localize(announcement.expireDateTime)).ewsformat(),
                "thumbnail": json.loads(announcement.thumbnail),
                "title": announcement.title,
                "description": announcement.description,
                "body": json.loads(announcement.body),
                "attachment": json.loads(announcement.attachment)
            })
        db_session.remove()
    except Exception as e:
        db_session.remove()
        return {'code': -3006, 'message': '获取通知列表失败', 'log': str(e)}, 200
    return {'code': 0, 'data': response, 'message': '成功'}, 200
コード例 #17
0
def getSchedule(dateToLoad: str, nameList=[]):
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {"message": "learner not found"}, 401
    nameList.append(learner.microsoftUserPrincipalName)
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer %s" % getValidMicrosoftToken(learner, db_session),
        "Prefer": 'outlook.timezone="China Standard Time"'
    }
    dateToLoad_year = int(dateToLoad.split("-")[0])
    dateToLoad_month = int(dateToLoad.split("-")[1])
    dateToLoad_day = int(dateToLoad.split("-")[2])
    start = admin_account.default_timezone.localize(EWSDateTime(dateToLoad_year, dateToLoad_month, dateToLoad_day))
    end = start + datetime.timedelta(days=1)
    myScheduleBody = {
        "schedules": nameList,
        "startTime": {
            "dateTime": start.ewsformat()[:19],
            "timeZone": "China Standard Time"
        },
        "endTime": {
            "dateTime": end.ewsformat()[:19],
            "timeZone": "China Standard Time"
        },
        "availabilityViewInterval": "60"
    }
    myScheduleResponse = requests.post("https://graph.microsoft.com/v1.0/me/calendar/getSchedule ", headers=headers, data=json.dumps(myScheduleBody))
    return myScheduleResponse.json()
コード例 #18
0
def miniprogram_event_get(isGetAll: bool = False):
    # 获取活动列表,目前暂时默认为返回全部条目
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    try:
        if isGetAll:
            eventList = db_session.query(orm.Event_db).all()
        else:
            eventList = db_session.query(
                orm.Event_db).filter(orm.Notification_db.expireDateTime >
                                     datetime.datetime.utcnow()).all()
        response = []
        for event in eventList:
            response.append({
                "id": event.id,
                "pushMessageId": event.pushMessageId,
                "initiatorId": event.initiatorId,
                "initiatorDisplayName": event.initiatorDisplayName,
                "eventInfo": json.loads(event.eventInfo),
                "invitee": json.loads(event.invitee),
                "thumbnail": json.loads(event.thumbnail)
            })
        db_session.remove()
    except Exception as e:
        db_session.remove()
        return {'code': -3006, 'message': '获取活动列表失败', 'log': str(e)}, 200
    return {'code': 0, 'data': response, 'message': '成功'}, 200
コード例 #19
0
def miniprogram_event_patch(eventId):
    # 修改活动接口,包括报名的部分
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    eventPatchBody_dict = connexion.request.get_json()
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    event: orm.Event_db = db_session.query(
        orm.Event_db).filter(orm.Event_db.id == eventId).one_or_none()
    pushMessage = db_session.query(orm.PushMessage_db).filter(
        orm.PushMessage_db.id == event.pushMessageId).one_or_none()
    if event.initiatorId != learner.id:
        try:
            newRsvp = json.loads(pushMessage.rsvp) if pushMessage.rsvp else {
                'accept': [],
                'decline': [],
                'tentative': []
            }
            newEntry = {
                'id': learner.id,
                'fullname': learner.familyName + learner.givenName
            }
            # 登记参加的处理逻辑
            if eventPatchBody_dict["rsvp"] == "参加":
                if newEntry not in newRsvp['accept']:
                    newRsvp["accept"].append(newEntry)
                    existingNotification: orm.Notification_db = db_session.query(
                        orm.Notification_db).filter(
                            orm.Notification_db.learnerId == learner.id
                        ).filter(orm.Notification_db.notificationType ==
                                 "活动日程").filter(orm.Notification_db.entityId ==
                                                event.id).one_or_none()
                    if existingNotification:
                        existingNotification.status = "参加"
                    else:
                        newNotification: orm.Notification_db = orm.Notification_db(
                            learnerId=learner.id,
                            notificationType="活动日程",
                            entityId=event.id,
                            createdDateTime=util.EWSDateTimeToDateTime(
                                account.default_timezone.localize(
                                    EWSDateTime.now())),
                            expireDateTime=util.EWSDateTimeToDateTime(
                                EWSDateTime.from_string(
                                    json.loads(
                                        event.eventInfo)["expireDateTime"])),
                            status="参加",
                            title=json.loads(event.eventInfo)["title"],
                            description=json.loads(
                                event.eventInfo)["description"],
                        )
                        db_session.add(newNotification)
                for responseType in ["decline"]:
                    if newEntry in newRsvp[responseType]:
                        newRsvp[responseType].remove(newEntry)
                for responseType in ["tentative"]:
                    if newEntry in newRsvp[responseType]:
                        newRsvp[responseType].remove(newEntry)
            # 登记不参加的处理逻辑
            if eventPatchBody_dict["rsvp"] == "不参加":
                if newEntry not in newRsvp['decline']:
                    newRsvp["decline"].append(newEntry)
                for responseType in ["accept", "tentative"]:
                    if newEntry in newRsvp[responseType]:
                        newRsvp[responseType].remove(newEntry)
                        notificationToDelete = db_session.query(
                            orm.Notification_db).filter(
                                orm.Notification_db.learnerId ==
                                learner.id).filter(
                                    orm.Notification_db.notificationType ==
                                    "活动日程").filter(orm.Notification_db.entityId
                                                   == event.id).one_or_none()
                        if notificationToDelete:
                            db_session.delete(notificationToDelete)
            # 登记待定的处理逻辑
            if eventPatchBody_dict["rsvp"] == "待定":
                if newEntry not in newRsvp['tentative']:
                    newRsvp["tentative"].append(newEntry)
                    existingNotification: orm.Notification_db = db_session.query(
                        orm.Notification_db).filter(
                            orm.Notification_db.learnerId == learner.id
                        ).filter(orm.Notification_db.notificationType ==
                                 "活动日程").filter(orm.Notification_db.entityId ==
                                                event.id).one_or_none()
                    if existingNotification:
                        existingNotification.status = "待定"
                    else:
                        newNotification: orm.Notification_db = orm.Notification_db(
                            learnerId=learner.id,
                            notificationType="活动日程",
                            entityId=event.id,
                            createdDateTime=util.EWSDateTimeToDateTime(
                                account.default_timezone.localize(
                                    EWSDateTime.now())),
                            expireDateTime=util.EWSDateTimeToDateTime(
                                EWSDateTime.from_string(
                                    json.loads(
                                        event.eventInfo)["expireDateTime"])),
                            status="参加",
                            title=json.loads(event.eventInfo)["title"],
                            description=json.loads(
                                event.eventInfo)["description"],
                        )
                        db_session.add(newNotification)
                for responseType in ["decline", "accept"]:
                    if newEntry in newRsvp[responseType]:
                        newRsvp[responseType].remove(newEntry)
            setattr(pushMessage, "rsvp", json.dumps(newRsvp))
            db_session.commit()
        except Exception as e:
            db_session.remove()
            return {'code': -3002, 'message': '更新rsvp信息失败', 'log': str(e)}, 200
        db_session.remove()
        return {'code': 0, 'message': '成功更新rsvp信息'}, 200
    else:
        try:
            for itemKey in eventPatchBody_dict:
                if itemKey == "initiatorDisplayName":
                    event.initiatorDisplayName = eventPatchBody_dict[itemKey]
                if itemKey == "invitee":
                    event.invitee = json.dumps(eventPatchBody_dict[itemKey])
                if itemKey == "thumbnail":
                    event.thumbnail = json.dumps(eventPatchBody_dict[itemKey])
                if itemKey == "content":
                    pushMessage.content = json.dumps(
                        eventPatchBody_dict[itemKey])
                if itemKey in ["title", "description", "fee", "location"]:
                    newEventInfo = json.loads(event.eventInfo)
                    newEventInfo[itemKey] = eventPatchBody_dict[itemKey]
                    event.eventInfo = json.dumps(newEventInfo)
                if itemKey in ["endDateTime", "startDateTime"]:
                    newEventInfo = json.loads(event.eventInfo)
                    newEventInfo[itemKey] = eventPatchBody_dict[itemKey]
                    event.eventInfo = json.dumps(newEventInfo)
                    newPatchDateTime = util.EWSDateTimeToDateTime(
                        EWSDateTime.from_string(eventPatchBody_dict[itemKey])),
                    setattr(pushMessage, itemKey, newPatchDateTime)
                if itemKey == "expireDateTime":
                    newPatchExpireDateTime = util.EWSDateTimeToDateTime(
                        EWSDateTime.from_string(eventPatchBody_dict[itemKey])),
                    setattr(pushMessage, itemKey, newPatchExpireDateTime)
                    setattr(event, "expireDateTime", newPatchExpireDateTime)
            newModifiedDateTime = util.EWSDateTimeToDateTime(
                account.default_timezone.localize(EWSDateTime.now())),
            pushMessage.modifiedDateTime = newModifiedDateTime
            db_session.commit()
            db_session.remove()
            return {'code': 0, 'message': '成功'}, 200
        except Exception as e:
            db_session.remove()
            return {'code': -3003, 'message': '更新活动失败', 'log': str(e)}, 200
コード例 #20
0
def miniprogram_event_post(eventPostBody):
    # 创建活动接口
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    eventPostBody_dict = connexion.request.get_json()
    learner = weapp.getLearner()
    if not learner:
        db_session.remove()
        return {'code': -1001, 'message': '没有找到对应的Learner'}, 200
    # 自定义鉴权
    if not learner.isAdmin:
        if "initiatorDisplayName" in eventPostBody:
            db_session.remove()
            return {
                'code': -1007,
                'message': '需要管理员权限',
                "detail": "非管理员不可自定义发起者名称"
            }, 200
        initiatorDisplayName = learner.familyName + learner.givenName
    else:
        initiatorDisplayName = eventPostBody_dict[
            "initiatorDisplayName"] if "initiatorDisplayName" in eventPostBody_dict else learner.familyName + learner.givenName
    try:
        newEvent = orm.Event_db(
            initiatorId=learner.id,
            initiatorDisplayName=initiatorDisplayName,
            eventInfo=json.dumps(eventPostBody_dict["eventInfo"]),
            invitee=json.dumps(eventPostBody_dict["invitee"]),
            thumbnail=json.dumps(eventPostBody_dict["thumbnail"]),
            expireDateTime=util.EWSDateTimeToDateTime(
                EWSDateTime.from_string(
                    eventPostBody_dict["eventInfo"]["expireDateTime"])))
        db_session.add(newEvent)
        db_session.commit()
        newPushMessage = orm.PushMessage_db(
            messageType="Event",
            entityId=newEvent.id,
            senderId=learner.id,
            senderDisplayName=initiatorDisplayName,
            recipients=json.dumps(eventPostBody_dict["invitee"]),
            rsvp=json.dumps({
                "accept": [],
                "decline": [],
                "tentative": []
            }),
            sentDateTime=util.EWSDateTimeToDateTime(
                account.default_timezone.localize(EWSDateTime.now())),
            modifiedDateTime=util.EWSDateTimeToDateTime(
                account.default_timezone.localize(EWSDateTime.now())),
            expireDateTime=util.EWSDateTimeToDateTime(
                EWSDateTime.from_string(
                    eventPostBody_dict["eventInfo"]["expireDateTime"])),
            content=json.dumps(eventPostBody_dict["content"]))
        db_session.add(newPushMessage)
        db_session.commit()
        newEvent.pushMessageId = newPushMessage.id
        db_session.commit()
        newNotification = orm.Notification_db(
            learnerId=learner.id,
            notificationType="活动日程",
            entityId=newEvent.id,
            createdDateTime=util.EWSDateTimeToDateTime(
                account.default_timezone.localize(EWSDateTime.now())),
            expireDateTime=util.EWSDateTimeToDateTime(
                EWSDateTime.from_string(
                    json.loads(newEvent.eventInfo)["expireDateTime"])),
            title=json.loads(newEvent.eventInfo)["title"],
            description=json.loads(newEvent.eventInfo)["description"])
        db_session.add(newNotification)
        db_session.commit()
        # TODO: 这里应当添加Microsoft Graph API为initiator添加appointment并发送至recipients
    except Exception as e:
        db_session.remove()
        return {'code': -3001, 'message': '活动创建失败', 'log': str(e)}, 200
    response = {"pushMessageId": newPushMessage.id, "id": newEvent.id}
    db_session.remove()
    return {'code': 0, 'data': response, 'message': '成功'}, 200