Example #1
0
 def add_expertise(self, member_ref, member_expertise, platform_response):
     expertise_data = {'member': [member_ref]}
     expertise_ref = None
     db = firestore.client()
     #expertise_query_ref=db.collection("expertise").where("expertise_category", "==", member_expertise).get()
     expertise_ref = db.collection("product_expertise_mapping").document(
         member_expertise)
     print('Inside add expertise. Ref is {}'.format(expertise_ref))
     try:
         expertise_obj = expertise_ref.get(
         )  #This will throw error if the expertise doesn't exist.
         member_array = expertise_obj.to_dict().get('member')
         if member_ref in member_array:
             #Member is already registered as an expert for expertise
             platform_response = "You are already registered as an expert for {}".format(
                 member_expertise)
         else:
             member_array.append(member_ref)
             expertise_ref.update({'member': member_array},
                                  firestore.CreateIfMissingOption(True))
     except google.cloud.exceptions.NotFound:
         #Don't hate me. Apparently this is the EAFP way in Python - https://docs.python.org/3.6/glossary.html#term-eafp
         expertise_ref = db.collection(
             u'product_expertise_mapping').document(member_expertise).set(
                 expertise_data)
         print("Added expertise")
     member_ref.update({'is_helper': True})
     platform_response = Template(platform_response).safe_substitute(
         arg1=member_expertise)
     return platform_response
Example #2
0
    def show_delete_restaurant(self):
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_DELETE_RESTAURANT},
            firestore.CreateIfMissingOption(True))

        user = fs.collection(Const.COL_USER).document(self.user_key).get()
        group = user.get(Const.FIELD_GROUP)

        ref = fs.collection(Const.COL_GROUP).document(group).get()
        restaurants = ref._data.get(Const.FIELD_RESTAURANT)

        restaurant_list = []
        for key, val in restaurants.items():
            restaurant_list.append(key)

        restaurant_list.append(Const.BTN_GOTO_START)

        rst = {
            "message": {
                "text": '삭제할 대상을 선택해 주세요'
            },
            "keyboard": {
                "type": "buttons",
                "buttons": restaurant_list
            }
        }

        return Util.send_response(rst)
Example #3
0
    def add_restaurant(self):
        user = fs.collection(Const.COL_USER).document(self.user_key).get()
        group = user.get(Const.FIELD_GROUP)
        title = user.get(Const.FIELD_ADD_RESTAURANT_TITLE)
        desc = user.get(Const.FIELD_ADD_RESTAURANT_DESC)

        try:
            ref = fs.collection(Const.COL_GROUP).document(group).get()
            restaurant = ref._data.get(Const.FIELD_RESTAURANT)
        except:
            restaurant = {}

        if restaurant is None:
            restaurant = {}

        restaurant[title] = {
            'desc': desc,
            'user': self.user_key,
            'added': Util.get_day_str()
        }

        if Util.is_img(desc):
            restaurant[title][Const.FIELD_IMG_SRC] = desc

        fs.collection(Const.COL_GROUP).document(group).update(
            {Const.FIELD_RESTAURANT: restaurant},
            firestore.CreateIfMissingOption(True))

        if Util.is_img(desc):
            msg = '[{}] 이(가) 등록되었습니다'.format(title)
            return Util.show_start_menu(msg, desc)

        msg = '이름:{}\n설명:{}\n등록되었습니다'.format(title, desc)
        return Util.show_start_menu(msg)
Example #4
0
    def show_group_list(self):
        # 상태 설정
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_SELECT_GROUP},
            firestore.CreateIfMissingOption(True))

        # 그룹 목록 가져오기
        groups = fs.collection(Const.COL_GROUP).get()
        group_list = []
        for doc in groups:
            group_list.append(doc.id)

        group_list.append(Const.BTN_GOTO_START)

        rst = {
            "message": {
                "text": '그룹을 선택해 주세요'
            },
            "keyboard": {
                "type": "buttons",
                "buttons": group_list
            }
        }

        return Util.send_response(rst)
Example #5
0
    def group_selected(self):
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_GROUP: self.content},
            firestore.CreateIfMissingOption(True))

        msg = '[{}] 을(를) 선택하였습니다'.format(self.content)
        return Util.show_start_menu(msg)
