
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: ./bilibili.ipynb

from nbexp_personal import sendEmail

def itemgetter(*args):
    g = operator.itemgetter(*args)
    def f(*args2):
        return dict(zip(args,  g(*args2)))
    return f

def write_json(filename, content):
    with open(filename, 'w', encoding='UTF-8') as f:
        json.dump( content,f, ensure_ascii=False, indent=4)
def read_json(filename):
    with open(filename, 'r', encoding='UTF-8') as f:
        return json.load( f)

# 复制为cCURL（posix）
def read_code(code_path):
    with open(code_path, 'r', encoding='UTF-8') as f:
        code = f.read().split('\n')[0]
        return code
code =read_code('../bili_curl.txt')

import nbexp_uncurl
import requests
from functools import partial
def fetch_code(code):
    """
    default timeout for five second
    """
    c =nbexp_uncurl.parse(code, timeout=5)
    r = eval(c)
    j = r.json()
    return j

import operator
import json
import datetime
def get_time(timestamp):
    d = datetime.datetime.fromtimestamp(timestamp)
    d = d.isoformat()
    return d

def cvt_cards(j):
    cards = j['data']['cards']

#     card = cards[0]
#     uname = card['desc']['user_profile']['info']['uname']
#     card = card['card']
#     print( desc)
#     return

    unames = list(map(lambda card:card['desc']['user_profile']['info']['uname'], cards))
    cards = list(map(operator.itemgetter('card'), cards))

    cards = list(map(json.loads, cards))

    kl = ('title', 'desc',  'pic', 'stat', 'ctime')
    cards = list(map(itemgetter(*kl), cards))

    def cvt(tp):
        card, uname = tp
        content_id = str(card['stat']['aid'])

        content = itemgetter(*kl[:-2])(card)
        pic = content['pic'] + '@64w_36h_1c.jpg'
        content['pic'] = pic

        d = get_time(card['ctime'])
        url = 'https://www.bilibili.com/video/av' + content_id

        return (content_id,  {'content': content , "url":url , 'time':d, 'uname':uname } )
    cards = dict((map(cvt, zip(cards, unames))))
    return cards

def get_cards():
    fetch = partial(fetch_code, code)
    cards = cvt_cards(fetch())
    return cards


def render_div(v):
    content = v['content']
    desc = content['desc']

    if len(desc) > 50:
        desc = desc[:20]+'...'

    body = f"""
        <div style="margin:10px">
            <img src='{content['pic']}'>
            <a href='{v['url']}'>{content['title']}</a>
            <span>{desc} {v['time']}</span>
        </div>
    """
    return body

def render_html(v_list):
    divs = ''.join(map(render_div, v_list))
    html = f"""\
    <html>
      <head></head>
      <body>
          {divs}
      </body>
    </html>
    """
    return html

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Create the body of the message (a plain-text and an HTML version).
def render_msg(v_list, sub_name=""):
    v_list = list(v_list)
    html = render_html(v_list)
    msg = MIMEMultipart('alternative')
    msg['Subject'] = sub_name + '订阅' + '+' + str(len(v_list))
    msg['From'] = sub_name
    msg['To'] = ''
    # Record the MIME types of both parts - text/plain and text/html.
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    return msg.as_string()



def get_main(json_path, get_cards, sub_name=""):
    """
    json_path where to read old cards and save merge content
    """

    def main():
        cards = get_cards()
        wj = partial( write_json, json_path,)
        rj = partial( read_json, json_path,)

        if not exists(json_path):
            # 发送所有
            wj({})

        old_cards = rj()

        new_cards = filter(lambda tp:tp[0] not in old_cards, cards.items())
        new_cards = map(operator.itemgetter(1), new_cards)
        new_cards = list(new_cards)
        if new_cards:
            msg = render_msg(new_cards, sub_name)
            sendEmail(msg)
            old_cards.update(cards)
            wj(old_cards)

    return main


def block_on_观视频工作室(tp):

    key, o = tp

    if o['uname'] != '观视频工作室': return True

    if '睡前消息' in o['content']['title']: return True

    return False

def filter_get_cards():
    cards = get_cards()
    cards = list(filter(block_on_观视频工作室, cards.items()))
    cards = dict(cards)

    return cards


from os.path import exists
json_path = './bili.json'
main = get_main(json_path, filter_get_cards, "bili")


if __name__ == '__main__': main()

#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: ./bilibili.ipynb

from nbexp_personal import sendEmail

def itemgetter(*args):
    g = operator.itemgetter(*args)
    def f(*args2):
        return dict(zip(args,  g(*args2)))
    return f

def write_json(filename, content):
    with open(filename, 'w', encoding='UTF-8') as f:
        json.dump( content,f, ensure_ascii=False, indent=4)
