Ejemplo n.º 1
0
def action_add_date_of_completion(): # Завершить задачу(обновить задачу)
	pk = input('id задачи: ')
	with db_session:
		task2 = Task.get(id=pk)
		if not task2:
			print('Задачи под id:{} не существует!'.format(pk))
			return
		tasks = Task[pk]
		task1 = input('Введите дату: ')
		dates2 = [
			'%Y-%m-%d',
			'%Y-%m-%d %H:%M',
			'%Y-%m-%d %H:%M:%S',
			'%d.%m.%Y',
			'%d.%m.%Y %H:%M',
			'%d.%m.%Y %H:%M:%S',
			'%d/%m/%Y',
			'%d/%m/%Y %H:%M',
			'%d/%m/%Y %H:%M:%S'
			]
		for dat in dates2:
			try:
				datetime.strptime(task1, dat)
			except ValueError:
				pass

			else:
				tasks.date_of_completion = task1
				commit()
				print('Задача id:{} завершена.'.format(pk))
				return
		print('Неверный формат даты!')
Ejemplo n.º 2
0
    def __init__(self, path):
        self.path = path

        i = 1
        with open(path) as f:
            for line in f:
                app.log('contrib: {}'.format(i), level=5)
                contribution_record = dict(zip(self.keys, [x.strip() for x in line.split('|')]))

                if contribution_record['STATE'] == 'CA' and contribution_record['CITY'] == 'LONG BEACH':

                    try:
                        this_contrib = Contribution(**contribution_record)
                        this_committee = Committee.get(CMTE_ID=this_contrib.CMTE_ID)
                        this_contrib.committee = this_committee

                        if i % app.BATCH_SIZE == 0:
                            app.log('commit!', level=3)
                            pony.commit()
                    except pony.core.CacheIndexError:
                        pass
                    except pony.core.TransactionIntegrityError:
                        pass
                    
                i += 1

        try:
            pony.commit()
        except pony.core.CacheIndexError:
            pass
        except pony.core.TransactionIntegrityError:
            pass
Ejemplo n.º 3
0
	def post(self):
		self.set_header("Content-type", "application/json")
		with db_session:
			red = Red_Salud.get(**self.form2Dict)
			if red:
				red.set(activo=False); commit()
		self.finish(dumps(red.activo))
Ejemplo n.º 4
0
    def __init__(self, path):
        self.path = path

        i = 1
        with open(path) as f:
            for line in f:
                app.log('committee: {}'.format(i), level=3)
                committee_record = dict(zip(self.keys, [x.strip() for x in line.split('|')]))
                app.log(committee_record, level=5)

                try:
                    Committee(**committee_record)
                    if i % app.BATCH_SIZE == 0:
                        app.log('commit!', level=3)
                        pony.commit()
                except pony.core.CacheIndexError:
                    pass
                except pony.core.TransactionIntegrityError:
                    pass

                i += 1

        try:
            pony.commit()
        except pony.core.CacheIndexError:
            pass
        except pony.core.TransactionIntegrityError:
            pass
Ejemplo n.º 5
0
def get_client_prefs():
    client = request.values['c']
    try:
        request.client = ClientPrefs[request.user, client]
    except ObjectNotFound:
        request.client = ClientPrefs(user = request.user, client_name = client)
        commit()
Ejemplo n.º 6
0
        def add_torrents_from_dir(self, torrents_dir, recursive=False):
            # TODO: Optimize this properly!!!!
            torrents_list = []
            errors_list = []

            if recursive:
                def rec_gen():
                    for root, _, filenames in os.walk(torrents_dir):
                        for fn in filenames:
                            yield os.path.join(root, fn)

                filename_generator = rec_gen()
            else:
                filename_generator = os.listdir(torrents_dir)

            # Build list of .torrents to process
            for f in filename_generator:
                filepath = os.path.join(torrents_dir, f)
                filename = str(filepath) if sys.platform == 'win32' else filepath.decode('utf-8')
                if os.path.isfile(filepath) and filename.endswith(u'.torrent'):
                    torrents_list.append(filepath)

            for chunk in chunks(torrents_list, 100):  # 100 is a reasonable chunk size for commits
                for f in chunk:
                    try:
                        self.add_torrent_to_channel(TorrentDef.load(f))
                    except DuplicateTorrentFileError:
                        pass
                    except:
                        errors_list.append(f)
                orm.commit()  # Kinda optimization to drop excess cache?

            return torrents_list, errors_list
Ejemplo n.º 7
0
def view_draft(id):
    post = orm.select(p for p in Post if p.id == id).get()

    if post is None:
        return abort(404)

    if request.method == "POST":
        post.title = request.form["title"]
        post.content = request.form["content"]
        post.header_image = request.form["header_image"]
        post.header_caption = request.form["header_caption"]

        if post.draft:
            # Only update the slug if the post is a draft.
            post.slug = slugify(post.title)
        elif not post.is_local_header_image():
            post.download_header_image()  # Possible race condition

        resp = {"success": False}

        try:
            orm.commit()
        except CommitException:
            resp["error"] = "Title must be unique"
        else:
            resp["success"] = True

        post.clear_cache()

        return Response(json.dumps(resp),  mimetype='application/json')

    return render_template("edit_post.html",
                           post=post)
Ejemplo n.º 8
0
    def compute_role(self):
        up_count = self.up_count
        down_count = self.down_count
        max_count = max(up_count, down_count)
        delta = abs(up_count - down_count)
        ratio = max_count / delta

        if ratio < 2 and max_count == down_count:
            self.role = "down"
        else:
            self.role = "up"
        if ratio > 6:
            self.role = "dispute"
        if self.role == "up" and self.reply_count > 20 and self.reply_hits > 60:
            self.role = "hot"

            if not m.Bill.get(user_id=self.author.id, role="reply-hot", reply_id=self.id):
                self.author.income(coin=config.reply_hot_coin, role="reply-hot", reply_id=self.id)
                bank = m.Bank.get_one()
                bank.spend(coin=config.reply_hot_coin, role="reply-hot", reply_id=self.id)
        if self.report_count > 12 and self.up_count < 5:
            self.role = "report"

            if not m.Bill.get(user_id=self.author.id, role="reply-report", reply_id=self.id):
                self.author.spend(coin=config.reply_report_coin, role="reply-report", reply_id=self.id)
                bank = m.Bank.get_one()
                bank.income(coin=config.reply_report_coin, role="reply-report", reply_id=self.id)

        try:
            orm.commit()
        except:
            pass
Ejemplo n.º 9
0
 def get(self):
     page = force_int(self.get_argument('page', 1), 1)
     user_id = force_int(self.get_argument('user_id', 0), 0)
     action = self.get_argument('action', None)
     current_user = self.current_user
     user = User.get(id=user_id)
     if not user:
         category = self.get_argument('category', 'all')
         return self.render("user/message_box.html",
                            category=category, page=page)
     message_box = current_user.get_message_box(user=user)
     if action == "read":
         message_box.status = 1
         return self.write({"status": "success", "message": "已读"})
     if not message_box:
         result = {"status": "error", "message": "无此私信"}
         return self.send_result(result)
     form = MessageForm()
     self.render("user/message.html", user=user, message_box=message_box,
                 form=form, page=page)
     if message_box.status == 0:
         message_box.status = 1
         try:
             orm.commit()
         except:
             pass
def save(t):
    try:
        _ = Tweet(text=t)
        commit()
        return True
    except CommitException:
        return False
Ejemplo n.º 11
0
	def post(self):
		self.set_header('Content-type', 'application/json')
		with db_session:
			et = Etnia.get(**self.form2Dict)
			if et:
				et.set(activo=False); commit()
		self.finish(dumps(et.activo))
Ejemplo n.º 12
0
 def remove(self):
     self.delete()
     try:
         orm.commit()
     except Exception:
         pass
     return self
Ejemplo n.º 13
0
def checkstoryvoting(story_ids):
    orm.sql_debug(False)

    if not current_app.story_voting:
        print('Story voting is disabled.')
        return

    if not story_ids:
        with orm.db_session:
            first_story = orm.select(orm.min(x.id) for x in Story).first()
            last_story = orm.select(orm.max(x.id) for x in Story).first()
        story_id = first_story
    else:
        story_ids_queue = story_ids[::-1]  # reversed

    while True:
        with orm.db_session:
            if not story_ids:
                stories = Story.select(lambda x: x.id >= story_id and x.id <= last_story).order_by(Story.id)[:50]
                if not stories:
                    break
            else:
                if not story_ids_queue:
                    break
                stories = list(Story.select(lambda x: x.id in story_ids_queue[-50:]).order_by(Story.id))
                story_ids_queue = story_ids_queue[:-50]
                if not stories:
                    continue

            changed_stories = []

            for story in stories:
                print('Story {}:'.format(story.id), end=' ', flush=True)
                old_count = story.vote_total  # TODO: rename to story.vote_count
                old_value = story.vote_value
                old_extra = story.vote_extra

                current_app.story_voting.update_rating(story)

                new_count = story.vote_total
                new_value = story.vote_value
                new_extra = story.vote_extra

                print('{} -> {}'.format(old_value, new_value), end='', flush=True)

                if old_count != new_count or old_value != new_value or json.loads(old_extra) != json.loads(new_extra):
                    print(' (changed)')
                    changed_stories.append(story)
                else:
                    print('')

            print('Saving...', end=' ', flush=True)
            for story in changed_stories:
                story.bl.search_update(update_fields={'vote_total', 'vote_value'})
            orm.commit()
            print('Done.', flush=True)

            if not story_ids:
                story_id = stories[-1].id + 1
Ejemplo n.º 14
0
 def run_command_add( self, request ):
     public_key = PublicKey.from_der(request.params.public_key_der)
     rec = this_module.User(user_name=request.params.user_name,
                            public_key_pem=public_key.to_pem())
     commit()  # make rec.id
     diff = self.Diff_add_one(self.rec2element(rec))
     subscription.distribute_update(self.iface, self.get_path(), diff)
     return self.ListHandle(self, key=rec.id)
Ejemplo n.º 15
0
Archivo: views.py Proyecto: iamsk/brat
 def post(self, *args, **kwargs):
     email = self.get_argument('email', None)
     password = self.get_argument('password', None)
     if not email or not password:
         raise exceptions.BadRequest
     user = User(email=email, password=password)
     commit()
     return user
Ejemplo n.º 16
0
def delete_post(id):
    post = orm.select(p for p in Post if p.id == id).get()
    post.delete()
    orm.commit()

    if "redirect" in request.form:
        return redirect(request.form["redirect"])

    return redirect(url_for('index'))
Ejemplo n.º 17
0
 def set_lastfm_method(self, method, args, content):
     """
     Store last.fm method response in database
     Works with expiration date.
     """
     with db_session:
         dt = self.get_dt()
         _ = LastFmCache(method_args=method + args, created_at=dt, updated_at=dt, content=content)
         commit()
Ejemplo n.º 18
0
	def post(self):
		self.set_header('Content-type', 'application/json')
		form = self.form2Dict
		with db_session:
			ct = Control.get(id_cnt=form.id_cnt)
			if ct:
				del form['id_cnt']; form.asistido = eval(form.asistido)
				ct.set(**form); commit()
		self.finish(dumps(True if ct else False))
Ejemplo n.º 19
0
 def test_recent(self):
     item = Item[self.item.id]
     item2 = Item[self.item2.id]
     item.checked_out = True
     item2.checked_out = False
     orm.commit()
     res = self.client.get("/api/v1/recentcheckouts/")
     assert_in(ItemSerializer(item).data, res.json['items'])
     assert_not_in(ItemSerializer(item2).data, res.json['items'])
Ejemplo n.º 20
0
	def post(self):
		if self.current_user.rol == u'Administrador':
			self.set_header("Content-type", "application/json")
			with db_session:
				red = Red_Salud.get(**self.form2Dict())
				if red:
					red.set(activo=False)
					commit()
			self.finish(dumps(red.activo))