Example #6
0
    def show_add_restaurant_confirm(self):
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_ADD_RESTAURANT_CONFIRM},
            firestore.CreateIfMissingOption(True))

        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_ADD_RESTAURANT_DESC: self.content},
            firestore.CreateIfMissingOption(True))

        user = fs.collection(Const.COL_USER).document(self.user_key).get()
        title = user.get(Const.FIELD_ADD_RESTAURANT_TITLE)
        desc = self.content

        if Util.is_img(desc):
            rst = {
                "message": {
                    "text":
                    '입력하신 음식점은 다음과 같습니다.\n\n이름:{}\n\n등록하시겠습니까?'.format(title),
                    "photo": {
                        "url": desc,
                        "width": 640,
                        "height": 480
                    }
                },
                "keyboard": {
                    "type":
                    "buttons",
                    "buttons":
                    [Const.BTN_ADD_RESTAURANT_CONFIRM, Const.BTN_GOTO_START]
                }
            }
        else:
            rst = {
                "message": {
                    "text":
                    '입력하신 음식점은 다음과 같습니다.\n\n이름:{}\n설명:{}\n\n등록하시겠습니까?'.format(
                        title, desc)
                },
                "keyboard": {
                    "type":
                    "buttons",
                    "buttons":
                    [Const.BTN_ADD_RESTAURANT_CONFIRM, Const.BTN_GOTO_START]
                }
            }

        return Util.send_response(rst)
Example #7
0
    def show_add_restaurant(self):
        # state : add_restaurant
        # 1. 이름을 입력해 주세요
        # 2. 설명을 작성해 주세요.
        # 상태 설정
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_ADD_RESTAURANT_TITLE},
            firestore.CreateIfMissingOption(True))

        rst = {"message": {"text": '음식점 이름을 입력해 주세요'}}

        return Util.send_response(rst)
Example #8
0
    def show_add_restaurant_desc(self):
        # content = 음식점 이름
        # 상태 설정
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_ADD_RESTAURANT_DESC},
            firestore.CreateIfMissingOption(True))

        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_ADD_RESTAURANT_TITLE: self.content})

        rst = {"message": {"text": '음식점 사진을 추가해 주세요'}}

        return Util.send_response(rst)
Example #9
0
    def show_delete_restaurant_confirm(self):
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_DELETE_RESTAURANT},
            firestore.CreateIfMissingOption(True))

        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_DELETE_RESTAURANT_TITLE: self.content},
            firestore.CreateIfMissingOption(True))

        title = self.content

        rst = {
            "message": {
                "text": '[{}] 을(를) 삭제하겠습니까?'.format(title)
            },
            "keyboard": {
                "type":
                "buttons",
                "buttons":
                [Const.BTN_DELETE_RESTAURANT_CONFIRM, Const.BTN_GOTO_START]
            }
        }

        return Util.send_response(rst)
Example #10
0
    def set_method(self, args, event):
        if len(args) == 0:
            response = 'Usage: user set username'
            asyncio.run_coroutine_threadsafe(
                self.send(self.conversation(event=event), response),
                self.pearl.loop)
            return

        usernames = self.usernames(event)
        uid = 'u' + event.sender_id.gaia_id
        new = args[0].lower()
        old = self.username(event, uid)

        if len(new) < 3 or len(new) > 12:
            response = 'Username must be between 3 and 12 characters long.'
            asyncio.run_coroutine_threadsafe(
                self.send(self.conversation(event=event), response),
                self.pearl.loop)
            return

        if not re.match('^[a-zA-Z0-9]*$', new):
            response = 'Username must only contain alphanumeric characters.'
            asyncio.run_coroutine_threadsafe(
                self.send(self.conversation(event=event), response),
                self.pearl.loop)
            return

        if new == old:
            response = 'That\'s your current username, silly!'
            asyncio.run_coroutine_threadsafe(
                self.send(self.conversation(event=event), response),
                self.pearl.loop)
            return

        if new in usernames:
            response = 'Sorry, <b>{}</b> is already taken.'.format(new)
            asyncio.run_coroutine_threadsafe(
                self.send(self.conversation(event=event), response),
                self.pearl.loop)
            return

        self.dbcall(
            event, lambda: self.user_ref.document('username').update(
                {uid: new}, firestore.CreateIfMissingOption(True)))
        response = 'You are now set to <b>{}</b>!'.format(new)
        asyncio.run_coroutine_threadsafe(
            self.send(self.conversation(event=event), response),
            self.pearl.loop)