def read_json(filename):
    with open(filename, 'r', encoding='UTF-8') as f:
        return json.load( f)

# 复制为cCURL（posix）
def read_code(code_path):
    with open(code_path, 'r', encoding='UTF-8') as f:
        code = f.read().split('\n')[0]
        return code
code =read_code('../bili_curl.txt')

import nbexp_uncurl
import requests
from functools import partial
def fetch_code(code):
    """
    default timeout for five second
    """
    c =nbexp_uncurl.parse(code, timeout=5)
    r = eval(c)
    j = r.json()
    return j

import operator
import json
import datetime
def get_time(timestamp):
    d = datetime.datetime.fromtimestamp(timestamp)
    d = d.isoformat()
    return d

def cvt_cards(j):
    cards = j['data']['cards']

#     card = cards[0]
#     uname = card['desc']['user_profile']['info']['uname']
#     card = card['card']
#     print( desc)
#     return

    unames = list(map(lambda card:card['desc']['user_profile']['info']['uname'], cards))
    cards = list(map(operator.itemgetter('card'), cards))

    cards = list(map(json.loads, cards))

    kl = ('title', 'desc',  'pic', 'stat', 'ctime')
    cards = list(map(itemgetter(*kl), cards))

    def cvt(tp):
        card, uname = tp
        content_id = str(card['stat']['aid'])

        content = itemgetter(*kl[:-2])(card)
        pic = content['pic'] + '@64w_36h_1c.jpg'
        content['pic'] = pic

        d = get_time(card['ctime'])
        url = 'https://www.bilibili.com/video/av' + content_id

        return (content_id,  {'content': content , "url":url , 'time':d, 'uname':uname } )
    cards = dict((map(cvt, zip(cards, unames))))
    return cards

def get_cards():
    fetch = partial(fetch_code, code)
    cards = cvt_cards(fetch())
    return cards


def render_div(v):
    content = v['content']
    desc = content['desc']

    if len(desc) > 50:
        desc = desc[:20]+'...'

    body = f"""
        <div style="margin:10px">
            <img src='{content['pic']}'>
            <a href='{v['url']}'>{content['title']}</a>
            <span>{desc} {v['time']}</span>
        </div>
    """
    return body

def render_html(v_list):
    divs = ''.join(map(render_div, v_list))
    html = f"""\
    <html>
      <head></head>
      <body>
          {divs}
      </body>
    </html>
    """
    return html

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Create the body of the message (a plain-text and an HTML version).
def render_msg(v_list, sub_name=""):
    v_list = list(v_list)
    html = render_html(v_list)
    msg = MIMEMultipart('alternative')
    msg['Subject'] = sub_name + '订阅' + '+' + str(len(v_list))
    msg['From'] = sub_name
    msg['To'] = ''
    # Record the MIME types of both parts - text/plain and text/html.
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    return msg.as_string()



def get_main(json_path, get_cards, sub_name=""):
    """
    json_path where to read old cards and save merge content
    """

    def main():
        cards = get_cards()
        wj = partial( write_json, json_path,)
        rj = partial( read_json, json_path,)

        if not exists(json_path):
            # 发送所有
            wj({})

        old_cards = rj()

        new_cards = filter(lambda tp:tp[0] not in old_cards, cards.items())
        new_cards = map(operator.itemgetter(1), new_cards)
        new_cards = list(new_cards)
        if new_cards:
            msg = render_msg(new_cards, sub_name)
            sendEmail(msg)
            old_cards.update(cards)
            wj(old_cards)

    return main


def block_on_观视频工作室(tp):

    key, o = tp

    if o['uname'] != '观视频工作室': return True

    if '睡前消息' in o['content']['title']: return True

    return False

def filter_get_cards():
    cards = get_cards()
    cards = list(filter(block_on_观视频工作室, cards.items()))
    cards = dict(cards)

    return cards


from os.path import exists
json_path = './bili.json'
main = get_main(json_path, filter_get_cards, "bili")


if __name__ == '__main__': main()
################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# # file to edit: ./bilibili.ipynb # 复制为cCURL（posix） default timeout for five second #     card = cards[0] #     uname = card['desc']['user_profile']['info']['uname'] #     card = card['card'] #     print( desc) #     return <div style="margin:10px">             <img src='{content['pic']}'>             <a href='{v['url']}'>{content['title']}</a>             <span>{desc} {v['time']}</span>         </div> \     <html>       <head></head>       <body>           {divs}       </body>     </html> # Create the body of the message (a plain-text and an HTML version). # Record the MIME types of both parts - text/plain and text/html. json_path where to read old cards and save merge content # 发送所有