Ejemplo n.º 21
0
	def post(self):
		with db_session:
			ubicado = Comunidad.get(id_com=self.get_arguments('id_com')[0])
			cs = Centro_Salud(tipo=self.get_argument('tipo'),nombre=self.get_argument('nombre'),ubicado=ubicado)
			cs.comunidades += [Comunidad.get(id_com=id_com) for id_com in self.get_arguments('id_com')[1:]]
			cs.comunidades += [ubicado]
			cs.prestaciones += [Prestacion.get(id_pst=id_pst) for id_pst in self.get_arguments('id_pst')]
			commit()
		self.redirect('/centros_salud/gestion?id_com={}'.format(ubicado.id_com))
Ejemplo n.º 22
0
def mark_topic():
    db.bind('mysql', **settings.get('DB'))
    db.generate_mapping()
    print('connect to db!')

    with db_session:
        print('select items!')

        estates = EstateQ2Entity.select(lambda e: e.topic == None).order_by(EstateQ2Entity.id)
        for estate in estates:

            raw_json = estate.seg_freq
            seg_freq = json.loads(raw_json)
            
            topic = 0

            if check_topic1(seg_freq):
                topic = topic | TOPIC1

            if check_topic2(seg_freq):
                topic = topic | TOPIC2

            if check_topic3(seg_freq):
                topic = topic | TOPIC3

            if check_topic4(seg_freq):
                topic = topic | TOPIC4

            if check_topic5(seg_freq):
                topic = topic | TOPIC5

            if check_topic6(seg_freq):
                topic = topic | TOPIC6

            if check_topic7(seg_freq):
                topic = topic | TOPIC7

            if check_topic8(seg_freq):
                topic = topic | TOPIC8

            if check_topic9(seg_freq):
                topic = topic | TOPIC9

            if check_topic10(seg_freq):
                topic = topic | TOPIC10

            if check_topic11(seg_freq):
                topic = topic | TOPIC11


            estate.topic = topic
            commit()

            if topic != 0:
                print('!!! topic: ', topic)

            print('id: ', estate.id)
Ejemplo n.º 23
0
 def post(self):
     remove_file(get_asset_path(self.current_user.background_img))
     self.current_user.background_img = ''
     try:
         orm.commit()
     except:
         pass
     result = {"status": "success", "message": "已成功重置背景图片"}
     self.send_result(result)
Ejemplo n.º 24
0
 def set_cached_service(self, service_name, content):
     """
     Store service response in database
     Works with expiration date.
     https://github.com/tb0hdan/voiceplay/issues/15
     """
     with db_session:
         dt = self.get_dt()
         _ = ServiceCache(service_name=service_name, created_at=dt, updated_at=dt, content=content)
         commit()
Ejemplo n.º 25
0
 def read_notifications(self):
     notifications = self.unread_notifications
     for n in notifications:
         n.status = 1
     try:
         orm.commit()
     except Exception, e:
         print type(e).__name__
         print e
         raise
Ejemplo n.º 26
0
 def delete(self, id):
     '''Delete an item.'''
     try:
         item = Item[id]
     except orm.ObjectNotFound:
         abort(404)
     item.delete()
     orm.commit()
     return jsonify({"message": "Successfully deleted item.",
                     "id": id}), 200
Ejemplo n.º 27
0
Archivo: pony.py Proyecto: CMLL/mixer
    def postprocess(self, target):
        """ Save objects in db.

        :return value: A generated value

        """
        if self.params.get('commit'):
            commit()

        return target
Ejemplo n.º 28
0
 def delete(self, id):
     '''Delete a person.'''
     try:
         person = Person[id]
     except orm.ObjectNotFound:
         abort(404)
     person.delete()
     orm.commit()
     return jsonify({"message": "Successfully deleted person.",
                     "id": id}), 200
Ejemplo n.º 29
0
 def post(self):
     '''Insert a new person.'''
     data = request.json
     firstname = data.get("firstname")
     lastname = data.get("lastname")
     if not firstname or not lastname:
         abort(400)  # Must specify both first and last name
     person = Person(firstname=firstname, lastname=lastname)
     orm.commit()
     return jsonify({"message": "Successfully added new person.",
                     "person": PersonSerializer(person).data}), 201
Ejemplo n.º 30
0
 def do_save( self, request, text ):
     if self.article_id is not None:
         article_rec = this_module.Article[self.article_id]
         article_rec.text = text
     else:
         article_rec = this_module.Article(text=text)
     commit()
     self.article_id = article_rec.id  # now may have new get_path()
     log.info('Article is saved, article_id = %r', self.article_id)
     subscription.distribute_update(self.iface, self.get_path(), text)
     return request.make_response_result(new_path=self.get_path())
Ejemplo n.º 31
0
    async def _bulk_import(self, ctx: SlashContext):
        await ctx.defer()

        author_id = ctx.author_id
        self.logger.info(
            f"trying to import by request of member: %d",
            author_id,
        )

        csvcontent = None
        try:
            async for msg in ctx.channel.history(limit=5):
                if (msg.author.id == author_id and len(msg.attachments) > 0
                        and msg.attachments[0].filename.endswith(".csv")):
                    csvcontent = io.BytesIO()
                    await msg.attachments[0].save(csvcontent)

        except (
                discord.Forbidden,
                discord.HTTPException,
                discord.NotFound,
                TypeError,
                ValueError,
        ) as e:
            self.logger.warning(
                e,
                exc_info=True,
            )
            return await ctx.send(
                content=
                "Couldn't find message with CSV file to import. Aborting.",
                hidden=True,
            )

        if csvcontent is None:
            return await ctx.send(
                content=
                "Couldn't find message with CSV file to import. Aborting.",
                hidden=True,
            )

        added = 0
        updated = 0

        csvreader = csv.reader(io.StringIO(csvcontent.read().decode("utf-8")),
                               quoting=csv.QUOTE_MINIMAL)
        for row in csvreader:
            topic, new = db.upsert_topic(str(ctx.guild.id), row[0], row[1],
                                         row[2], row[3],
                                         row[4] if len(row) == 5 else "")
            if new:
                added += 1
            else:
                updated += 1

        # TODO: remove this and figure out how to make @db_session work with async
        commit()
        self.bot.loop.create_task(self.__sync_wiki_command(ctx.guild.id))

        await ctx.send(
            content=
            f"Import was successfuly finished! **{added}** added and **{updated}** updated.",
        )
Ejemplo n.º 32
0
    def make_object(self, data):
        model = self.opts.model

        instance = model(**data)
        commit()
        return instance
