Ejemplo n.º 1
0
def getPackInfo():
    logger.info("API Handler pack/info")

    try:
        pass
    except Exception:
        return {
            'status': 'error',
            'message': 'Unknown'
        }

    if(session.isAnonymous()):
        return {
            'status': 'error',
            'message': 'Working with packs in anonymous mode is not supported'
        }

    packs, unlocked = postgre.pack.getPacks(session.userID())
    packs = [ postgre.pack.idToHashId(pack_id) for pack_id in packs]

    return {
        'status':'ok',
        'data': {
            'packs': packs,
            'unlocked': unlocked
        }
    }
Ejemplo n.º 2
0
def consulta_ISBN(update, context):
    try:
        estante = context.user_data.get('estante', '-')
        text = update.message.text.strip()
        payload['search'] = text
        logger.info('Recebeu ISBN {}'.format(text))
        r = requests.post(ISBN_URL, json=payload, headers=headers)
        try:
            livro_json = r.json()['value'][0]
        except IndexError:
            livro_json = {
                'RowKey': text,
                'Title': text,
                'Colection': '',
                'Subject': 'ISBN não encontrado',
                'Authors': ''
            }
        livro_json['estante'] = estante
        writer.writerow(livro_json)
        csv_out.flush()
        livro_json_fields = {
            field: livro_json[field]
            for field in [*fields.split(','), 'estante']
        }
        livro_json_fields['Authors'] = ','.join(livro_json_fields['Authors'])
        livro = Livro(**livro_json_fields)
        session.add(livro)
        session.commit()
        reply_text = livro_json['RowKey'] + ' - ' + livro_json['Title']
    except Exception as err:
        reply_text = 'ERRO:' + str(err)
        logger.error(err, exc_info=True)
    update.message.reply_text(reply_text)
Ejemplo n.º 3
0
def signupPostWeb():
    logger.info("API Handler session/signup web version")

    try:
        username = request.json['username']
        password = request.json['password']
        email = request.json['email']
        validation_code = request.json['validation_code']
    except Exception:
        return {
            'status': 'error',
            'message': 'Required: username, password, validation_code, email'
        }

    validation = validate_user(
        username,
        password,
        email,
        validation_code
    )
    if validation is not None:
        return validation

    salt, hashPass = hash.new(password)
    status = postgre.user.signupUser(username, salt, hashPass, email)

    if status['status'] == 'ok':
        session.authorize(username, password)

    return status
def final_grade_sheet_service(class_id: str):
    students_with_score_details = final_grade_sheet(class_id)
    if len(students_with_score_details) == 0:
        logger.info("Could not get any student who took this class")
        return {
            "msg":
            "No student took this class. Please recheck if the class_id is a valid one",
            "status": 400
        }

    logger.info("Students found who took this class")

    for doc in students_with_score_details:
        # correcting some output projections
        for score in doc["details"]:
            score["marks"] = score.pop("score")

        # assigning total to root of every doc for easy sorting
        total = sum([i["marks"] for i in doc["details"]])
        doc["total"] = total

    student_count = len(students_with_score_details)
    students_with_score_details.sort(reverse=True, key=lambda x: x["total"])

    # assigning grades
    for i in range(student_count):
        doc = students_with_score_details[i]
        doc["details"].append({"type": "total", "marks": doc.pop("total")})
        assign_grade(i + 1, student_count, doc)

    result = dict()
    result["class_id"] = int(class_id)
    result["students"] = students_with_score_details
    return result
Ejemplo n.º 5
0
def register_user(username, password):

    check_existing = get_user_credentials(username)
    if check_existing:
        logger.info("authenticate_user()", "register failed because another user with the same username exists")
        return {
            "msg": "username : {0} exists. "
                   "Try some other username as it should be unique !".format(username)
        }

    # creating user in data
    result = create_user(username, encrypt_password(password))

    if not result:
        return {
            "msg": "Unable to create new user. I am sorry !!"
        }

    # generating token
    token = generate_token(username)

    return {
        "msg": "Registered",
        "username": username,
        "token": token
    }
