def test_auth_custom_password(self): test_password = '******' query_insert = sqlalchemy.text( 'INSERT INTO users (username, password) VALUES (:username, :password)' ) db.get_conn().execute(query_insert, username=self.testuser, password=test_password) user.load_user_data() with self.assertRaises(Exception): user.get_user_token(self.testuser) query_delete = sqlalchemy.text( 'DELETE FROM users WHERE ((username = :username))') db.get_conn().execute(query_delete, username=self.testuser) user.load_user_data()
def setup(): """ iniate bot_controller """ user.load_user_data() auth_token = user.get_user_token(os.getenv('TEST_USER')) groupware.load_project_list(auth_token) print('PROJECT_LIST:', groupware.PROJECT_LIST) print('user.ALIAS:', user.ALIAS)
def post_report_single(username, fields, image_data): """ send a single report """ print('sending report for ' + username) files = { 'evidenceTask': ('image.' + image_data['type'], image_data['content'], 'image/' + image_data['type']), } auth_token = user.get_user_token(username) res = groupware.post_report(auth_token, fields, files) print('ok') return True
def test_auth_custom_alias(self): test_alias = 'dummy_alias' query_insert = sqlalchemy.text( 'INSERT INTO users (username, password) VALUES (:username, :password)' ) db.get_conn().execute(query_insert, username=self.testuser, password=self.testuser) user.load_user_data() # make sure alias not exists yet self.assertIsNotNone(user.get_user_token(self.testuser)) with self.assertRaises(Exception): user.get_user_token(test_alias) # test adding alias user.set_alias(self.testuser, test_alias) self.assertIsNotNone(user.get_user_token(test_alias)) query_delete = sqlalchemy.text( 'DELETE FROM users WHERE ((username = :username))') db.get_conn().execute(query_delete, username=self.testuser)
def action_checkout(item): """ action for /checkout command """ # parse input if 'caption' in item['message']: input_text = item['message']['caption'] elif 'text' in item['message']: input_text = item['message']['text'] lines = input_text.split("\n") first_params = lines[0] first_params = first_params[first_params.find(' ')+1 :] # start from after first ' ' first_params = first_params.split('|') # split with '|' if len(first_params) != 1 : bot.process_error(item, 'Wrong format') return current_time = datetime.now(timezone('Asia/Jakarta')) current_time_utc = current_time.astimezone(timezone('UTC')) checkoutDateTimeFormat = current_time_utc.strftime('%Y-%m-%dT%H:%M:%I.000Z') dateNow = current_time.strftime('%Y-%m-%d') hourMinuteNow = current_time.strftime('%H:%M') username = first_params[0].strip() data = { 'date': checkoutDateTimeFormat, } getToken = user.get_user_token(username) req = requests.post( url=CHECKOUT_URL, headers={ 'Authorization': 'Bearer ' + getToken, }, data=data ) msg = "%s | Checkout Pukul %s %s" % (username , hourMinuteNow, bot.EMOJI_SUCCESS) responseMessage = json.loads(req.text) if req.status_code >= 300: errors = "%s | Checkout Gagal | %s %s " % (username, responseMessage["message"], bot.EMOJI_FAILED) return bot.process_error(item, errors) else: return bot.reply_message(item, msg)
def test_auth_duplicate_alias(self): test_alias = 'dummy_alias' query_insert = sqlalchemy.text( 'INSERT INTO users (username, password, alias) VALUES (:username, :password, :alias)' ) db.get_conn().execute(query_insert, username=self.testuser, password=self.testuser, alias=test_alias) user.load_user_data() # make sure alias exists self.assertIsNotNone(user.get_user_token(test_alias)) # test adding alias res = user.set_alias(self.testuser, test_alias) self.assertFalse(res[0]) query_delete = sqlalchemy.text( 'DELETE FROM users WHERE ((username = :username))') db.get_conn().execute(query_delete, username=self.testuser)
def process_report(telegram_item, input_fields, image_data, peserta=None, save_history=True): """ process parsing result from our telegram processor""" if save_history: chat_history.insert(chat_id=telegram_item['message']['chat']['id'], message_id=telegram_item['message']['message_id'], content=telegram_item) print('>>> PROCESSING REPORT >>>') print('Fields:', input_fields, 'File type:', image_data['type']) fields = json.loads(json.dumps( input_fields)) # clone fields to avoid changing source values field_aliases = { 'tanggal': 'dateTask', 'kesulitan': 'difficultyTask', 'penyelenggara': 'organizerTask', 'tugasutama': 'isMainTask', 'lokasi': 'workPlace', 'lampiran': 'documentTask', } for field in field_aliases: if field in fields: fields[field_aliases[field]] = fields[field] default_date_task = datetime.fromtimestamp(telegram_item['message']['date']) \ if telegram_item['message']['date'] else \ datetime.now() defaults_values = { 'dateTask': default_date_task.strftime('%Y-%m-%d'), 'difficultyTask': 3, 'organizerTask': 'PLD', 'isMainTask': 'true', 'isDocumentLink': 'true', 'workPlace': 'WFH', 'documentTask': 'null', } for field in defaults_values: if field not in fields: fields[field] = defaults_values[field] fields['dateTask'] += groupware.TIMESTAMP_TRAIL_FORMAT errors = groupware.validate_report(fields) # cek groupware api status req = requests.get(url=groupware.LOGBOOK_API_URL, headers={ 'Authorization': 'Bearer ' + user.get_user_token(os.getenv('TEST_USER')), }) if req.status_code >= 300: errors.append( "Groupware status code : {}\n\nMohon maaf, sedang ada ganguan pada sistem groupware. Silahkan coba lagi setelah beberapa saat" .format(req.status_code)) if peserta is None: if 'peserta' in fields: peserta = fields['peserta'] else: errors.append('tidak ada peserta yang disebutkan') # validate accumulated errors if len(errors) > 0: msg = ''.join(["\n- " + str(e) for e in errors]) process_error(telegram_item, msg) return None def send_result(result): reply_message(telegram_item, "Hasil:\n" + "\n".join(results), is_direct_reply=True) # processing all peserta results = [] for username in peserta: status = 'Berhasil ' bullet = EMOJI_SUCCESS try: post_report_single(username, fields, image_data) except Exception as e: print(e) print(traceback.print_exc()) status = 'Gagal - {}'.format(e) bullet = EMOJI_FAILED results.append("{} {} | {}".format(bullet, username, status)) # display result for each 100 user if len(results) >= 100: send_result(results) results = [] # if there are still results left if len(results) > 0: send_result(results) return True
def action_checkin(item, peserta=None): """ action for /checkin command """ # parse input if 'caption' in item['message']: input_text = item['message']['caption'] elif 'text' in item['message']: input_text = item['message']['text'] lines = input_text.split("\n") first_params = lines[0] first_params = first_params[first_params.find(' ') + 1:] # start from after first ' ' first_params = first_params.split('|') # split with '|' if len(first_params) != 2: bot.process_error(item, 'Wrong format') return current_time = datetime.now(timezone('Asia/Jakarta')) current_time_utc = current_time.astimezone(timezone('UTC')) checkinDateTimeFormat = current_time_utc.strftime('%Y-%m-%dT%H:%M:%I.000Z') dateNow = current_time.strftime('%Y-%m-%d') hourMinuteNow = current_time.strftime('%H:%M') username = first_params[0].strip() location = first_params[1].strip().upper() locationAvailable = ['WFH', 'WFO', 'PERJADIN'] if location in locationAvailable: data = { 'date': checkinDateTimeFormat, 'location': location, 'message': "HADIR", 'note': "", } getToken = user.get_user_token(username) req = requests.post(url=CHECKIN_URL, headers={ 'Authorization': 'Bearer ' + getToken, }, data=data) msg = "%s | HADIR %s Pukul %s %s %s" % ( username, dateNow, hourMinuteNow, bot.EMOJI_SUCCESS, location) responseMessage = json.loads(req.text) if req.status_code >= 300: errors = "%s | Checkin Gagal | %s %s " % ( username, responseMessage["message"], bot.EMOJI_FAILED) return bot.process_error(item, errors) else: return bot.reply_message(item, msg) else: msg = "Checkin gagal | Jenis kehadiran anda tidak sesuai" return bot.reply_message(item, msg)
def is_today_holiday(): """ simple wrapper for groupware.check_date_is_holiday() """ auth_token = user.get_user_token(os.getenv('TEST_USER')) return groupware.check_date_is_holiday(auth_token)