Ejemplo n.º 33
0
def reply(msg):
    global restrictedMode
    chatId = msg['chat']['id']
    name = msg['from']['first_name']
    text = msg.get("text", "")

    if chatId < 0:
        return

    if not User.exists(lambda u: u.chatId == chatId):
        User(chatId=chatId)
    if not Data.exists(lambda u: u.chatId == chatId):
        Data(chatId=chatId)
    if not ParsedData.exists(lambda u: u.chatId == chatId):
        ParsedData(chatId=chatId)
    if not Settings.exists(lambda u: u.chatId == chatId):
        Settings(chatId=chatId)

    user = User.get(chatId=chatId)
    userdata = Data.get(chatId=chatId)
    stored = ParsedData.get(chatId=chatId)

    if (not restrictedMode) or helpers.isAdmin(chatId):
        if text == "/about":
            bot.sendMessage(
                chatId, "ℹ️ <b>Informazioni sul bot</b>\n"
                "ClasseVivaBot è un bot creato e sviluppato da Filippo Pesavento, che ti può aiutare "
                "durante l'anno scolastico mandando notifiche per le novità del registro e molto altro.\n"
                "Prova ad usarlo per scoprire quanto è comodo!\n\n"
                "<b>Sviluppo:</b> <a href=\"https://t.me/pesaventofilippo\">Filippo Pesavento</a> e Francesco De Benedittis\n"
                "<b>Contributori:</b> Gianluca Parri e PolpOnline\n"
                "<b>Hosting:</b> Filippo Pesavento\n\n"
                "<b>Info sicurezza:</b> /aboutprivacy",
                parse_mode="HTML",
                disable_web_page_preview=True)

        elif text == "/aboutprivacy":
            bot.sendMessage(
                chatId, "ℹ️ <b>Informazioni sulla privacy</b>\n"
                "La mia password è al sicuro? 🤔\n\n"
                "🔐 <b>Sì: la tua password viene criptata.</b>\n"
                "Il bot conserva la tua password in maniera sicura, salvandola in un formato non leggibile da "
                "persone estranee. Sei al sicuro: i tuoi dati non verranno visti nè rubati da nessuno!\n\n"
                "🔐 <b>Spiegazione dettagliata:</b>\n"
                "Tecnicamente potrei decriptare a mano le password e vederle, ma sostanzialmente è complicato, "
                "perchè il bot genera una chiave per l'algoritmo (visto che il cripting deve essere reversibile, "
                "per poter mandare le notifiche automatiche) prendendo come dati una chiave comune (che salvo nella RAM, "
                "per evitare che qualcuno che non sia io possa leggere il database e i dati degli utenti) "
                "e anche l'username dell'utente. Quindi ogni utente ha la propria password criptata con una chiave diversa da tutti "
                "gli altri, e sarebbe difficile anche per me risalire alla password, dovendo sapere di chi è l'username collegato a "
                "quella password specifica.\n"
                "Questo non vuol dire che non possa farlo: con un po' di lavoro ci riuscirei. Quindi alla fine devi decidere tu: "
                "io ti posso assicurare che non leggerò mai nè proverò mai a decriptare le password, sia per un discorso di etica "
                "che per scelta personale, ma non sono tuo amico nè tuo conoscente: quindi se decidi di non fidarti di uno sconosciuto "
                "che ti scrive su Telegram (ti posso capire benissimo) sei libero di non usare il bot 🙂\n\n"
                "<a href=\"https://kutt.it/botinfo\">Altre info & Privacy Policy</a>\n"
                "<a href=\"https://t.me/pesaventofilippo\">Contattami</a>\n\n"
                "<i>Se sei venuto qui prima di digitare la password per il login, scrivila adesso!</i>",
                parse_mode="HTML",
                disable_web_page_preview=True)

        elif user.status != "normal":
            if text == "/annulla":
                user.status = "normal"
                bot.sendMessage(chatId, "Comando annullato!")

            elif user.status == "login_0":
                if len(text) < 5:
                    bot.sendMessage(
                        chatId,
                        "⚠️ Errore: l'username è troppo corto. Riprova!")
                    return
                user.username = text
                user.status = "login_1"
                bot.sendMessage(
                    chatId, "👍 Ottimo. Adesso inviami la password.\n"
                    "Ricorda che la password viene salvata solo per te e viene criptata, nessuno potrà leggerla.\n\n"
                    "Sei preoccupato per la sicurezza della password? /aboutprivacy"
                )

            elif user.status == "login_1":
                user.password = crypt_password(text, chatId)
                user.status = "normal"
                commit()
                api = ClasseVivaAPI()

                try:
                    api.login(user.username, decrypt_password(chatId))
                except ApiServerError:
                    try:
                        bot.sendMessage(
                            chatId,
                            "⚠️ I server di ClasseViva non sono raggiungibili.\n"
                            "Riprova tra qualche minuto.")
                    except (TelegramError, BotWasBlockedError):
                        pass
                    return
                except Exception:
                    helpers.clearUserData(chatId)
                    try:
                        bot.sendMessage(
                            chatId,
                            "😯 Le tue credenziali di accesso sono errate.\n"
                            "Effettua nuovamente il /login per favore.")
                    except (TelegramError, BotWasBlockedError):
                        pass
                    return

                bot.sendMessage(
                    chatId, "Fatto 😊\n"
                    "Premi /help per vedere la lista dei comandi disponibili.")
                sent = bot.sendMessage(chatId, "🔍 Aggiorno il profilo...")
                data = helpers.fetchStrict(api)
                helpers.updateUserdata(chatId, data)
                helpers.fetchAndStore(chatId, api, data, fetch_long=True)
                bot.editMessageText((chatId, sent['message_id']),
                                    "✅ Profilo aggiornato!")

            elif user.status == "calling_support":
                user.status = "normal"
                for a in helpers.isAdmin():
                    bot.sendMessage(
                        a,
                        "🆘 <b>Richiesta di aiuto</b>\n"
                        "Da: <a href=\"tg://user?id={0}\">{1}</a>\n\n"
                        "<i>Rispondi al messaggio per parlare con l'utente.</i>"
                        .format(chatId, name),
                        parse_mode="HTML")
                    if "reply_to_message" in msg:
                        bot.forwardMessage(
                            a, chatId, msg["reply_to_message"]["message_id"])
                    bot.forwardMessage(a,
                                       chatId,
                                       msg['message_id'],
                                       disable_notification=True)
                bot.sendMessage(chatId, "<i>Richiesta inviata.</i>\n"
                                "Un admin ti risponderà il prima possibile.",
                                parse_mode="HTML")

            elif user.status == "sending_orario":
                if msg.get("photo"):
                    fileId = msg.get("photo")[0]["file_id"]
                    ext = "photo"
                elif msg.get("document"):
                    fileId = msg.get("document")["file_id"]
                    ext = "document"
                else:
                    bot.sendMessage(
                        chatId,
                        "🤔 Documento non valido. Invia una foto o un file.\n"
                        "Premi /annulla per annullare.")
                    return

                if not Document.exists(
                        lambda d: (d.chatId == chatId and d.type == "orario")):
                    Document(chatId=chatId,
                             type="orario",
                             data={
                                 "fileId": fileId,
                                 "ext": ext
                             })
                else:
                    doc = Document.get(chatId=chatId, type="orario")
                    doc.data = {"fileId": fileId, "ext": ext}
                bot.sendMessage(
                    chatId, "✅ Orario impostato!\n"
                    "Richiamalo con /orario.")
                user.status = "normal"

            elif user.status == "memo_date":
                if not text:
                    bot.sendMessage(
                        chatId, "Inviami la data in formato GG/MM.\n"
                        "Premi /annulla per annullare.")
                    return

                try:
                    now = datetime.now()
                    when = datetime.strptime(text, "%d/%m")
                    when.replace(year=now.year)

                    if when < now:
                        when.replace(year=now.year + 1)
                    if when > now + timedelta(days=28):
                        bot.sendMessage(
                            chatId, "⚠️ Data non valida.\n"
                            "La data non può essere oggi, nel passato oppure fra più di 4 settimane.\n"
                            "Premi /annulla per annullare.")
                        return

                    memoDate = when.strftime("%d/%m/%Y")
                    user.status = f"memo_text#{memoDate}"

                    bot.sendMessage(
                        chatId, f"💡 <b>Data memo: {memoDate}</b>\n"
                        f"Inviami il testo del memo, o premi /annulla per annullare.",
                        parse_mode="HTML")
                except ValueError:
                    bot.sendMessage(
                        chatId, "⚠️ Data non valida.\n"
                        "Inviami la data in formato GG/MM.\n"
                        "Premi /annulla per annullare.")

            elif user.status.startswith("memo_text"):
                if not text or len(text) > 400:
                    bot.sendMessage(
                        chatId,
                        "⚠️ Inviami il testo della memo (max. 400 caratteri).\n"
                        "Premi /annulla per annullare.")
                    return

                memoDate = user.status.split("#")[1]
                memo = Document(chatId=chatId,
                                type="memo",
                                data={
                                    "date": memoDate,
                                    "text": text
                                })

                user.status = "normal"
                stored.agenda = parsers.parseAgenda(userdata.agenda, chatId)
                stored.domani = parsers.parseDomani(userdata.agenda, chatId)
                bot.sendMessage(
                    chatId,
                    f"✅ Ho creato la memo per il <b>{memo.data['date']}</b>:\n"
                    f"\"{memo.data['text']}\"\n\n"
                    f"Vedilo in /agenda!",
                    parse_mode="HTML")

        elif text == "/help":
            bot.sendMessage(
                chatId, "Ciao, sono il bot di <b>ClasseViva</b>! 👋🏻\n"
                "Posso aiutarti a <b>navigare</b> nel registro e posso mandarti <b>notifiche</b> quando hai nuovi avvisi.\n\n"
                "<b>Lista dei comandi</b>:\n"
                "- /login - Effettua il login\n"
                "- /aggiorna - Aggiorna manualmente tutti i dati, per controllare se ci sono nuovi avvisi.\n"
                "Oppure, puoi lasciarlo fare a me ogni mezz'ora :)\n"
                "- /agenda - Visualizza agenda (compiti e verifiche)\n"
                "- /domani - Vedi i compiti che hai per domani\n"
                "- /promemoria - Vedi un promemoria con i compiti da fare per domani e le lezioni svolte oggi.\n"
                "- /memo - Aggiungi un memo all'agenda\n"
                "- /voti - Visualizza la lista dei voti\n"
                "- /lezioni - Visualizza la lista delle lezioni\n"
                "- /didattica - Visualizza la lista dei file in didattica\n"
                "- /circolari - Visualizza le circolari da leggere\n"
                "- /orario - Imposta o visualizza l'orario delle lezioni\n"
                "- /settings - Modifica le impostazioni personali del bot\n"
                "- /assenze - Visualizza assenze, ritardi e uscite anticipate\n"
                "- /note - Visualizza la lista delle note\n"
                "- /info - Visualizza le tue info utente\n"
                "- /prof - Visualizza la lista delle materie e dei prof\n"
                "- /about - Informazioni sul bot\n"
                "- /aboutprivacy - Più informazioni sulla privacy\n"
                "- /logout - Disconnettiti\n"
                "- /support - Contatta lo staff (emergenze)\n\n"
                "<b>Notifiche</b>: ogni mezz'ora, se vuoi, ti invierò un messaggio se ti sono arrivati nuovi voti, note, compiti, materiali, avvisi o circolari.\n"
                "<b>Impostazioni</b>: con /settings puoi cambiare varie impostazioni, tra cui l'orario delle notifiche, quali notifiche ricevere e se riceverle di notte."
                "",
                parse_mode="HTML")

        elif text.startswith("/broadcast ") and helpers.isAdmin(chatId):
            bdText = text.split(" ", 1)[1]
            pendingUsers = select(u.chatId for u in User)[:]
            userCount = len(pendingUsers)
            for u in pendingUsers:
                try:
                    bot.sendMessage(u,
                                    bdText,
                                    parse_mode="HTML",
                                    disable_web_page_preview=True)
                except (TelegramError, BotWasBlockedError):
                    userCount -= 1
            bot.sendMessage(
                chatId,
                "📢 Messaggio inviato correttamente a {0} utenti!".format(
                    userCount))

        elif text.startswith("/sendmsg ") and helpers.isAdmin(chatId):
            selId = int(text.split(" ", 2)[1])
            selText = str(text.split(" ", 2)[2])
            bot.sendMessage(selId, selText, parse_mode="HTML")
            bot.sendMessage(chatId,
                            selText + "\n\n- Messaggio inviato!",
                            parse_mode="HTML")

        elif text == "/globalupdate" and helpers.isAdmin(chatId):
            bot.sendMessage(chatId, "🕙 Inizio aggiornamento globale...")
            runUpdates(long_fetch=True)
            bot.sendMessage(chatId, "✅ Aggiornamento globale completato!")

        elif text == "/silentupdate" and helpers.isAdmin(chatId):
            bot.sendMessage(chatId, "🕙 [BG] Inizio aggiornamento globale...")
            runUpdates(long_fetch=True, sendMessages=False)
            bot.sendMessage(chatId, "✅ [BG] Aggiornamento globale completato!")

        elif text == "/users" and helpers.isAdmin(chatId):
            totalUsers = len(select(u for u in User)[:])
            loggedUsers = len(select(u for u in User if u.password != "")[:])
            bot.sendMessage(chatId,
                            "👤 Utenti totali: <b>{}</b>\n"
                            "👤 Utenti loggati: <b>{}</b>".format(
                                totalUsers, loggedUsers),
                            parse_mode="HTML")

        elif text == "/restrict" and helpers.isAdmin(chatId):
            restrictedMode = True
            bot.sendMessage(chatId, "<i>Modalità ristretta attiva.\n"
                            "Solo gli admin possono usare il bot.</i>",
                            parse_mode="HTML")

        elif text == "/unrestrict" and helpers.isAdmin(chatId):
            restrictedMode = False
            bot.sendMessage(chatId, "<i>Modalità ristretta disattivata.\n"
                            "Tutti gli utenti potranno usare il bot.</i>",
                            parse_mode="HTML")

        elif "reply_to_message" in msg:
            if helpers.isAdmin(chatId):
                try:
                    userId = msg['reply_to_message']['forward_from']['id']
                    bot.sendMessage(userId,
                                    "💬 <b>Risposta dello staff</b>\n"
                                    "{0}".format(text),
                                    parse_mode="HTML")
                    bot.sendMessage(chatId, "Risposta inviata!")
                except Exception:
                    bot.sendMessage(chatId, "Errore nell'invio.")
            else:
                if text.lower() == "no":
                    bot.sendMessage(chatId,
                                    "<i>Ah ok, scusa.</i>",
                                    parse_mode="HTML")
                else:
                    bot.sendMessage(
                        chatId, "Scrivi /support per parlare con lo staff.")

        elif text == "/annulla":
            bot.sendMessage(chatId, "😴 Nessun comando da annullare!")

        elif helpers.hasStoredCredentials(chatId):
            if text == "/start":
                bot.sendMessage(chatId,
                                "Bentornato, <b>{0}</b>!\n"
                                "Cosa posso fare per te? 😊".format(name),
                                parse_mode="HTML")

            elif text == "/login":
                bot.sendMessage(
                    chatId, "Sei già loggato.\n"
                    "Premi /logout per uscire.")

            elif text == "/logout":
                bot.sendMessage(
                    chatId,
                    "Tutti i tuoi dati scolastici e le credenziali verranno eliminate dal bot.\n"
                    "Sei <b>veramente sicuro</b> di voler uscire?",
                    parse_mode="HTML",
                    reply_markup=keyboards.logout())

            elif text == "/didattica":
                helpers.sendLongMessage(
                    chatId,
                    "📚 <b>Files caricati in didattica</b>:\n\n"
                    "{0}".format(stored.didattica),
                    parse_mode="HTML",
                    disable_web_page_preview=True)

            elif text == "/info":
                bot.sendMessage(chatId,
                                "ℹ️ <b>Ecco le tue info</b>:\n\n"
                                "{0}".format(stored.info),
                                parse_mode="HTML")

            elif text == "/prof":
                helpers.sendLongMessage(chatId,
                                        "📚 <b>Lista materie e prof</b>:\n\n"
                                        "{0}".format(stored.prof),
                                        parse_mode="HTML")

            elif text == "/note":
                helpers.sendLongMessage(chatId,
                                        "❗️<b>Le tue note</b>:\n\n"
                                        "{0}".format(stored.note),
                                        parse_mode="HTML")

            elif text == "/voti":
                helpers.sendLongMessage(chatId,
                                        "📝 <b>I tuoi voti</b>:\n\n"
                                        "{0}".format(stored.voti),
                                        parse_mode="HTML")

            elif text == "/assenze":
                helpers.sendLongMessage(chatId,
                                        "{0}".format(stored.assenze),
                                        parse_mode="HTML")

            elif text == "/agenda":
                bot.sendMessage(
                    chatId,
                    "📆 <b>Agenda compiti per le prossime 2 settimane</b>:\n\n"
                    "{0}".format(stored.agenda),
                    parse_mode="HTML",
                    disable_web_page_preview=True)

            elif text == "/domani":
                isSaturday = datetime.now().isoweekday() == 6
                dayString = "lunedì" if isSaturday else "domani"
                bot.sendMessage(chatId,
                                "📆 <b>Compiti e verifiche per {0}</b>:\n\n"
                                "{1}".format(dayString, stored.domani),
                                parse_mode="HTML",
                                disable_web_page_preview=True)

            elif text == "/circolari":
                bot.sendMessage(chatId,
                                "📩 <b>Circolari da leggere</b>:\n\n"
                                "{0}".format(stored.circolari),
                                parse_mode="HTML",
                                disable_web_page_preview=True)

            elif text == "/lezioni":
                bot.sendMessage(chatId,
                                "📚 <b>Lezioni di oggi</b>:\n\n"
                                "{0}".format(stored.lezioni),
                                parse_mode="HTML",
                                disable_web_page_preview=True,
                                reply_markup=keyboards.lezioni())

            elif text == "/settings":
                bot.sendMessage(
                    chatId, "🛠 <b>Impostazioni</b>\n"
                    "Ecco le impostazioni del bot. Cosa vuoi modificare?",
                    parse_mode="HTML",
                    reply_markup=keyboards.settings_menu())

            elif text == "/promemoria":
                bot.sendMessage(chatId,
                                "🕙 <b>Promemoria!</b>\n\n"
                                "📆 <b>Cosa devi fare per domani</b>:\n\n"
                                "{0}\n\n\n"
                                "📚 <b>Le lezioni di oggi</b>:\n\n"
                                "{1}".format(stored.domani, stored.lezioni),
                                parse_mode="HTML",
                                disable_web_page_preview=True)

            elif text == "/aggiorna":
                if (user.remainingCalls > 0) or (helpers.isAdmin(chatId)):
                    if not updateLock.acquire(blocking=False):
                        bot.sendMessage(
                            chatId, "ℹ️ <b>Aspetta!</b>\n"
                            "Il bot sta già eseguendo degli aggiornamenti globali per tutti gli utenti.",
                            parse_mode="HTML")
                        return

                    sent = bot.sendMessage(chatId,
                                           "📙📙📙 Cerco aggiornamenti... 0%")
                    user.remainingCalls -= 1
                    commit()
                    updateLock.release()
                    bot.editMessageText((chatId, sent['message_id']),
                                        "📗📙📙 Cerco aggiornamenti... 10%")
                    api = ClasseVivaAPI()
                    bot.editMessageText((chatId, sent['message_id']),
                                        "📗📙📙 Cerco aggiornamenti... 20%")

                    if helpers.userLogin(chatId, api):
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📙📙 Cerco aggiornamenti... 35%")
                        try:
                            data = helpers.fetchStrict(api)
                        except ApiServerError:
                            bot.editMessageText((
                                chatId, sent['message_id']
                            ), "⚠️ I server di ClasseViva non sono raggiungibili.\n"
                                                "Riprova tra qualche minuto.")
                            return
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📗📙 Cerco aggiornamenti... 50%")
                        dataDidattica = parsers.parseNewDidattica(
                            userdata.didattica, data['didattica'])
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📗📙  Cerco aggiornamenti... 60%")
                        dataNote = parsers.parseNewNote(
                            userdata.note, data['note'])
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📗📙 Cerco aggiornamenti... 70%")
                        dataVoti = parsers.parseNewVoti(
                            userdata.voti, data['voti'], chatId)
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📗📙 Cerco aggiornamenti... 80%")
                        dataAgenda = parsers.parseNewAgenda(
                            userdata.agenda, data['agenda'], chatId)
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📗📙 Cerco aggiornamenti... 90%")
                        dataCircolari = parsers.parseNewCircolari(
                            userdata.circolari, data['circolari'])
                        bot.editMessageText((chatId, sent['message_id']),
                                            "📗📗📗  Cerco aggiornamenti... 100%")

                        if dataDidattica is not None:
                            bot.sendMessage(
                                chatId,
                                "🔔 <b>Nuovi file caricati!</b>{0}".format(
                                    dataDidattica),
                                parse_mode="HTML",
                                disable_web_page_preview=True)
                        if dataNote is not None:
                            bot.sendMessage(
                                chatId,
                                "🔔 <b>Hai nuove note!</b>{0}".format(dataNote),
                                parse_mode="HTML")
                        if dataVoti is not None:
                            bot.sendMessage(
                                chatId,
                                "🔔 <b>Hai nuovi voti!</b>{0}".format(dataVoti),
                                parse_mode="HTML")
                        if dataAgenda is not None:
                            bot.sendMessage(
                                chatId,
                                "🔔 <b>Hai nuovi impegni!</b>\n{0}".format(
                                    dataAgenda),
                                parse_mode="HTML",
                                disable_web_page_preview=True)
                        if dataCircolari is not None:
                            bot.sendMessage(
                                chatId,
                                "🔔 <b>Hai nuove circolari!</b>{0}".format(
                                    dataCircolari),
                                parse_mode="HTML",
                                disable_web_page_preview=True)

                        if not any([
                                dataDidattica, dataNote, dataVoti, dataAgenda,
                                dataCircolari
                        ]):
                            bot.editMessageText((chatId, sent['message_id']),
                                                "📗 Dati aggiornati!\n"
                                                "📗 Nessuna novità!")
                        else:
                            bot.deleteMessage((chatId, sent['message_id']))

                        helpers.updateUserdata(chatId, data)
                        helpers.fetchAndStore(chatId,
                                              api,
                                              data,
                                              fetch_long=True)

                else:
                    bot.sendMessage(
                        chatId,
                        "⛔️ Hai usato troppi /aggiorna recentemente. Aspetta un po'!"
                    )

            elif (text == "/support") or (text == "/start support"):
                user.status = "calling_support"
                bot.sendMessage(
                    chatId, "🆘 <b>Richiesta di supporto</b>\n"
                    "Se hai qualche problema che non riesci a risolvere, scrivi qui un messaggio, e un admin "
                    "ti contatterà il prima possibile.\n\n"
                    "<i>Per annullare, premi</i> /annulla.",
                    parse_mode="HTML")

            elif text == "/orario":
                if not Document.exists(
                        lambda d: (d.chatId == chatId and d.type == "orario")):
                    user.status = "sending_orario"
                    bot.sendMessage(
                        chatId, "🕑 <b>Impostazione orario</b>\n"
                        "Inviami un documento (PDF oppure foto) per salvarlo e richiamarlo "
                        "quando serve con /orario!",
                        parse_mode="HTML")
                else:
                    doc = Document.get(chatId=chatId, type="orario")
                    sendFunc = bot.sendPhoto if doc.data[
                        "ext"] == "photo" else bot.sendDocument
                    sendFunc(chatId,
                             doc.data["fileId"],
                             reply_markup=keyboards.mod_orario())

            elif text == "/memo":
                user.status = "memo_date"
                today = datetime.now().weekday()
                bot.sendMessage(
                    chatId, "💡 <b>Memo personale</b>\n"
                    "Crea un memo personale per aggiungere i compiti da fare all'agenda!\n"
                    "Inviami <b>la data</b> di consegna, nel formato GG/MM, oppure scegli un'opzione "
                    "da quelle qui sotto.\n\n"
                    "Premi /annulla per annullare.",
                    parse_mode="HTML",
                    reply_markup=keyboards.create_memo(today))

            elif text == "/resetmemo":
                memos = select(m for m in Document
                               if m.chatId == chatId and m.type == "memo")[:]
                for memo in memos:
                    memo.delete()
                bot.sendMessage(chatId, "✅ Ho eliminato tutte le memo!")

            # Custom Start Parameters
            elif text.startswith("/start "):
                param = text.split(' ')[1]
                if param.startswith("circ"):
                    evtCode = param.split("-")[0].replace("circ", "")
                    pubId = int(param.split("-")[1])
                    sendFile(chatId, "circolare", evtCode, pubId)

                elif param.startswith("file"):
                    intId = int(param[4:])
                    sendFile(chatId, "file", intId)

                elif param.startswith("link"):
                    intId = int(param[4:])
                    sendFile(chatId, "link", intId)

            elif text == "⬆️⬆️⬇️⬇️⬅️➡️⬅️➡️🅱️🅰️" or text == "⬆️⬆️⬇️⬇️⬅️➡️⬅️➡️🅱🅰":
                from random import choice
                today = datetime.today().strftime("%d/%m/%Y")
                subject = choice(
                    ["MATEMATICA", "ITALIANO", "INGLESE", "STORIA"])
                bot.sendMessage(chatId,
                                "🔔 <b>Hai nuovi voti!</b>\n\n"
                                "📚 <b>{}</b>\n\n"
                                "📗 <b>Voto 10</b> • Scritto • {}\n"
                                "<i>Start!</i>".format(subject, today),
                                parse_mode="HTML")

            # Text is not a keyword
            else:
                bot.sendMessage(
                    chatId, "Non ho capito...\n"
                    "Serve aiuto? Premi /help")

        # User not logged in
        else:
            if text == "/login":
                user.status = "login_0"
                bot.sendMessage(
                    chatId,
                    "Per favore, inviami il tuo <b>username</b> (quello che usi per accedere al registro).\n"
                    "Usa /annulla se serve.",
                    parse_mode="HTML")
            else:
                bot.sendMessage(chatId,
                                "Benvenuto, <b>{0}</b>!\n"
                                "Per utilizzarmi devi eseguire il /login.\n\n"
                                "Premi /help se serve aiuto.".format(name),
                                parse_mode="HTML")

    # Normal user with restricted mode
    else:
        if text == "/moreinfo":
            bot.sendMessage(
                chatId, "❓ <b>Che genere di problemi?</b>\n"
                "ClasseViva ha recentemente imposto un limite alle sue API, che questo bot utilizza, "
                "anche se è nascosto e non sempre uguale. Con l'aumentare degli utenti, il bot doveva fare "
                "sempre più richieste e una volta raggiunto il limite ha cominciato a non funzionare più.\n"
                "La soluzione sarebbe avere una lista di minimo 20 proxy da utilizzare per fare le richieste "
                "(si tratta di max. 200KB di traffico ogni 30 minuti, non è quello il problema), che "
                "però è molto difficile da trovare senza pagare qualche servizio, che al momento non posso permettermi.\n\n"
                "❔ <b>Posso contattarti?</b>\n"
                "Certo, puoi scrivermi per qualsiasi motivo <a href=\"https://t.me/pesaventofilippo\">qui</a> "
                "o mandarmi una mail a [email protected].\n"
                "Non sono un bot, quindi magari non rispondo subito 🙂",
                parse_mode="HTML",
                disable_web_page_preview=True)

        else:
            bot.sendMessage(
                chatId, "ℹ️ <b>Bot in manutenzione</b>\n"
                "Il bot è attualmente in manutenzione per problemi con ClasseViva, e tutte le sue "
                "funzioni sono temporaneamente disabilitate.\n"
                "Non eliminare questa chat: se vuoi puoi archiviarla su Telegram, così appena "
                "ci saranno notizie ti manderò un messaggio.\n\n"
                "/moreinfo",
                parse_mode="HTML")
