command.py 5.9 KB
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020-02-13 09:25
# @Author  : Lemon
# @File    : command.py
# @Software: PyCharm
import os

import requests
from fbchat import ThreadType, EmojiSize

from lib import common
import uuid
from base64 import b64decode

from lib.common import WorkPlace


def _send_msg(local_func, remote_func, to, content, thread_type, suffix):
    _type = getattr(ThreadType, thread_type.upper())
    if content.startswith('http'):
        res = remote_func(content, thread_id=to, thread_type=_type)
    else:
        _temp = b64decode(content.encode('utf-8'))
        _temp_path = 'filecache'
        if not os.path.exists(_temp_path): os.mkdir(_temp_path)
        filename = os.path.join(_temp_path, '%s.%s' % (uuid.uuid1().hex, suffix))
        with open(filename, 'wb') as f:
            f.write(_temp)
        try:
            res = local_func(filename, thread_id=to, thread_type=_type)
        except BaseException as err:
            os.remove(filename)
            raise err
    return res


def _upload_binary(upload_func, set_func, image, setting):
    if image.startswith("http"):
        r = requests.get(image)
        assert r.status_code == 200, '图片资源无法下载,link="{}"'.format(image)
        temp_ = r.content
    else:
        temp_ = b64decode(image.encode('utf-8'))
    fbid = upload_func(temp_)
    if not setting:
        return {"photo_id": fbid}
    else:
        return set_func(fbid)


class Executor():

    def __init__(self, client):
        self.client = client

    def textMsg(self, to, content, thread_type="USER"):
        _type = getattr(ThreadType, thread_type.upper())
        res = self.client.sendMessage(message=content, thread_id=to, thread_type=_type)
        return res

    def imageMsg(self, to, image, thread_type="USER", suffix='jpg'):
        return _send_msg(self.client.sendLocalImage,
                         self.client.sendRemoteImage,
                         to,
                         image,
                         thread_type,
                         suffix)

    def voiceMsg(self, to, voice, thread_type='USER', suffix='mp3'):
        return _send_msg(self.client.sendLocalVoiceClips,
                         self.client.sendRemoteVoiceClips,
                         to,
                         voice,
                         thread_type,
                         suffix)

    def fileMsg(self, to, link, thread_type="USER"):
        _type = getattr(ThreadType, thread_type.upper())
        return self.client.sendRemoteFiles(link, thread_id=to, thread_type=_type)

    def stickerMsg(self, to, sticker_id, thread_type="USER"):
        _type = getattr(ThreadType, thread_type.upper())
        return self.client.sendSticker(sticker_id, thread_id=to, thread_type=_type)

    def emojiMsg(self, to, emoji, size='small', thread_type="USER"):
        _type = getattr(ThreadType, thread_type.upper())
        _size = getattr(EmojiSize, size.upper())
        return self.client.sendEmoji(emoji=emoji, size=_size, thread_id=to, thread_type=_type)

    def linkMsg(self, to, link, thread_type='USER'):
        _type = getattr(ThreadType, thread_type.upper())
        return self.client.sendPictureLink(link, thread_id=to, thread_type=_type)

    def waveMsg(self, to, first=True, thread_type='USER'):
        _type = getattr(ThreadType, thread_type.upper())
        return self.client.wave(first, thread_id=to, thread_type=_type)

    def searchForUsers(self, name, limit=5):
        users = self.client.searchForUsers(name, limit)
        keys = ['type', 'gender', 'is_friend', 'name', 'photo', 'uid', 'url']
        result = []
        for u in users:
            info = common.todict(u, keys)
            info['type'] = info.get('type').name
            info['gender'] = 'boy' if info['gender'] == 'male_singular' else 'girl'

            result.append(info)
        return result

    def uploadAvatar(self, image, setting=False):
        return _upload_binary(
            self.client.uploudAvatar,
            self.client.setAvatar,
            image,
            setting
        )

    def uploadCover(self, image, setting=False):
        return _upload_binary(
            self.client.uploadCover,
            self.client.setCover,
            image,
            setting
        )

    def pymkFriends(self, filter_ids: list = []):
        result = self.client._pymk_request(filter_ids)
        data = {
            'size': len(result),
            'detail': result,
        }
        return data

    def friendRequests(self, next_url=None, require_gender=True):
        result, next_url = self.client._friendRequest(next_url, require_gender=require_gender)
        data = {
            'size': len(result),
            'detail': result,
            'next_url': 'https://www.facebook.com' + next_url if next_url else None
        }
        return data

    def sentRequests(self, next_url, require_gender):
        result, next_url = self.client._outgoingRequest(next_url, require_gender=require_gender)
        data = {
            'size': len(result),
            'detail': result,
            'next_url': 'https://www.facebook.com' + next_url if next_url else None
        }
        return data

    def fetchUserInfo(self, fbid_list):
        if not isinstance(fbid_list, (tuple, list)):
            raise BaseException("fbid_list 参数要求是文本型列表")
        users = self.client.fetchUserInfo(*fbid_list)
        keys = ['type', 'gender', 'is_friend', 'name', 'photo', 'uid', 'url']
        objects = []
        for _, u in users.items():
            info = common.todict(u, include=keys)
            info['type'] = info.get('type').name
            info['gender'] = 'boy' if info['gender'] == 'male_singular' else 'girl'
            objects.append(info)
        return objects

    def addWork(self, work_detail, privacy='EVERYONE'):
        print(work_detail)
        work = WorkPlace.from_dict(work_detail)
        print(work)
        res = self.client.addWorkPlace(work, privacy)
        return res