soonmyeong2

improve search

wello_firebase_SDKKey.json
__pycache__
vip_key.jks
\ No newline at end of file
vip_key.jks
backend/wello_firebase_SDKKey.json
\ No newline at end of file
......
#-*- coding: utf-8 -*-
from datetime import datetime, timedelta
import re
class D_day:
def __init__(self, date_str):
self.date = date_str
def dday_calculate(self, date):
y_m_d = date.split("-")
return (datetime.now() - datetime(int(y_m_d[0]), int(y_m_d[1]), int(y_m_d[2]))).days
def date_calculate(self):
dates = re.findall(r'[0-9]{2,4}[.|-][0-9]{1,2}[.|-][0-9]{1,2}|~', self.date)
for i in range(len(dates)):
dates[i] = dates[i].replace(".", "-")
# 날짜가 없는 경우
if len(dates) == 0:
return "상시"
# XXX ~
if dates[-1] == "~":
dday = self.dday_calculate(dates[0])
if dday > 0:
return "진행중"
else:
return "준비중"
# ~ XXX and XXX ~ XXX
if dates[-1] != "~":
dday = self.dday_calculate(dates[-1])
if dday < 0:
return "D"+str(dday)
else:
return "종료"
# except
return "상 시"
def update_date(self, date):
self.date = date
#### example
'''
a=D_day("2019.11.20")
print(a.date_calculate())
a.update_date("2019.11.21")
print(a.date_calculate())
a.update_date("~2019.11.30")
print(a.date_calculate())
a.update_date("2019.10.11~2019.11.27")
print(a.date_calculate())
a.update_date("2019.10.11~")
print(a.date_calculate())
'''
import hashlib
from firebase_admin import db
from firebase_admin import credentials
import firebase_admin
import csv
cred = credentials.Certificate('wello_firebase_SDKKey.json')
firebase_admin.initialize_app(cred, {'databaseURL': 'https://capstone-vip.firebaseio.com/'})
ref = db.reference()
policies = ref.get()
## compare dict
policy_dict = dict()
def policy_hash_writer(policies):
with open('./hash_policy.csv', 'w', encoding='utf-8', newline='') as csvfile:
wr = csv.writer(csvfile)
for policy in policies:
sha = hashlib.sha256()
sha.update(str(policy).encode('utf-8'))
wr.writerow([policy["Value"], sha.hexdigest()])
def policy_db_reader():
for policy in policies:
if policy["Value"] in policy_dict.keys():
sha = hashlib.sha256()
sha.update(str(policy).encode('utf-8'))
if policy_dict[policy["Value"]] != sha.hexdigest():
print("change contents : ", policy["Value"], ".", policy["Policy"])
else:
print("new policy : ", policy["Value"], ". ", policy["Policy"])
def policy_hash_reader():
with open('./hash_policy.csv', 'r', encoding='utf-8') as csvfile:
rdr = csv.reader(csvfile)
for r in rdr:
policy_dict[r[0]] = r[1]
#policy_hash_writer(policies)
policy_hash_reader()
policy_db_reader()
from firebase_admin import db
from firebase_admin import credentials
import firebase_admin
from D_dayCalculator import D_day
import json
cred = credentials.Certificate('wello_firebase_SDKKey.json')
firebase_admin.initialize_app(cred, {'databaseURL': 'https://capstone-vip.firebaseio.com/'})
ref = db.reference()
policies = ref.get()
date = D_day("1970.01.01")
#with open('view_count_raw.json', 'rt', encoding='utf-8') as json_file:
# view_count = json.load(json_file)
for policy in policies:
# 날짜 갱신
date.update_date(policy["Date"])
print(date.date_calculate())
ref.child(policy["Value"]).child("D_day").set(date.date_calculate())
0,d24548533c984425a9a96cbd23e0085baed58a16d26d2764ee3e08f4ec9f2713
1,4f2e40e552527f48278fa2cdfadfa34e61c5a1672d82dc2ff42fcb4bff484cc2
2,7f41b893ec6ca567b928f9ba975c87e31db98a14fa6bc1c28431ab3a244cca43
3,fb6094dc6ba8c21846557664fda37a808f9877f35f301c444194b484e6cf38ae
4,121b23de7cf0d313077a208739b7a202ddfe6442c3f62dd2ed0cb475411c3bb8
5,26e05536f3fc6a844af4a746ecd070157180e4787fb122cf18b5dc8b91d2ff63
6,2809644d986b0226b080fdffbe7d3d1453095a12984101edbaefbf61821a8848
7,c7e3ac97575b1006424d0f2a391df327dc249067f0361d604355700bbe780102
8,3d7f2a439aa277c88101b08d2af865d6610f9791b614d9bbcce5a5f424736bb5
9,fba861e8ecc5f5411dec793409f8a98a96cbbb738fba74be397294e288dc7a4b
from firebase_admin import messaging
from firebase_admin import credentials
from firebase_admin import datetime
from firebase_admin import db
import firebase_admin
import json
import re
cred = credentials.Certificate('wello_firebase_SDKKey.json')
firebase_admin.initialize_app(cred, {'databaseURL': 'https://wello-topic.firebaseio.com/'})
ref = db.reference()
topics = list(ref.get())
pre_topic = list()
def send_to_topic(policy, topic):
message = messaging.Message(
android=messaging.AndroidConfig(
ttl=datetime.timedelta(seconds=3600),
priority='normal',
notification=messaging.AndroidNotification(
title='새 정책 알람',
body=policy,
icon='@drawable/mini',
color='#29ABE2',
sound='default'
),
),
data={
'score': '850',
'time': '2:45',
},
webpush=messaging.WebpushConfig(
notification=messaging.WebpushNotification(
title='웹 알림',
body='TEST',
icon='',
),
),
topic=topic,
)
response = messaging.send(message)
print('Successfully sent message:', response)
for topic in topics:
categorys = re.findall('c[0-9]+[_][0-9]+', topic)
for i in range(len(categorys) - 1, -1, -1):
if '1' == categorys[i].split('_')[-1]:
categorys.pop(i)
pre_topic.append(categorys)
print('new policy category : ', end = '')
policy = input()
policy_category = re.findall('c[0-9]+[_][0-9]+', policy)
policy_category_list = re.findall('c[0-9]+', policy)
push_index = list()
flag = True
for i, categorys in enumerate(pre_topic):
for category in categorys:
if category.split('_')[0] in policy_category_list:
if category not in policy_category:
flag = False
break
if flag: push_index.append(i)
flag = True
for push in push_index:
send_to_topic('[가정복지부] 기성이를 보유하신 가정에 지원금을 드립니다.', topics[push])
#-*- coding: utf-8 -*-
from datetime import datetime, timedelta
import json
import re
def dday_calculate(date):
y_m_d = date.split("-")
return (datetime.now() - datetime(int(y_m_d[0]), int(y_m_d[1]), int(y_m_d[2]))).days
def date_calculate(url):
dates = re.findall(r'[0-9]{2,4}[.|-][0-9]{1,2}[.|-][0-9]{1,2}|~', url)
for i in range(len(dates)):
dates[i] = dates[i].replace(".", "-")
# 날짜가 없는 경우
if len(dates) == 0:
return "상시"
# XXX ~
if dates[-1] == "~":
dday = dday_calculate(dates[0])
if dday > 0:
return "진행중"
else:
return "준비중"
# ~ XXX and XXX ~ XXX
if dates[-1] != "~":
dday = dday_calculate(dates[-1])
if dday < 0:
return "D"+str(dday)
else:
return "종료"
# except
return "상 시"
with open('d.json', 'rt', encoding='utf-8') as json_file:
json_data = json.load(json_file)
for js in json_data:
for key, value in js.items():
if type(value) != str and key != 'View':
js[key] = str(value)
if key == "Link" and value[0] == '[':
js[key] = value[1:-1]
# critical point
if key == "View":
js["D_day"] = date_calculate(js["Date"])
break
###############
with open('result.json', 'w', encoding='utf-8') as make_file:
make_file.write('[')
for i, js in enumerate(json_data):
json.dump(js, make_file, indent="\t", ensure_ascii=False)
if i != len(json_data) - 1:
make_file.write(',')
make_file.write(']')
{
"0": {
"2019-11-19": 14
},
"1": {
"2019-11-19": 3
},
"2": {
"2019-11-19": 13
},
"3": {
"2019-11-19": 4
},
"4": {
"2019-11-19": 3
},
"5": {
"2019-11-19": 4
},
"6": {
"2019-11-19": 6
},
"7": {
"2019-11-19": 3
},
"8": {
"2019-11-19": 4
},
"9": {
"2019-11-19": 11
}
}
\ No newline at end of file
from firebase_admin import db
from firebase_admin import credentials
import firebase_admin
import json
from datetime import datetime
cred = credentials.Certificate('wello_firebase_SDKKey.json')
firebase_admin.initialize_app(cred, {'databaseURL': 'https://capstone-vip.firebaseio.com/'})
ref = db.reference()
policies = ref.get()
## compare dict
json_data = dict()
today = str(datetime.now().year) + "-" + str(datetime.now().month) + "-" + str(datetime.now().day)
def view_count_raw_writer():
with open('./view_count_raw.json', 'w', encoding='utf-8') as make_file:
json.dump(json_data, make_file, indent="\t")
def count_update():
for policy in policies:
if policy["Value"] in json_data.keys():
if policy["Value"][datetime.now()] in json_data["Value"].keys():
json_data[policy["Value"]][today] = abs(policy["View"])
else:
json_data[policy["Value"]][today] = dict()
json_data[policy["Value"]][today] = abs(policy["View"])
else:
json_data[policy["Value"]] = dict()
json_data[policy["Value"]][today] = abs(policy["View"])
def view_count_raw_reader():
with open('./view_count_raw.json', 'r', encoding='utf-8') as json_file:
json_data = json.load(json_file)
view_count_raw_reader()
count_update()
print(json.dumps(json_data, indent="\t"))
view_count_raw_writer()
......@@ -17,26 +17,6 @@ class AccountSettingActivity : AppCompatActivity() {
val bottomNavigationView: BottomNavigationView = findViewById(R.id.bottomNavigation_account_setting) as BottomNavigationView
bottomNavigationView.selectedItemId = R.id.bottomInfo
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
/*
val prof: SharedPreferences = getSharedPreferences("policy_key", Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor=prof.edit()
input_db.setOnClickListener{
editor.putString("0", "[신한금융그룹] 신한 희망사회프로젝트 위기가정 재기지원사업 2년차 사업(2019년 5월~2020년 4월)")
editor.putString("1", "2020년 동계 아름드리 대학생 해외봉사단원 모집")
editor.putString("2", "초록우산 어린이재단 인재양성사업 - 2020 아이리더 모집공고")
editor.putString("3", "(열매나눔복지재단, 처갓집양념치킨)2019 저소득가구 창업지원사업 처갓집양념치킨 창업자 모집공고(5.31-)")
editor.putString("4", "[2017년도] 예비부부교실 / 신혼부부교실 : 연간일정")
editor.putString("5", "신생아지원")
editor.putString("6", "성폭력피해아동청소년 전용쉼터운영지원")
editor.putString("7", "국가유공자등취업지원")
editor.putString("8", "결혼이민자 통번역 서비스")
editor.putString("9", "한부모가족자녀 교육비 지원")
editor.commit()
}
*/
}
private val mOnNavigationItemSelectedListener=
BottomNavigationView.OnNavigationItemSelectedListener{ item->
......
......@@ -31,25 +31,6 @@ class MainActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/////
val prof: SharedPreferences = getSharedPreferences("policy_key", Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor=prof.edit()
editor.putString("0", "[신한금융그룹] 신한 희망사회프로젝트 위기가정 재기지원사업 2년차 사업(2019년 5월~2020년 4월)")
editor.putString("1", "2020년 동계 아름드리 대학생 해외봉사단원 모집")
editor.putString("2", "초록우산 어린이재단 인재양성사업 - 2020 아이리더 모집공고")
editor.putString("3", "(열매나눔복지재단, 처갓집양념치킨)2019 저소득가구 창업지원사업 처갓집양념치킨 창업자 모집공고(5.31-)")
editor.putString("4", "[2017년도] 예비부부교실 / 신혼부부교실 : 연간일정")
editor.putString("5", "신생아지원")
editor.putString("6", "성폭력피해아동청소년 전용쉼터운영지원")
editor.putString("7", "국가유공자등취업지원")
editor.putString("8", "결혼이민자 통번역 서비스")
editor.putString("9", "한부모가족자녀 교육비 지원")
editor.commit()
/////
emailSigninBtn.setOnClickListener{
loginEmail()
}
......
......@@ -55,7 +55,7 @@ class QnAAdapter : RecyclerView.Adapter<QnAAdapter.MainViewHolder>() {
tvTitle.text = item.answer
tvContent.text = item.question
tvSecond.setOnClickListener{
tvTitle.setVisibility(View.GONE)
//tvTitle.setVisibility(View.GONE)
}
/* if (item.arrow != "") {
......
......@@ -4,7 +4,6 @@ import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
//import androidx.appcompat.widget.SearchView
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.view.View
......@@ -22,13 +21,19 @@ import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.ValueEventListener
import androidx.fragment.app.FragmentActivity
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
data class MemoItem(
val Target : String = "",
val Policy : String = "",
val Content : String = "",
val Link : String = ""
val Link : String = "",
val Value : String = ""
)
var database = FirebaseDatabase.getInstance().reference
......@@ -49,6 +54,26 @@ class SearchActivity : AppCompatActivity() {
//searchView.onActionViewExpanded(); //new Added line
searchView.setIconifiedByDefault(false)
///
database.orderByChild("Policy").addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val size = dataSnapshot.childrenCount
//Toast.makeText(this@SearchActivity, size.toString(), Toast.LENGTH_SHORT).show()
if (prof.getString("len", "-1") != size.toString()) {
//Toast.makeText(this@SearchActivity, "비 효율", Toast.LENGTH_SHORT).show()
editor.putString("len", size.toString())
for (memoSnapshot in dataSnapshot.children) {
val memo = memoSnapshot.getValue(MemoItem::class.java)
editor.putString(memo!!.Value, memo!!.Policy)
}
editor.commit()
}
}
override fun onCancelled(p0: DatabaseError) {
}
})
fun CloseKeyboard()
{
var view = this.currentFocus
......@@ -71,9 +96,8 @@ class SearchActivity : AppCompatActivity() {
CloseKeyboard()
// DB 내 목록에서 맞는거 찾는 부분
val arr = arrayOf(0,1,2,3,4,5,6,7,8,9)
val key = arrayListOf<String>()
for (i in arr) {
for (i in 0.. (prof.getString("len", "-1")!!.toInt() -1)) {
val temp = prof.getString("$i", "fail")
val regex = "$query".toRegex()
val matchResult : MatchResult? = regex.find(temp.toString())
......
......@@ -78,12 +78,6 @@
android:text="회원 탈퇴 (준비중)"
android:textSize="17dp" />
<Button
android:id="@+id/input_db"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="디비에 넣기" />
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
......
......@@ -24,7 +24,7 @@
<TextView
android:id="@+id/questionText"
android:layout_width="wrap_content"
android:layout_height="65dp"
android:layout_height="50dp"
android:layout_gravity="center|right"
android:layout_weight="1"
android:gravity="center|left"
......@@ -47,9 +47,9 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F1F9FF"
android:lineSpacingExtra="6dp"
android:paddingLeft="11dp"
android:text="TextView"
android:lineSpacingExtra="6dp"
android:textSize="13dp" />
</LinearLayout>
......
No preview for this file type