Ejemplo n.º 34
0
 def __init__(self, owner):
     self.__owner = owner
     self.__object_class = owner.__class__.__name__
     if owner.id is None:
         commit()
     self.__object_id = owner.id
Ejemplo n.º 35
0
def setup_general_config():
    '''
    Is used to populate the database if it has been reset.
    :return:
    '''

    long_string = ConfigType.get(type="long_string")
    long_string = ConfigType(
        type="long_string") if long_string is None else long_string

    string = ConfigType.get(type="string")
    string = ConfigType(type="string") if string is None else string

    number = ConfigType.get(type="number")
    number = ConfigType(type="number") if number is None else number

    config_list = [{
        "key":
        "frontend_url",
        "value":
        "localhost:3001",
        "config_type":
        string,
        "description":
        "The url to this frontend page (used for links in the emails)"
    }, {
        "key":
        "archive_base_url",
        "value":
        "localhost:3001/api/archive/download",
        "config_type":
        string,
        "description":
        "The base url to download archives from (used in emails to the board)"
    }, {
        "key":
        "document_template_url",
        "value":
        "https://www.overleaf.com/read/ddjdhxnkxttj",
        "config_type":
        string,
        "description":
        "The template overleaf document for the different reports (used in the emails)"
    }, {
        "key": "gotify_url",
        "value": "http://*****:*****@chalmers.it",
        "config_type": string,
        "description": "The email to the secretary"
    }, {
        "key": "board_email",
        "value": "*****@*****.**",
        "config_type": string,
        "description": "The email to the board"
    }, {
        "key": "group_email_domain",
        "value": "@chalmers.it",
        "config_type": string,
        "description": "The domain to send emails to"
    }, {
        "key": "from_email_address",
        "value": "*****@*****.**",
        "config_type": string,
        "description": "The email to send from"
    }, {
        "key":
        "mail_to_groups_subject",
        "value":
        "Dokument till sektionsmöte den {day}/{month}",
        "config_type":
        string,
        "description":
        """
The subject for "regular" email sendout (that goes out to all active groups that have documents to turn in for the meeting). \n
Description of the formatting values:  \n
 - {group_name} = The display name of the group \n
 - {meeting_day} = The day of month for the meeting \n
 - {meeting_month} = The month (number) of the meeting \n
 - {deadline_time} = The deadline time (hh:mm) \n
 - {deadline_date} = The deadline date (dd/mm) \n
 - {task_list} = A list of the tasks that the group should upload \n
 - {frontend_url} = The url to the website \n
 - {group_code} = Their unique code \n
 - {template_url} = The document (overleaf) template url \n
 - {secretary_email} = The email to the secretary \n
 - {board_display_name} = The display name of the board \n
 - {board_email} = The email to the board
 """
    }, {
        "key":
        "mail_to_groups_message",
        "value":
        "\nHej {group_name}!\n\nDen {meeting_day}/{meeting_month} är det dags för sektionsmöte och senast {deadline_time} den {deadline_date} behöver ni lämna in "
        "följande dokument: {task_list}\nDetta görs på sidan: {frontend_url}\nAnge koden: {group_code}\n\nMall för vissa "
        "dokument finns här: {template_url}\nGör en kopia av projektet (Menu -> Copy Project) och fyll i.\n\nOm ni har "
        "några frågor eller stöter på några problem kan kan ni kontakta mig på {secretary_email} eller hela {board_display_name} på {board_email} "
        ": ).",
        "config_type":
        long_string,
        "description":
        """
The body of the "regular" emails (the ones that are sent to all the active groups that should turn in documents for the meeting).  \n
Description of the formatting values:  \n
 - {group_name} = The display name of the group \n
 - {meeting_day} = The day of month for the meeting \n
 - {meeting_month} = The month (number) of the meeting \n
 - {deadline_time} = The deadline time (hh:mm) \n
 - {deadline_date} = The deadline date (dd/mm) \n
 - {task_list} = A list of the tasks that the group should upload \n
 - {frontend_url} = The url to the website \n
 - {group_code} = Their unique code \n
 - {template_url} = The document (overleaf) template url \n
 - {secretary_email} = The email to the secretary \n
 - {board_display_name} = The display name of the board \n
 - {board_email} = The email to the board
             """
    }, {
        "key":
        "mail_to_board_subject",
        "value":
        "Dokument för sektionsmöte {meeting_number} lp {meeting_lp}",
        "config_type":
        string,
        "description":
        """
The subject of the email that is sent to the board upon reaching the deadline.  \n
Description of the formatting values:  \n
 - {board_name} = The display name of the board \n
 - {meeting_number} = The number of the meeting (usually 0) \n
 - {meeting_lp} = The study period of the meeting \n
 - {meeting_archive_url} = A link to the archive download \n
 - {secretary_email} = The email to the secretary
             """
    }, {
        "key":
        "mail_to_board_message",
        "value":
        "\nHej {board_name}!\n\nDeadlinen för dokumentinsamling till sektionsmöte {meeting_number} i lp {meeting_lp} är nu nådd.\nFör "
        "nedladdning av dessa dokument klicka på denna länk: {meeting_archive_url}\n\nVid frågor, kontakta sekreteraren på {secretary_email}",
        "config_type":
        long_string,
        "description":
        """
The contents of the email that is sent out to the board upon reaching the deadline. \n
Description of the formatting values:  \n
 - {board_name} = The display name of the board \n
 - {meeting_number} = The number of the meeting (usually 0) \n
 - {meeting_lp} = The study period of the meeting \n
 - {meeting_archive_url} = A link to the archive download \n
 - {secretary_email} = The email to the secretary
             """
    }, {
        "key":
        "mail_for_stories_subject",
        "value":
        "Dokument för sektionsmöte {meeting_number} lp {meeting_lp}",
        "config_type":
        string,
        "description":
        """ 
The subject of the email that is sent to the "story groups" (i.e. the groups that needs to turn in eberattelser / vberattelser. \n
Description of the formatting values:  \n
 - {group_name_year} = Display name of the group. \n
 - {meeting_day} = The day of month that the meeting will take place \n
 - {meeting_month} = The month (number) of the meeting \n
 - {deadline_time} = The deadline time \n
 - {deadline_date} = The deadline date \n
 - {task_list} = A list of the tasks that the group will have to turn in. \n
 - {frontend_url} = A url to the frontend (upload page) \n
 - {group_code} = Their unique code \n
 - {template_url} = A link the overleaf template for the documents. \n
 - {secretary_email} = The email to the secretary \n
 - {board_display_name} = The display name of the board \n
 - {board_email} = The email to the board \n
 - {meeting_number} = The number of the meeting that study period (usually 0) \n
 - {meeting_lp} = The study period
             """
    }, {
        "key":
        "mail_for_stories",
        "value":
        "\nHej {group_name_year}!\n\nDen {meeting_day}/{meeting_month} är det dags för sektionsmöte och senast {deadline_time} den {deadline_date} behöver ni lämna in "
        "följande dokument: {task_list}\nDetta görs på sidan: {frontend_url}\nAnge koden: {group_code}\n\nMall för vissa "
        "dokument finns här: {template_url}\nGör en kopia av projektet (Menu -> Copy Project) och fyll i.\n "
        "Kontakta revisorerna på [email protected] för mer information om vad som behövs göras innan ni "
        "kan bli rekomenderade att bli ansvarsbefriade.\n\nOm ni har "
        "några frågor eller stöter på några problem kan kan ni kontakta mig på {secretary_email} eller hela {board_display_name} på {board_email} "
        ": ).",
        "config_type":
        long_string,
        "description":
        """
The body of the email that is sent to the "story groups" (i.e. the groups that needs to turn in eberattelser / vberattelser) \n
Description of the formatting values:  \n
 - {group_name_year} = Display name of the group. \n
 - {meeting_day} = The day of month that the meeting will take place \n
 - {meeting_month} = The month (number) of the meeting \n
 - {deadline_time} = The deadline time \n
 - {deadline_date} = The deadline date \n
 - {task_list} = A list of the tasks that the group will have to turn in. \n
 - {frontend_url} = A url to the frontend (upload page) \n
 - {group_code} = Their unique code \n
 - {template_url} = A link the overleaf template for the documents. \n
 - {secretary_email} = The email to the secretary \n
 - {board_display_name} = The display name of the board \n
 - {board_email} = The email to the board \n
 - {meeting_number} = The number of the meeting that study period (usually 0) \n
 - {meeting_lp} = The study period
             """
    }, {
        "key": "board_display_name",
        "value": "styrIT",
        "config_type": string,
        "description": "The display name of the board"
    }, {
        "key":
        "minutes_after_deadline_to_mail",
        "value":
        "5",
        "config_type":
        number,
        "description":
        "The amount of minutes to wait extra after the deadline before sending the email to the board"
    }, {
        "key":
        "check_for_deadline_frequency",
        "value":
        "5",
        "config_type":
        number,
        "description":
        "The frequence (in minutes) to check if any deadlines have been reached"
    }, {
        "key":
        "possible_years_back_for_stories",
        "value":
        "5",
        "config_type":
        number,
        "description":
        "The number of years back that one should be able to select story groups for (usually 5 due to tax reasons)"
    }]

    for config in config_list:
        conf = Config.get(key=config["key"])
        if conf is None:
            Config(key=config["key"],
                   value=config["value"],
                   config_type=config["config_type"],
                   description=config["description"])
        else:
            # Since the only way to change the description is here,
            # we always want the db version to be up to date with this list on application restart.
            conf.description = config["description"]

    # Setup groups and tasks
    groups = [{
        "codeName": "armit",
        "displayName": "ArmIT"
    }, {
        "codeName": "digit",
        "displayName": "digIT"
    }, {
        "codeName": "fanbarerit",
        "displayName": "FanbärerIT"
    }, {
        "codeName": "fritid",
        "displayName": "frITid"
    }, {
        "codeName": "mrcit",
        "displayName": "MRCIT"
    }, {
        "codeName": "nollkit",
        "displayName": "NollKIT"
    }, {
        "codeName": "prit",
        "displayName": "P.R.I.T."
    }, {
        "codeName": "sexit",
        "displayName": "sexIT"
    }, {
        "codeName": "snit",
        "displayName": "snIT"
    }, {
        "codeName": "styrit",
        "displayName": "styrIT"
    }, {
        "codeName": "equalit",
        "displayName": "EqualIT"
    }, {
        "codeName": "flashit",
        "displayName": "FlashIT"
    }]

    tasks = [{
        "codeName": "vplan",
        "displayName": "Verksamhetsplan / Operational plan"
    }, {
        "codeName": "budget",
        "displayName": "Budget"
    }, {
        "codeName": "vrapport",
        "displayName": "Verksamhetsrapport / Operational report"
    }, {
        "codeName": "vberattelse",
        "displayName": "Verksamhetsberättelse / Operational story"
    }, {
        "codeName": "eberattelse",
        "displayName": "Ekonomisk Berättelse / Economic story"
    }]

    for group in groups:
        if Group.get(name=group["codeName"]) is None:
            new_group = Group(name=group["codeName"],
                              display_name=group["displayName"])

            if GroupYear.get(group=new_group, year="active") is None:
                GroupYear(group=new_group, year="active", finished=False)

    for task in tasks:
        if Task.get(name=task["codeName"]) is None:
            Task(name=task["codeName"], display_name=task["displayName"])

    commit()
    print("Finished loading database data from general config file.")