Ejemplo n.º 6
0
def handle_callback_query(query):
    logger.info(query.data)

    # query.answer()
    chat_id = query.message.chat.id

    arr = query.data.split(":")
    query_type, query_value = arr[0], arr[1]

    if query_type == 'download_bilibili_cover':
        # 提取 B 站视频的封面图片
        pic_url = services.get_bilibili_cover_img(query_value)
        bot.send_photo(chat_id=chat_id, photo=pic_url)

    elif query_type == 'download_bilibili_video':
        query.edit_message_text(text="小关正在加速为您下载视频,稍后会将下载链接呈上!!!")

        title = services.download_bilibili_video(query_value)
        logger.debug('Download {}'.format(title))

        download_url = 'https://telegram.pushy.site/download/{}.flv'.format(
            title)
        bot.send_message(chat_id=chat_id,
                         text='下载链接为: {}'.format(download_url))

    elif query_type == 'download_zhihu_video':
        download_url = services.get_zhihu_video_download_url(
            'https://www.zhihu.com/video/{}'.format(query_value))
        query.edit_message_text(text=download_url)
Ejemplo n.º 7
0
def favoriteBlunder():
    logger.info("API Handler blunder/favorite")

    if session.isAnonymous():
        return {
            'status': 'error',
            'message': 'Favorites allowed only for authorized user'
        }

    try:
        blunder_id = request.json['blunder_id']
    except Exception:
        return {'status': 'error', 'message': 'Blunder id required'}

    if not postgre.blunder.favoriteBlunder(session.userID(), blunder_id):
        return {'status': 'error', 'message': "Can't favorite blunder"}

    result = postgre.blunder.getBlunderInfoById(session.userID(), blunder_id)
    if result is None:
        return {
            'status': 'error',
            'message': 'Invalid blunder id',
        }

    return {'status': 'ok', 'data': result}
Ejemplo n.º 8
0
 def run(self):
     try:
         self.result = self.func(*self.args)  # unwrap the arguments
         logger.info(str(self.func), "returned => ", self.result)
     except Exception as e:
         logger.exception(e)
         self.result = -1
Ejemplo n.º 9
0
def sheldon_job():
    global sheldon_old_episode

    resp = requests.get('https://91mjw.com/video/2248.htm')
    element = etree.HTML(resp.text)

    episodes = element.xpath('//*[@id="video_list_li"]/div/a')
    last_episode = episodes[-1].xpath('text()')[0]

    if not sheldon_old_episode:
        # 初始化
        sheldon_old_episode = last_episode

    if sheldon_old_episode != last_episode:
        sheldon_old_episode = last_episode
        # 有新的一集更新了,获取新的一集视频链接
        video_id = episodes[-1].xpath('@id')[0]
        video_link = 'https://91mjw.com/vplay/{}.html'.format(video_id)
        logger.info('更新了: {}'.format(video_link))
        # 推送给所有用户
        ids = models.get_all_user_id()
        print(ids)
        for user_id in ids:
            bot.sendMessage(chat_id=user_id, text=video_link)
    else:
        logger.info('未更新')
Ejemplo n.º 10
0
def validateBlunder():
    logger.info("API Handler blunder/validate")

    try:
        blunder_id = request.json['id']
        user_line = request.json['line']
        spent_time = request.json['spentTime']
        type = request.json['type']
    except Exception:
        return {
            'status': 'error',
            'message': 'Blunder id, user line, spent time and type required'
        }

    if type == const.tasks.RATED:
        return validateRatedBlunder(blunder_id, user_line, spent_time)
    elif type == const.tasks.EXPLORE:
        return validateExploreBlunder(blunder_id, user_line, spent_time)
    elif type == const.tasks.PACK:
        return validatePackBlunder(blunder_id, user_line, spent_time)
    else:
        return {
            'status': 'error',
            'message': 'Blunder type must be explore,rated or pack'
        }