Example #11
0
 def handle(self, args, event):
     if len(args) > 0 and args[0] in self.methods:
         try:
             if not self.user_ref:
                 self.user_ref = self.pearl.plugins[
                     'firebase'].db.collection('user')
                 self.dbcall(
                     event, lambda: self.user_ref.document('username').
                     update({}, firestore.CreateIfMissingOption(True)))
             self.methods[args[0]](args[1:], event)
         except:
             return
     else:
         asyncio.run_coroutine_threadsafe(
             self.send(self.conversation(event=event), self.usage),
             self.pearl.loop)
         return
Example #12
0
    def delete_restaurant(self):
        user = fs.collection(Const.COL_USER).document(self.user_key).get()
        group = user.get(Const.FIELD_GROUP)
        title = user.get(Const.FIELD_DELETE_RESTAURANT_TITLE)

        try:
            ref = fs.collection(Const.COL_GROUP).document(group).get()
            restaurant = ref._data.get(Const.FIELD_RESTAURANT)
            del restaurant[title]
        except:
            restaurant = {}

        fs.collection(Const.COL_GROUP).document(group).update(
            {Const.FIELD_RESTAURANT: restaurant},
            firestore.CreateIfMissingOption(True))

        msg = '[{}] 을(를) 삭제하였습니다.'.format(title)
        return Util.show_start_menu(msg)
Example #13
0
    def show_restaurant_list(self):
        # 상태 설정
        fs.collection(Const.COL_USER).document(self.user_key).update(
            {Const.FIELD_STATE: Const.STATE_SELECT_RESTAURANT},
            firestore.CreateIfMissingOption(True))

        # 그룹이 없으면 그룹 선택으로 보낸다.
        try:
            user = fs.collection(Const.COL_USER).document(self.user_key).get()
            user_group = user.get(Const.FIELD_GROUP)
        except:
            print("NotFound user")
            return self.show_group_list()

        try:
            # 해당 그룹의 식당목록을 가져온다.
            restaurant_list = []

            group = fs.collection(Const.COL_GROUP).document(user_group).get()
            restaurants = group.get(Const.FIELD_RESTAURANT)
            for key, val in restaurants.items():
                restaurant_list.append(key)
        except:
            print('No RESTAURANTS')
            return Util.show_start_menu('등록된 식당이 없습니다')

        shuffle(restaurant_list)

        if len(restaurant_list) > Const.SHOW_COUNT:
            restaurant_list = restaurant_list[:Const.SHOW_COUNT]

        restaurant_list.append(Const.BTN_GOTO_START)

        rst = {
            "message": {
                "text": '식당을 선택해 주세요'
            },
            "keyboard": {
                "type": "buttons",
                "buttons": restaurant_list
            }
        }

        return Util.send_response(rst)
Example #14
0
def firebase_store_chats(messages):
    batch = db.batch()

    for message in messages:
        message_user_id = message['authorDetails']['channelId']
        message_id = message['id'].replace(
            '.', '-')  #firebase can't handle periods in keys
        data = {
            message_id: {
                "message_text": message['snippet']['displayMessage'],
                "message_username": message['authorDetails']['displayName'],
                "chat_id": message['snippet']['liveChatId'],
            }
        }
        # Update batch object
        ref = db.collection(u'messages').document(message_user_id)
        batch.update(ref, data, firestore.CreateIfMissingOption(True))

    batch.commit()
Example #15
0
    def create_history(self, today):
        user = fs.collection(Const.COL_USER).document(self.user_key).get()
        user_group = user.get(Const.FIELD_GROUP)

        # 오늘 기준
        # 5일 전까지 고려
        title_list = []
        for i in range(1, 5 + 1):
            ago_day = Util.get_day_str(-1 * i)
            max_title = self.get_max_selected_restaurant(user_group, ago_day)
            if max_title:
                title_list.append(max_title)

        fs.collection(Const.COL_SELECT).document(user_group).collection(
            Const.COL_HISTORY).document(today).update(
                {Const.FIELD_MAX_HISTORY_LIST: title_list},
                firestore.CreateIfMissingOption(True))

        return title_list