Ejemplo n.º 36
0
def installFromLocal():

    global option

    if len(option["pathlib"]) == 0 or option["pathlib"] == ".":
        option["pathlib"] = Path().cwd()
    else:
        option["pathlib"] = Path(option["pathlib"])

    pwd = option["pathlib"].joinpath(Path(option["src"]))

    if not Path(pwd).exists():
        logger.error(pwd + " doesn't exist!")
        return None

    agdaLibFiles = [
        f for f in pwd.glob(option["name"] + LIB_SUFFIX) if f.is_file()
    ]
    agdaPkgFiles = [
        f for f in pwd.glob(option["name"] + PKG_SUFFIX) if f.is_file()
    ]

    if len(agdaLibFiles) + len(agdaPkgFiles) == 0:
        logger.error(" no libraries (" + LIB_SUFFIX + " or "\
                    + PKG_SUFFIX + ") files detected." )
        return None

    libFile = Path("")
    if len(agdaPkgFiles) == 1:
        libFile = agdaPkgFiles[0]
    elif len(agdaLibFiles) == 1:
        libFile = agdaLibFiles[0]
    else:
        logger.error("[!] Use --name to specify the library name.")
        return None

    logger.info("Library file detected: " + libFile.name)

    info = readLibFile(libFile)

    option["name"] = info.get("name", "")

    if len(option["name"]) == 0:
        option["name"] = option["pathlib"].name

    versionName = option["version"]

    if versionName == "":
        versionName = str(info.get("version", ""))
    if versionName == "" and pwd.joinpath(".git").exists():
        try:
            with open(os.devnull, 'w') as devnull:
                result = subprocess.run(
                    ["git", "describe", "--tags", "--long"],
                    stdout=subprocess.PIPE,
                    stderr=devnull,
                    cwd=pwd.as_posix())
                versionName = result.stdout.decode()
        except:
            pass

    if versionName == "" and pwd.joinpath(".git").exists():
        try:
            with open(os.devnull, 'w') as devnull:
                result = subprocess.run(["git", "rev-parse", "HEAD"],
                                        stdout=subprocess.PIPE,
                                        stderr=devnull,
                                        cwd=pwd.as_posix())
                versionName = result.stdout.decode()[:8]
        except:
            pass

    if versionName == "":
        versionName = str(uuid.uuid1())

    logger.info("Library version: " + versionName)

    # At this point we have the name from the local library
    library = Library.get(name=option["name"])

    if library is None:
        library = Library(name=option["name"])

    versionLibrary = LibraryVersion.get(library=library, name=versionName)

    if versionLibrary is not None:

        if versionLibrary.installed:
            logger.warning("This version ({}) is already installed.".format(
                versionLibrary.freezeName))
            if option["yes"] or click.confirm(
                    'Do you want to uninstall it first?'):
                try:
                    uninstallLibrary(libname=option["name"],
                                     database=False,
                                     remove_cache=True)
                except Exception as e:
                    logger.error(e)
                    return None
            else:

                versionNameProposed = "{}-{}".format(versionName, uuid.uuid1())
                logger.warning("Version suggested: " + option["name"] + "@" +
                               versionNameProposed)

                if click.confirm(
                        'Do you want to install it using this version?',
                        abort=True):
                    versionLibrary = LibraryVersion(
                        library=library,
                        name=versionNameProposed,
                        cached=True,
                        editable=option["editable"])
    else:
        versionLibrary = LibraryVersion(library=library,
                                        name=versionName,
                                        cached=True,
                                        editable=option["editable"])

    if option["editable"]:
        versionLibrary.origin = pwd.as_posix()
        versionLibrary.editable = True
        option["editable"] = False  # Just used editable once

    try:
        if not (versionLibrary.editable):
            if versionLibrary.sourcePath.exists():
                remove_tree(versionLibrary.sourcePath.as_posix())

            logger.info("Adding " + versionLibrary.sourcePath.as_posix())
            copy_tree(pwd.as_posix(), versionLibrary.sourcePath.as_posix())

    except Exception as e:
        logger.error(e)
        logger.error("Fail to copy directory (" + pwd.as_posix() + ")")
        return None

    commit()

    try:
        info = versionLibrary.readInfoFromLibFile()

        keywords = info.get("keywords", []) + info.get("category", [])
        keywords = list(set(keywords))

        for word in keywords:

            keyword = Keyword.get_for_update(word=word)

            if keyword is None:
                keyword = Keyword(word=word)

            if not library in keyword.libraries:
                keyword.libraries.add(library)

            if not versionLibrary in keyword.libVersions:
                keyword.libVersions.add(versionLibrary)

        versionLibrary.depend.clear()
        for depend in info.get("depend", []):

            if type(depend) == list:
                logger.info("no supported yet.")
            else:
                if "@" in depend:
                    dname, _ = depend.split("@")
                else:
                    dname = depend
                dependency = Library.get(name=dname)

                if dependency is not None:
                    versionLibrary.depend.add(Dependency(library=dependency))

                    if not option[
                            "no_dependencies"] and not dependency.installed:

                        oldOption = option
                        option["libname"] = dependency.name
                        option["version"] = ""
                        option["name"] = "*"
                        option["libnames"] = ()
                        installFromIndex()
                        option = oldOption

                else:
                    logger.warning(depend + " is not in the index")

        versionLibrary.install(not (option["no_defaults"]))

        commit()
        return versionLibrary

    except Exception as e:
        try:
            if not (versionLibrary.editable
                    ) and versionLibrary.sourcePath.exists():
                remove_tree(versionLibrary.sourcePath.as_posix())
        except:
            logger.error(" fail to remove the sources: {}".format(
                versionLibrary.sourcePath.as_poasix()))

        logger.error(e)
        return None