Ejemplo n.º 11
0
def voteBlunderComment():
    logger.info("API Handler comment/vote")

    if session.isAnonymous():
        return {
            'status': 'error',
            'message': 'Voting allowed only for authorized user'
        }

    try:
        blunder_id = request.json['blunder_id']
        comment_id = request.json['comment_id']
        vote = request.json['vote']
    except Exception:
        return {
            'status': 'error',
            'message': 'Blunder id, comment id and vote required'
        }

    if postgre.blunder.blunderCommentAuthor(comment_id) == session.userID():
        return {'status': 'error', 'message': "Can't vote for own comments"}

    if not postgre.blunder.voteBlunderComment(session.userID(), comment_id,
                                              vote):
        return {'status': 'error', 'message': "Can't vote comment"}

    result = postgre.blunder.getBlunderInfoById(session.userID(), blunder_id)
    if result is None:
        return {
            'status': 'error',
            'message': 'Invalid blunder id',
        }

    return {'status': 'ok', 'data': result}
Ejemplo n.º 12
0
    def __init__(self, func_ref, func_args):
        Thread.__init__(self)
        self.func = func_ref
        self.args = func_args
        self.result = None

        logger.info('Thread {0}({1})'.format(func_ref.__name__, *func_args),
                    ' initialized')
def get_student_performance_in_class(class_id: str):
    result = get_studentwise_performance(class_id)
    if result:
        logger.info(len(result), "results returned")
        return {"class_id": class_id, "students": result}
    else:
        logger.info(0, "results returned")
        return {"class_id": int(class_id), "students": []}
def get_students_enrolled(class_id: str):
    result = get_studentwise_info(class_id)
    if result:
        logger.info(len(result), "results returned")
        return {"class_id": int(class_id), "students": result}
    else:
        logger.info(0, "results returned")
        return {"class_id": int(class_id), "students": []}
Ejemplo n.º 15
0
def handle_command(cmd):
    logger.info("handle /{} command".format(cmd))

    if cmd == 'start':
        return start_handler()
    elif cmd == 'help':
        return help_handler()
    else:
        return '未知命令'
Ejemplo n.º 16
0
def sendFeedback():
    logger.info("API Handler feedback/send")

    try:
        message = request.json['message']
    except Exception:
        return {'status': 'error', 'message': 'Message required'}

    return postgre.feedback.saveFeedback(message)
Ejemplo n.º 17
0
def userBlundersCount():
    logger.info("API Handler user/blunders-count")

    try:
        username = request.json['username']
    except Exception:
        return {'status': 'error', 'message': 'Username required'}

    return postgre.user.getBlundersStatistic(username)
Ejemplo n.º 18
0
def getUsersOnline():
    logger.info("API Handler global/users-online")
    
    return {
        'status': 'ok',
        'data': {
            "users-online-list" : postgre.statistic.getActiveUsers('1 HOUR')
        }
    }
Ejemplo n.º 19
0
def getBlundersByDate():
    logger.info("API Handler user/blunders-by-date")

    try:
        username = request.json['username']
        interval = request.json['interval']
    except Exception:
        return {'status': 'error', 'message': 'Username and interval required'}

    return postgre.user.getBlundersByDate(username, interval)
Ejemplo n.º 20
0
 def do_work(self):
     # print(self.file)
     try:
         self.convert_to_xml_tree()
         self.pass_id = int(self.find_pass_value())
         self.guess_id_number()
         self.find_description()
         self.make_new_file_name()
     except Exception as e:
         logger.info(e)
Ejemplo n.º 21
0
def azz_net_job(username):
    latest_pic_url = get_first_page_urls(username)[0]
    # 判断最新一张是否在历史中,如果不在说明为新的作品
    if not redis.sismember(key(username), latest_pic_url):
        # 发现新的作品,推送:
        logger.info('检测到 {} 有新的作品发布'.format(username))
        for user_id in models.get_all_user_id():
            content = '{} 发布了新的作品,图片链接为: \n{}'.format(username, latest_pic_url)
            bot.send_message(chat_id=user_id, text=content)
        redis.sadd(key(username), latest_pic_url)
def get_classes_taken(student_id: str):
    student_details = get_student_details(student_id)
    if len(student_details) == 0:
        logger.info("Could not find any student by the given student id")
        return {
            "msg": "No valid student_id found for the given student_id",
            "status": 400
        }
    logger.info("Student found for the given student id")
    student_details["classes"] = get_classes_taken_by_student(student_id)
    return student_details