Example #16
0
    def append_conversation_ref(self, member_ref, conversation_ref):
        print('About to append the conversation ID {} to member ID'.format(
            conversation_ref.get().id,
            member_ref.get().id))
        conversations_array = member_ref.get().get('conversations')
        if conversation_ref in conversations_array:
            #Don't do anything.Member is already added to the conversation
            print('Member already added to the conversation')
        else:
            conversations_array.append(conversation_ref)
            member_ref.update(
                {
                    'conversations': conversations_array,
                    'lastactivedate': datetime.datetime.now()
                }, firestore.CreateIfMissingOption(True))
            print('Assigned member to the conversation ID: {}'.format(
                conversation_ref.get().id))

        #member_ref.update({'active_conv_partners':active_helpees_array})
        return True
Example #17
0
    def restaurant_selected(self):
        user = fs.collection(Const.COL_USER).document(self.user_key).get()
        user_group = user.get(Const.FIELD_GROUP)
        today = Util.get_day_str()

        fs.collection(Const.COL_SELECT).document(user_group).collection(
            Const.COL_TODAY).document(today).update(
                {self.user_key: self.content},
                firestore.CreateIfMissingOption(True))

        msg = '[{}] 을(를) 선택하였습니다'.format(self.content)

        try:
            ref = fs.collection(Const.COL_GROUP).document(user_group).get()
            restaurants = ref._data.get(Const.FIELD_RESTAURANT)
            target = restaurants.get(self.content)
            img_src = target.get(Const.FIELD_IMG_SRC)
        except:
            img_src = None

        return Util.show_start_menu(msg, img_src)
Example #18
0
    act_category = tempList1[0]
    act_child_category = tempList1[1]
    act_name = tempList2[0]
    act_speaker = tempList2[1]
    act_organizer = tempList3[0]
    act_co_organizer = tempList3[1]
    act_content = mylist[i][4]
    act_signup_way = tempList4[0]
    act_signup_time_start = tempList4[1]
    act_signup_time_end = tempList4[2]
    act_social_ability = tempList6
    act_participant = tempList7

    activities_ref = db.collection(u'Activities').document(act_id)

    activities_ref.update(
        {
            "act_category": act_category,
            "act_child_category": act_child_category,
            "act_name": act_name,
            "act_speaker": act_speaker,
            "act_organizer": act_organizer,
            "act_co_organizer": act_co_organizer,
            "act_content": act_content,
            "act_sinup_way": act_signup_way,
            "act_signup_time_start": act_signup_time_start,
            "act_sign_up_time_end": act_signup_time_end,
            "act_social_ability": act_social_ability,
            "act_participant": act_participant
        }, firestore.CreateIfMissingOption(True))
Example #19
0
 def _save(self, pk, meta):
     doc_ref = self._get_ref_doc(pk)
     doc_ref.update(meta, firestore.CreateIfMissingOption(True))
Example #20
0
 def assign_helper(self,payload,conversation_ref):
     #Assign this conversation to this expert.
     member_ref = self.core_engine_obj.get_member()
     #self.core_engine_obj.append_conversation_ref(member_ref,conversation_ref)
     ### Add to active conversation partner Map
     conversations_array = member_ref.get().get('conversations')
     member_short_id = ''
     if conversation_ref in conversations_array:
         #Don't do anything.Member is already added to the conversation
         print('Member already added to the conversation')
     else:
         conversations_array.append(conversation_ref)
         active_helpees_map = member_ref.get().get('active_conv_partners')
         print("Active Helpees Map",active_helpees_map)
         member_short_id = (conversation_ref.get().to_dict().get('helpee_ref').get().to_dict().get('first_name')+conversation_ref.get().to_dict().get('helpee_ref').get().to_dict().get('last_name')[0]+''+str(len(active_helpees_map)+1)).lower()
         #dict_key = member_short_id 
         active_helpees_map[member_short_id]=conversation_ref.get().to_dict().get('helpee_ref').get().to_dict().get('fb_id')
         member_ref.update({'conversations':conversations_array,'active_conv_partners':active_helpees_map,'lastactivedate':datetime.now()}, firestore.CreateIfMissingOption(True))
     ####
     conversation_ref.update({'helper_ref':member_ref})
     product_Name = conversation_ref.get().to_dict().get('product')
     payload['message']['text'] = Template(payload['message'].get('text')).safe_substitute(arg1=product_Name)
     if payload['platform'].get('helper_next_state'):
         conversation_ref.update({'helper_state':payload['platform'].get('helper_next_state')})
     if payload['platform'].get('helpee_next_state'):
         conversation_ref.update({'helpee_state':payload['platform'].get('helpee_next_state')})
     #del payload['platform']
     return member_short_id