Ejemplo n.º 37
0
 def set_resolved(self, feedback_id):
     Feedback[feedback_id].done = datetime.utcnow()
     commit()
Ejemplo n.º 38
0
 def test_scan_file(self):
     self.scanner.scan_file("/some/inexistent/path")
     commit()
     self.assertEqual(db.Track.select().count(), 1)
Ejemplo n.º 39
0
 def post(self, budget_id):
     '''Create an item'''
     item_obj = db.Item(**ns.payload)
     commit()
     return item_obj, 201
Ejemplo n.º 40
0
def reply(msg):
    chatId = msg['chat']['id']
    text = msg['text']
    name = msg['from']['first_name']

    if not User.exists(lambda u: u.chatId == chatId):
        User(chatId=chatId)
    user = User.get(chatId=chatId)

    if user.status == "newclip":
        if text == "/cancel":
            user.status = "normal"
            bot.sendMessage(chatId, "❎ Operation cancelled!")

        else:
            clip = Clip(user=user, text=helpers.sanitize(text))
            commit()
            user.status = "cliptitle#{}".format(clip.id)
            bot.sendMessage(
                chatId, "✅ Clip successfully created!\n"
                "What title should it have?")

    elif user.status.startswith("cliptitle"):
        clipid = int(user.status.split("#")[1])
        clip = Clip.get(user=user, id=clipid)
        clip.title = helpers.sanitize(text)
        user.status = "normal"
        bot.sendMessage(
            chatId,
            "📝 Clip <b>{}</b> renamed!\n"
            "Ready to share it? Use me in a chat by typing @clipsharebot!".
            format(text),
            parse_mode="HTML")

    elif user.status == "normal":
        if text == "/start":
            bot.sendMessage(
                chatId,
                "Hey, <b>{}</b>! 👋🏻\n"
                "Type /new to create a new custom clip.".format(name),
                parse_mode="HTML")

        elif text == "/cancel":
            bot.sendMessage(
                chatId, "Operation cancelled!\n"
                "I was doing nothing, btw... 😴")

        elif text == "/new" or ("newclip_inline" in text):
            user.status = "newclip"
            bot.sendMessage(
                chatId,
                "✏️ Ok, send me the text for the new clip!\nType /cancel to abort."
            )

        elif text == "/list":
            clips = user.clips
            if clips:
                message = "📚 <b>Clips List</b>\n<i>Click on a title to see the full content</i>\n"
                for clip in clips:
                    message += "\n📄 <a href=\"https://t.me/clipsharebot?start=getclip_{}\">{}</a>".format(
                        clip.id, clip.title)
            else:
                message = "😓 Sorry, you don't have clips yet! Type /new to get started."
            bot.sendMessage(chatId,
                            message,
                            parse_mode="HTML",
                            disable_web_page_preview=True)

        elif text == "/delete":
            if user.clips:
                sent = bot.sendMessage(
                    chatId, "🗑 <b>Delete a Clip</b>\n"
                    "What clip would you like to delete? Type /list if you want to see a clip's full content.",
                    parse_mode="HTML")
                bot.editMessageReplyMarkup(
                    (chatId, sent['message_id']),
                    keyboards.delete(user, sent['message_id']))
            else:
                bot.sendMessage(
                    chatId,
                    "😓 Sorry, you don't have clips yet! Type /new to get started."
                )

        elif text.startswith("/start getclip"):
            clipid = int(text.split("_")[1])
            clip = Clip.get(user=user, id=clipid)
            if clip:
                bot.sendMessage(
                    chatId,
                    "📖 <b>Open Clip</b>\n\n<b>Title:</b> {}\n<b>Text:</b> {}".
                    format(clip.title, clip.text),
                    parse_mode="HTML")
            else:
                bot.sendMessage(chatId,
                                "🔒 <i>Error: this clip has been deleted.</i>",
                                parse_mode="HTML")

        else:
            bot.sendMessage(chatId,
                            "🤨 <i>Command not found.</i>",
                            parse_mode="HTML")
Ejemplo n.º 41
0
 def __scan(self, force=False):
     self.scanner = Scanner(force=force)
     self.scanner.queue_folder("folder")
     self.scanner.run()
     commit()
Ejemplo n.º 42
0
def add_data():
    product = Product(id=product_id, name=product_name)
    Title(id=1, name='title', product=product)
    commit()
Ejemplo n.º 43
0
def add_users():
    with db_session:
        for user in user_data:
            User(name=user['name'])
    commit()
Ejemplo n.º 44
0
def api_v1_playlist_put(token: Authentication, req: CreatePlaylistRequest):
  playlist = Playlist(name=req.name)
  orm.commit()
  return playlist
Ejemplo n.º 45
0
def usersave():
    """ User data save into DB """
    array = []
    now = datetime.datetime.now()
    dni = request.params.get("dni")
    nombre = request.params.get("nombre")
    apellido = request.params.get("apellido")
    email = request.params.get("email")
    direccion = request.params.get("dir")
    ciudad = request.params.get("ciudad")
    codigopostal = request.params.get("cp")
    nvoucher = request.params.get("voucher")
    nidproducto = request.params.get("id")
    array.append(dni)
    array.append(nombre)
    array.append(apellido)
    array.append(email)
    array.append(direccion)
    array.append(ciudad)
    array.append(codigopostal)
    array.append(now)
    array.append(nvoucher)
    array.append(nidproducto)


    #Get all the objects from database
    clientes = select(p for p in Cliente)[:]
    result = {'data': [p.to_dict() for p in clientes]}

    # Get all the objects from DB and confirm if DNI
    # already exists.
    for i in result['data']:
        print(i['dni'])
        print(array[0])
        if str(i['dni']) == str(array[0]):
            return redirect('/already')

    # Validate Null spaces in textbox.
    c = 0
    save = 0
    for i in array:
        if i == "":
            c = c + 1
            if c == 7:
                return redirect('/complete')
                save = 0
        else:
            c = c + 1
            if c == 7:
                save = 1
          
    if save == 1:
        Cliente(dni=array[0], nombre=array[1],
                apellido=array[2], email=array[3],
                direccion=array[4],ciudad=array[5],
                codigoPostal=array[6],fechaRegistro=str(array[7]))
        theID = Cliente.get(dni=array[0]).id
        current_voucher = Voucher.get(codigovoucher=array[8])
        current_voucher.cliente = theID
        current_voucher.estado = 1
        current_voucher.producto = array[9]
        # Commit Cliente in to the DB
        commit()
        return redirect('/thanks')