Ejemplo n.º 23
0
def getUsersTop():
    logger.info("API Handler global/users-top")

    return {
        'status': 'ok',
        'data': {
            "users-top-by-rating":
            postgre.statistic.getUsersTopByRating(10),
            "users-top-by-activity":
            postgre.statistic.getUsersTopByActivity('1 WEEK', 10),
        }
    }
Ejemplo n.º 24
0
def getUserProfile():
    logger.info("API Handler user/profile")

    try:
        username = request.json['username']
    except Exception:
        return {
            'status': 'error',
            'message': 'Username required'
        }

    return postgre.user.getUserProfile(username)
Ejemplo n.º 25
0
    async def on_connect(self, ws):
        log.info(f'Successfully connected to id {self.vk_id} WebSocket')
        self.task = asyncio.ensure_future(self.task_listener(ws))

        self.alive = True
        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                await self.process_message(ws, msg.data)
            elif msg.type == aiohttp.WSMsgType.ERROR:
                log.warning(f'Got ws error: {msg.data}')
                self.alive = False
                return
Ejemplo n.º 26
0
async def check_transactions():
    current_price = Decimal.from_float(await get_current_price())
    trans = Transaction.select().where(
        Transaction.date_closed.is_null(True)
        & (Transaction.rate_opened < current_price))

    for t in trans:
        price_treshold = t.rate_opened + t.diff
        if current_price > price_treshold:
            profit = t.calculate_profit(current_price)
            message = f'User {t.user.name} need to close his transaction ' \
                      f'#{t.id} to gain {profit:.2f}$'
            logger.info('Transaction #%s should be closed', t.id)
            await send_message(message)
Ejemplo n.º 27
0
    async def get_tasks(self):
        can_run = int(g.stats.get_stats_assoc()['can_draw'])
        data = await r.post(f'{self.url}/c/get-pixels',
                            data={
                                'id': self.id,
                                'expected_count': can_run
                            })

        if data is None:
            return

        if 'pixels' in data and len(data['pixels']) > 0:
            g.task_handler.extend(data['pixels'])
            log.info(f'Retrieved {len(data["pixels"])} tasks from the base.')
Ejemplo n.º 28
0
def getBlundersFavorites():
    logger.info("API Handler user/favorite-blunders")

    try:
        username = request.json['username']
        offset = request.json['offset']
        limit = request.json['limit']
    except Exception:
        return {
            'status': 'error',
            'message': 'Username, offset and limit required'
        }

    return postgre.statistic.getBlundersFavorites(username, offset, limit)
Ejemplo n.º 29
0
def getCommentsByUser():
    logger.info("API Handler user/comments")

    try:
        username = request.json['username']
        offset = request.json['offset']
        limit = request.json['limit']
    except Exception:
        return {
            'status': 'error',
            'message': 'Username, offset and limit required'
        }

    return postgre.statistic.getCommentsByUser(username, offset, limit)
Ejemplo n.º 30
0
def analyzeBlunder():
    logger.info("API Handler blunder/analyze")

    try:
        blunder_id = request.json['blunder_id']
        line = request.json['line']
    except Exception:
        return {
            'status': 'error',
            'message': 'blunder_id and line is required'
        }

    if (session.isAnonymous()):
        return {
            'status': 'error',
            'message': 'Analyzing in anonymous mode is not supported'
        }

    blunder = postgre.blunder.getBlunderById(blunder_id)
    if blunder is None:
        return {'status': 'error', 'message': "Invalid blunder id"}

    blunder_fen = blunder['fen_before']
    blunder_move = blunder['blunder_move']
    forced_line = blunder['forced_line']

    if chess.mismatchCheck(blunder_move, forced_line, line):
        return {
            'status': 'error',
            'message': "Remote database has been changed"
        }

    data = chess.boardsToAnalyze(blunder_fen, blunder_move, forced_line, line)

    data = searchForPreanalyzed(blunder_id, data)

    # No need to start engine process if all needed data known
    if not isAllCalculated(data):
        data = calcualteWithEngine(blunder_id, blunder_fen, data)

    return {
        'status': 'ok',
        'data': {
            'variations': [{
                'line': element['engine']['line'],
                'score': element['engine']['score'],
                'status': element['status']
            } for element in data]
        }
    }