Ejemplo n.º 46
0
    def go(self):
        need_update_account = True
        while True:
            time.sleep(0.5)
            # profit_notify_everyday()
            try:
                if need_update_account:
                    self.logger.info("更新账户信息")
                    account = self.account()
                    need_update_account = False
            except Exception as e:
                self.logger.error("获取账户信息错误: %s, 暂停2s", str(e))
                time.sleep(2)
                continue
            self.logger.info(
                "本次循环前资产, cny: %.2f, btc: %.4f, ltc: %.4f, eth: %.4f, 总cny: %.2f",
                account['free']['cny'],
                account['free']['btc'],
                account['free']['ltc'],
                account['free']['eth'],
                account['total_cny'],
            )
            self.logger.info(
                "本次循环前冻结资产, cny: %.2f, btc: %.4f, ltc: %.4f, eth: %.4f",
                account['frozen']['cny'],
                account['frozen']['btc'],
                account['frozen']['ltc'],
                account['frozen']['eth'],
            )
            for k, v in account['platform'].items():
                self.logger.info("%s 平台 cny: %s, eth: %s, ltc: %s, btc: %s", k,
                                 str(v['cny']), str(v['eth']), str(v['ltc']),
                                 str(v['btc']))
            try:
                min_buy, max_sell = self.collect_depth(account)
            except Exception as e:
                self.logger.error("获取深度信息错误: %s, 暂停2s", str(e))
                time.sleep(2)
                continue
            if min_buy['client'].name == max_sell['client'].name:
                self.logger.info("相同平台%s, 跳过", min_buy['client'].name)
                continue
            before_coin = account['free'][self.coin]
            before_cny = account['free']['cny']

            # 判断coin 数量
            if float(account[min_buy['client'].name]['free']['cny']) < 1:
                self.logger.info(
                    "%s 平台cny不足: %s < 1", min_buy['client'].name,
                    account[min_buy['client'].name]['free']['cny'])
                continue
            if float(account[max_sell['client'].name]['free'][
                    self.coin]) < 0.03:
                self.logger.info(
                    "%s 平台%s: %s < 0.03", max_sell['client'].name, self.coin,
                    account[max_sell['client'].name]['free'][self.coin])
                continue
            sell_count, buy_count = self.calculate_trade_count(
                account, max_sell, min_buy)
            if sell_count < trade_count_limit:
                self.logger.info("sell_count %.4f < %.4f 跳过", sell_count,
                                 trade_count_limit)
                continue

            # 判断深度
            if buy_count > min_buy['depth'][
                    1] * depth_limit or sell_count > max_sell['depth'][
                        1] * depth_limit:
                # 用depth_limit来确保有足够多的单可以交易
                self.logger.info("深度不足: %.3f < %.4f * %s or %.3f < %.4f * %s",
                                 buy_count, min_buy['depth'][1],
                                 str(depth_limit), sell_count,
                                 max_sell['depth'][1], str(depth_limit))
                continue

            # 判断盈利
            # 这里的计算利润和交易所的计算会有精度问题
            sell_count = round(sell_count, 4)
            buy_count = round(buy_count, 4)
            sell_money = sell_count * max_sell['depth'][0] * (1 - fee)
            buy_money = buy_count * min_buy['depth'][0]
            profit = sell_money - buy_money
            self.logger.info("%s price: %s, %s price: %s",
                             max_sell['client'].name, max_sell['depth'][0],
                             min_buy['client'].name, min_buy['depth'][0])
            if max_sell['depth'][0] - min_buy['depth'][0] < limit_diff:
                self.logger.info("差价小于 %s", str(limit_diff))
                continue
            # if profit < profit_limit:
            #     self.logger.info("本次收益 %.2f < %.2f, 跳过", profit, profit_limit)
            #     continue

            self.logger.info("本次预计收益 %.2f - %.2f = %.2f", sell_money,
                             buy_money, profit)
            # 先执行卖出, 再执行买入
            ret, msg = self.trade(sell_client=max_sell['client'],
                                  buy_client=min_buy['client'],
                                  sell_count=sell_count,
                                  buy_count=buy_count,
                                  sell_price=max_sell['depth'][0],
                                  buy_price=min_buy['depth'][0])
            if not ret:
                self.logger.warn("本次交易失败: %s", str(msg))
                continue
            account = self.account()
            self.logger.info(
                "本次循环后资产, cny: %.2f, btc: %.4f, ltc: %.4f, eth: %.4f,总cny: %.2f",
                account['free']['cny'],
                account['free']['btc'],
                account['free']['ltc'],
                account['free']['eth'],
                account['total_cny'],
            )
            self.logger.info(
                "本次循环后冻结资产, cny: %.2f, btc: %.4f, ltc: %.4f, eth: %.4f",
                account['frozen']['cny'],
                account['frozen']['btc'],
                account['frozen']['ltc'],
                account['frozen']['eth'],
            )
            self.logger.info(
                "实际收益, cny: %.2f - %.2f = %.2f, %s: %.4f - %.4f = %.4f",
                account['free']['cny'],
                before_cny,
                account['free']['cny'] - before_cny,
                self.coin,
                account['free'][self.coin],
                before_coin,
                account['free'][self.coin] - before_coin,
            )
            if 0 < account['free']['cny'] - before_cny < profit:
                self.logger.warn("实际收益 小于 预计收益")
            # 记录交易
            for k, v in account['platform'].items():
                self.logger.info("%s 平台 cny: %s, ltc: %s, btc: %s", k,
                                 str(v['cny']), str(v['ltc']), str(v['btc']))
            Record(
                create_time=datetime.now(),
                before_cny=str(before_cny),
                coin=self.coin,
                current_volume=str(account['free'][self.coin]),
                cny=str(account['free']['cny']),
                sell_price=str(max_sell['depth'][0]),
                sell_amount=str(sell_count),
                sell_platform=max_sell['client'].name,
                buy_price=str(min_buy['depth'][0]),
                buy_amount=str(buy_count),
                buy_platform=min_buy['client'].name,
            )
            commit()
            price = min_buy['depth'][0]
            coin_diff = (account['free'][self.coin] - before_coin)
            real_profit = account['free'][
                'cny'] - before_cny + coin_diff * price
            if coin_diff < -0.005:
                # 补偿差值
                self.coin_diff = abs(coin_diff)
            self.logger.info("实际利润(币值变化 + cny变化) %.2f", real_profit)
            if real_profit < 0:
                self.logger.warn("实际收益小于0")
                break
            need_update_account = True
Ejemplo n.º 47
0
def installFromGit():

    global option

    if not isGit(option.get("url", "")):
        logger.error("This is not a git repository.\
                  You may want to add '.git' at the end of your URL.")
        return None

    logger.info("Installing from git: %s" % option["url"])

    with TemporaryDirectory() as tmpdir:

        try:
            click.echo("Using temporary directory: {}".format(tmpdir))

            if Path(tmpdir).exists():
                remove_tree(tmpdir)

            # To display a nice progress bar, we need the size of
            # the repository, so let's try to get that number

            # -- SIZE Repo

            size = 0
            if "github" in option["url"]:

                reporef = option["url"].split("github.com")[-1]
                infourl = GITHUB_API + reporef.split(".git")[0]

                response = requests.get(infourl, stream=True)

                if not response.ok:
                    logger.error("Request failed: %d" % response.status_code)
                    return None

                info = response.json()
                size = int(info.get("size", 0))

            else:

                response = requests.get(option["url"], stream=True)
                if not response.ok:
                    logger.error("Request failed: %d" % response.status_code)
                    return None

                size_length = response.headers.get('content-length')
                size = 0
                if size_length is None:
                    for _ in response.iter_content(1024):
                        size += 1024
                else:
                    size = size_length
                size = int(size)

            logger.info("Downloading " + option["url"]  \
                  + " (%s)" % str(humanize.naturalsize(size, binary=True)))

            with click.progressbar(length=10 * size,
                                   bar_template='|%(bar)s| %(info)s %(label)s',
                                   fill_char=click.style('█', fg='cyan'),
                                   empty_char=' ',
                                   width=30) as bar:

                class Progress(git.remote.RemoteProgress):

                    total, past = 0, 0

                    def update(self,
                               op_code,
                               cur_count,
                               max_count=None,
                               message=''):

                        if cur_count < 10:
                            self.past = self.total
                        self.total = self.past + int(cur_count)

                        bar.update(self.total)

                click.echo("Git branch: " + option["branch"])

                REPO = git.Repo.clone_from(option["url"],
                                           tmpdir,
                                           branch=option["branch"],
                                           progress=Progress())

            if option["version"] != "":
                try:
                    # Seen on https://goo.gl/JVs8jJ
                    REPO.git.checkout(option["version"])

                except Exception as e:
                    logger.error(e)
                    logger.error(" version or tag not found ({})".format(
                        option["version"]))
                    return None

            option["pathlib"] = tmpdir

            libVersion = installFromLocal()

            if libVersion is None:
                logger.error(" we couldn't install the version you specified.")
                return None

            libVersion.fromGit = True
            libVersion.origin = option["url"]
            libVersion.library.url = option["url"]
            libVersion.library.default = not (option["no_defaults"])

            if option["version"] != "":
                libVersion.sha = REPO.head.commit.hexsha

            commit()
            return libVersion

        except Exception as e:
            logger.error(e)
            logger.error(
                "There was an error when installing the library. May you want to run init?"
            )
            return None
Ejemplo n.º 48
0
import os
import time
from random import choice

from models import Journal
from pony.orm import commit, db_session

LEVEL_CHOICE = [10, 20, 30, 40, 50]
count = int(os.environ.get("ITERATIONS", "1000"))


start = now = time.time()
with db_session():
    for i in range(count):
        Journal(level=choice(LEVEL_CHOICE), text=f"Insert from B, item {i}")
    commit()
now = time.time()

print(f"Pony ORM, B: Rows/sec: {count / (now - start): 10.2f}")
Ejemplo n.º 49
0
 def add(self, user_id, text):
     Feedback(user_id=user_id, text=text, created=datetime.utcnow())
     commit()
Ejemplo n.º 50
0
def add_tag(value):
    if value:
        Tag(value=value)
        orm.commit()
Ejemplo n.º 51
0
async def delete(request, id):
    with orm.db_session:
        n = News[id]
        n.hide = True
        orm.commit()
    return json({}, headers={'Access-Control-Allow-Origin': '*'})
Ejemplo n.º 52
0
    def process_item(self, item: Item, spider: Spider):
        if type(item) is UserItem:
            if 'avatar_url' in item:
                avatar_url = item['avatar_url'][0]
                if avatar_url[0] == '/':
                    avatar_url = avatar_url[1:]
                avatar_url = 'http://mc.bbcity.ru/' + avatar_url

                avatar_response = urllib.request.urlopen(avatar_url)
                avatar = avatar_response.read()

                self.User(id=int(item['id'][0]),
                          name=item['name'][0],
                          avatar_url=item['avatar_url'][0],
                          avatar=avatar,
                          registration_date=item['registration_date'][0])
                orm.commit()
            else:
                self.User(id=int(item['id'][0]),
                          name=item['name'][0],
                          registration_date=item['registration_date'][0])
                orm.commit()
        elif type(item) is SectionItem:
            self.Section(id=int(item['id']), title=item['title'])
            orm.commit()
        elif type(item) is ForumItem:
            self.Forum(id=int(item['id']),
                       title=item['title'],
                       section=int(item['section_id']))
            orm.commit()
        elif type(item) is TopicItem:
            self.Topic(id=int(item['id']),
                       title=item['title'],
                       forum=int(item['forum_id']))
            orm.commit()
        elif type(item) is PostItem:
            self.Post(id=int(item['id']),
                      topic=int(item['topic']),
                      number=int(item['number']),
                      date=int(item['date']),
                      author=int(item['author']),
                      text=str(item['text']))
            orm.commit()

        return item
Ejemplo n.º 53
0
def add_tweet(tweet, sentiment):
    text = tweet.text.translate(non_bmp_map)
    tweet = Tweet(tweet_id=str(tweet.id), text=text, sentiment=sentiment)
    orm.commit()
Ejemplo n.º 54
0
def add_data():
    product = Product(id=1, name='product_name')
    Title(id=1, name='title', product=product)
    commit()
    print('created')
Ejemplo n.º 55
0
    def dispatch_request(self, action=4):
        form = FormRoute.get(action)
        if not form or not form.is_profile():
            return redirect(url_for('.profile'))

        tabs = [
            dict(title='Edit Profile',
                 glyph='pencil',
                 active=False,
                 url=url_for('.profile', action=FormRoute.EDIT_PROFILE.value)),
            dict(title='Log out on all devices',
                 glyph='remove',
                 active=False,
                 url=url_for('.profile', action=FormRoute.LOGOUT_ALL.value)),
            dict(title='Change Password',
                 glyph='qrcode',
                 active=False,
                 url=url_for('.profile',
                             action=FormRoute.CHANGE_PASSWORD.value))
        ]

        admin = current_user.role_is(UserRole.ADMIN)
        if admin:
            tabs.extend([
                dict(title='New Blog Post',
                     glyph='font',
                     active=False,
                     url=url_for('.profile',
                                 action=FormRoute.NEW_BLOG_POST.value)),
                dict(title='New Meeting Page',
                     glyph='resize-small',
                     active=False,
                     url=url_for('.profile',
                                 action=FormRoute.NEW_MEETING_PAGE.value)),
                dict(title='New Email Template',
                     glyph='envelope',
                     active=False,
                     url=url_for('.profile',
                                 action=FormRoute.NEW_EMAIL_TEMPLATE.value)),
                dict(title='New Team Member',
                     glyph='knight',
                     active=False,
                     url=url_for('.profile',
                                 action=FormRoute.NEW_MEMBER_PAGE.value)),
                dict(title='Ban User',
                     glyph='remove-circle',
                     active=False,
                     url=url_for('.profile', action=FormRoute.BAN_USER.value)),
                dict(title='Change Role',
                     glyph='arrow-up',
                     active=False,
                     url=url_for('.profile',
                                 action=FormRoute.CHANGE_USER_ROLE.value))
            ])

        if form == FormRoute.EDIT_PROFILE:
            message = 'Edit Profile'
            tabs[0]['active'] = True
            active_form = ProfileForm(obj=current_user.get_user())
            if active_form.validate_on_submit():
                u = User.get(id=current_user.id)
                u.name = active_form.name.data
                u.surname = active_form.surname.data
                u.country = active_form.country.data
                u.degree = active_form.degree.data
                u.status = active_form.status.data

                if active_form.banner_field.data:
                    u.banner = save_upload(active_form.banner_field.data,
                                           images=True)

                if active_form.affiliation.data:
                    u.affiliation = active_form.affiliation.data
                elif u.affiliation:
                    u.affiliation = ''

                if active_form.position.data:
                    u.position = active_form.position.data
                elif u.position:
                    u.position = ''

                if active_form.town.data:
                    u.town = active_form.town.data
                elif u.town:
                    u.town = ''

                flash('Profile updated')

        elif form == FormRoute.LOGOUT_ALL:
            message = 'Log out on all devices'
            tabs[1]['active'] = True
            active_form = ReLoginForm()
            if active_form.validate_on_submit():
                u = User.get(id=current_user.id)
                u.change_token()
                logout_user()
                flash('Successfully logged out from all devices')
                return redirect(url_for('.login'))

        elif form == FormRoute.CHANGE_PASSWORD:
            message = 'Change Password'
            tabs[2]['active'] = True
            active_form = ChangePasswordForm()
            if active_form.validate_on_submit():
                u = User.get(id=current_user.id)
                u.change_password(active_form.password.data)
                logout_user()
                flash('Successfully changed password')
                return redirect(url_for('.login'))

        elif admin and form == FormRoute.NEW_BLOG_POST:
            message = 'New Blog Post'
            tabs[3]['active'] = True
            active_form = PostForm()
            if active_form.validate_on_submit():
                banner_name, file_name = combo_save(active_form.banner_field,
                                                    active_form.attachment)
                p = BlogPost(type=active_form.type,
                             title=active_form.title.data,
                             slug=active_form.slug.data,
                             body=active_form.body.data,
                             banner=banner_name,
                             attachments=file_name,
                             author=current_user.get_user())
                commit()
                return redirect(url_for('.blog_post', post=p.id))

        elif admin and form == FormRoute.NEW_MEETING_PAGE:
            message = 'New Meeting Page'
            tabs[4]['active'] = True
            active_form = MeetingForm()

            def add_post():
                banner_name, file_name = combo_save(active_form.banner_field,
                                                    active_form.attachment)
                p = Meeting(
                    meeting=active_form.meeting_id.data,
                    deadline=active_form.deadline.data,
                    poster_deadline=active_form.poster_deadline.data,
                    participation_types=active_form.participation_types,
                    thesis_types=active_form.thesis_types,
                    order=active_form.order.data,
                    type=active_form.type,
                    author=current_user.get_user(),
                    title=active_form.title.data,
                    slug=active_form.slug.data,
                    body_name=active_form.body_name.data,
                    body=active_form.body.data,
                    banner=banner_name,
                    attachments=file_name)
                commit()
                return p.id

            if active_form.validate_on_submit():
                if active_form.type != MeetingPostType.MEETING:
                    if active_form.meeting_id.data and Meeting.exists(
                            id=active_form.meeting_id.data,
                            post_type=MeetingPostType.MEETING.value):
                        return redirect(url_for('.blog_post', post=add_post()))
                    active_form.meeting_id.errors = ['Bad parent']
                else:
                    if active_form.deadline.data and active_form.poster_deadline.data:
                        return redirect(url_for('.blog_post', post=add_post()))
                    active_form.deadline.errors = ["Need deadline"]
                    active_form.poster_deadline.errors = ["Need deadline"]

        elif admin and form == FormRoute.NEW_EMAIL_TEMPLATE:
            message = 'New Email Template'
            tabs[5]['active'] = True
            active_form = EmailForm()

            def add_post():
                banner_name, file_name = combo_save(active_form.banner_field,
                                                    active_form.attachment)
                p = Email(from_name=active_form.from_name.data,
                          reply_name=active_form.reply_name.data,
                          reply_mail=active_form.reply_mail.data,
                          meeting=active_form.meeting_id.data,
                          type=active_form.type,
                          author=current_user.get_user(),
                          title=active_form.title.data,
                          slug=active_form.slug.data,
                          body=active_form.body.data,
                          banner=banner_name,
                          attachments=file_name)
                commit()
                return p.id

            if active_form.validate_on_submit():
                if active_form.type.is_meeting:
                    if active_form.meeting_id.data and Meeting.exists(
                            id=active_form.meeting_id.data,
                            post_type=MeetingPostType.MEETING.value):
                        return redirect(url_for('.blog_post', post=add_post()))
                    active_form.meeting_id.errors = ['Bad parent']
                else:
                    return redirect(url_for('.blog_post', post=add_post()))

        elif admin and form == FormRoute.NEW_MEMBER_PAGE:
            message = 'New Member'
            tabs[6]['active'] = True
            active_form = TeamForm()
            if active_form.validate_on_submit():
                banner_name, file_name = combo_save(active_form.banner_field,
                                                    active_form.attachment)
                p = TeamPost(type=active_form.type,
                             title=active_form.title.data,
                             slug=active_form.slug.data,
                             body=active_form.body.data,
                             banner=banner_name,
                             attachments=file_name,
                             author=current_user.get_user(),
                             role=active_form.role.data,
                             scopus=active_form.scopus.data,
                             order=active_form.order.data)
                commit()
                return redirect(url_for('.blog_post', post=p.id))

        elif admin and form == FormRoute.BAN_USER:
            message = 'Ban User'
            tabs[7]['active'] = True
            active_form = BanUserForm()
            if active_form.validate_on_submit():
                u = User.get(email=active_form.email.data.lower())
                u.active = False
                flash('Successfully banned %s %s (%s)' %
                      (u.name, u.surname, u.email))

        elif admin and form == FormRoute.CHANGE_USER_ROLE:
            message = 'Change Role'
            tabs[8]['active'] = True
            active_form = ChangeRoleForm()
            if active_form.validate_on_submit():
                u = User.get(email=active_form.email.data.lower())
                u.user_role = active_form.type.value
                flash('Successfully changed %s %s (%s) role' %
                      (u.name, u.surname, u.email))

        else:  # admin or GTFO
            return redirect(url_for('.profile'))

        return render_template("forms.html",
                               subtitle='Profile',
                               title=current_user.full_name,
                               tabs=tabs,
                               form=active_form,
                               message=message)
Ejemplo n.º 56
0
 def update(self, obj):
     d = self.from_dict(obj)
     entity = self.klass.get(id=d['id'])
     entity.set(**d)
     commit()
     return self.to_dict(entity)
Ejemplo n.º 57
0
    def instantiate(self, request, context):
        """
        app 实例化
        :param request:
        :param context:
        :return:
        """
        LOG.info('receive instantiate msg...')
        res = TerminateResponse(status=utils.FAILURE)

        parameter = InstantiateRequest(request)

        LOG.debug('校验access token, host ip')
        host_ip = validate_input_params(parameter)
        if host_ip is None:
            return res

        LOG.debug('获取实例ID')
        app_instance_id = parameter.app_instance_id
        if app_instance_id is None:
            return res

        LOG.debug('查询数据库是否存在相同记录')
        app_ins_mapper = AppInsMapper.get(app_instance_id=app_instance_id)
        if app_ins_mapper is not None:
            LOG.info('app ins %s exist', app_instance_id)
            return res

        LOG.debug('读取包的hot文件')
        hot_yaml_path = get_hot_yaml_path(parameter.app_package_path)
        if hot_yaml_path is None:
            return res

        LOG.debug('构建heat参数')
        tpl_files, template = template_utils.get_template_contents(
            template_file=hot_yaml_path)
        fields = {
            'stack_name': 'eg-' + ''.join(str(uuid.uuid4()).split('-'))[0:8],
            'template': template,
            'files': dict(list(tpl_files.items()))
        }
        LOG.debug('init heat client')
        heat = openstack_utils.create_heat_client(host_ip)
        try:
            LOG.debug('发送创建stack请求')
            stack_resp = heat.stacks.create(**fields)
        except Exception as exception:
            LOG.error(exception, exc_info=True)
            return res
        AppInsMapper(app_instance_id=app_instance_id,
                     host_ip=host_ip,
                     stack_id=stack_resp['stack']['id'],
                     operational_status=utils.INSTANTIATING)
        LOG.debug('更新数据库')
        commit()

        LOG.debug('开始更新状态定时任务')
        start_check_stack_status(app_instance_id=app_instance_id)

        res.status = utils.SUCCESS
        LOG.debug('消息处理完成')
        return res
Ejemplo n.º 58
0
def rm_birthdate(user):
    _ = Birthday.select(lambda birthdate: birthdate.user_id == user.id).first().delete()
    orm.commit()
    return f'Birthdate has been removed for {user.name}.'
Ejemplo n.º 59
0
 def save(self):
     try:
         orm.commit()
     except:
         pass
     return self
Ejemplo n.º 60
0
def generate_api():
    try:
        options = {}
        race = False
        meta_options_source = {}
        if 'file' in request.files:
            file = request.files['file']
            options = get_yaml_data(file)
            if type(options) == str:
                return {"text": options}, 400
            if "race" in request.form:
                race = bool(0 if request.form["race"] in
                            {"false"} else int(request.form["race"]))
            meta_options_source = request.form

        json_data = request.get_json()
        if json_data:
            meta_options_source = json_data
            if 'weights' in json_data:
                # example: options = {"player1weights" : {<weightsdata>}}
                options = json_data["weights"]
            if "race" in json_data:
                race = bool(0 if json_data["race"] in
                            {"false"} else int(json_data["race"]))

        if not options:
            return {
                "text":
                "No options found. Expected file attachment or json weights."
            }, 400

        if len(options) > app.config["MAX_ROLL"]:
            return {
                "text": "Max size of multiworld exceeded",
                "detail": app.config["MAX_ROLL"]
            }, 409
        meta = get_meta(meta_options_source)
        meta["race"] = race
        results, gen_options = roll_options(options, meta["plando_options"])
        if any(type(result) == str for result in results.values()):
            return {"text": str(results), "detail": results}, 400
        else:
            gen = Generation(
                options=pickle.dumps({
                    name: vars(options)
                    for name, options in gen_options.items()
                }),
                # convert to json compatible
                meta=json.dumps(meta),
                state=STATE_QUEUED,
                owner=session["_id"])
            commit()
            return {
                "text":
                f"Generation of seed {gen.id} started successfully.",
                "detail":
                gen.id,
                "encoded":
                app.url_map.converters["suuid"].to_url(None, gen.id),
                "wait_api_url":
                url_for("api.wait_seed_api", seed=gen.id, _external=True),
                "url":
                url_for("wait_seed", seed=gen.id, _external=True)
            }, 201
    except Exception as e:
        return {"text": "Uncaught Exception:" + str(e)}, 500