Ejemplo n.º 1
0
def __main__():
    args = parse_args()
    if args.phone and args.password:
        login.LoginViaCellphone(args.phone, args.password)
        logger.info(
            '使用账号:%s (VIP %s)' %
            (GetCurrentSession().login_info['content']['profile']['nickname'],
             GetCurrentSession().login_info['content']['profile']['vipType']))
    eThread = Thread(target=executor_loop)
    eThread.setDaemon(True)
    eThread.start()
    # starts execution thread
    total_queued = args.func(args)

    # now wait until all tasks are done...report some progress maybe?
    def report():
        if total_xfered > 0:
            power = math.floor(math.log(total_xfered) / math.log(1024))
            xfered = '%.2f%s' % (total_xfered / 1024**power,
                                 ['B', 'KB', 'MB', 'GB'][power])
            sys.stderr.write('[STAT] %.2f%% (%.0f/%d) - Xfer: %s\n' %
                             (total_progress * 100 / total_queued,
                              total_progress, total_queued, xfered))

    while task_queue.unfinished_tasks != 0:
        report()
        sleep(1)
    report()
    logger.info('下载完成')
    return 0
Ejemplo n.º 2
0
def download_by_url(url, dest):
    # Downloads generic content
    response = GetCurrentSession().get(url, stream=True)
    with open(dest, 'wb') as f:
        for chunk in response.iter_content(1024 * 2**10):
            f.write(chunk)  # write every 1MB read
    return dest
Ejemplo n.º 3
0
def copy_recommend_playlist(config, my_log, login_test=False):
    try:
        apis.login.LoginViaCellphone(config.phone, config.password)
    except apis.login.LoginFailedException:
        my_log("{} login failure. [apis.login.LoginFailedException]".format(
            config.phone))
    login_info = GetCurrentSession().login_info
    if login_info.get("success"):
        my_log("{} login success.".format(config.phone))
        if login_test:
            return True
    else:
        my_log("{} login failure. [{}]".format(config.phone, login_info))
        return False

    recommend_playlist = v3_discovery_recommend_songs(
        'db25c96804ce4f2ee92ce5634bac61b2', 1, 'iOS')
    if recommend_playlist.get("code") != 200:
        my_log(
            "recommend playlist get failure. [{}]".format(recommend_playlist))
        return False
    else:
        my_log("recommend playlist get success.")
    recommend_playlist_dailysongs = recommend_playlist.get("data").get(
        "dailySongs")
    recommend_playlist_dailydongids = []
    for song in recommend_playlist_dailysongs:
        recommend_playlist_dailydongids.append(str(song.get("id")))
    recommend_playlist_dailydongids.reverse()
    recommend_new_playlist_title = time.strftime("%Y-%m-%d",
                                                 time.localtime()) + " 今日推荐"

    # 新建歌单
    recommend_new_playlist = apis.playlist.SetCreatePlaylist(
        recommend_new_playlist_title)
    if recommend_new_playlist.get("code") == 200:
        recommend_new_playlist_id = recommend_new_playlist.get("id")
        my_log("new playlist create success, title: {}, id: {}".format(
            recommend_new_playlist_title, recommend_new_playlist_id))
    else:
        my_log(
            "new playlist create failure. [{}]".format(recommend_new_playlist))
        return False

    # 将今日推荐每首歌添加到新建歌单
    recommend_new_playlist_set = apis.playlist.SetManipulatePlaylistTracks(
        trackIds=recommend_playlist_dailydongids,
        playlistId=recommend_new_playlist_id)
    if recommend_new_playlist_set.get("code") == 200:
        my_log("recommend new playlist set success.")
        return True
    else:
        my_log("recommend new playlist set failure. [{}]".format(
            recommend_new_playlist_set))
        return False
Ejemplo n.º 4
0
 def _stats_server(self, request: Request, content):
     '''server hoster nickname'''
     self.setdefault('count', 0)
     if self['count'] < 2:
         self['count'] = 2
     if GetCurrentSession().login_info['success']:
         request.send_response(200)
         return GetCurrentSession().login_info['content']['profile']
     else:
         request.send_response(404)
         return {}
Ejemplo n.º 5
0
def download(url, dest, account=False):
    global total_progress, total_xfered
    # Downloads generic content
    response = GetCurrentSession().get(url, stream=True)
    length = int(response.headers.get('content-length'))
    with open(dest, 'wb') as f:
        for chunk in response.iter_content(1024 * 2**10):
            total_xfered += len(chunk)
            if account:
                total_progress += len(chunk) / length
            f.write(chunk)  # write every 1MB read
    return dest
Ejemplo n.º 6
0
 def __checkLogin(self):
     rsp = login.LoginQrcodeCheck(self.uuid)
     if rsp['code'] == 803 or rsp['code'] == 800:
         login.WriteLoginInfo(login.GetCurrentLoginStatus())
         Config.getCookie("netease", "pyncm")["session"] = DumpSessionAsString(GetCurrentSession())
         self.__setQrImg(self.empty_image)
         self.__setLoginInfo()
Ejemplo n.º 7
0
def login():
    phone = input('Phone:')
    passw = getpass.getpass('Password:')
    apis.login.LoginViaCellphone(phone, passw)
    logger.debug(' '.join(
        ('[+]',
         GetCurrentSession().login_info['content']['profile']['nickname'],
         'has logged in')))
    return True
Ejemplo n.º 8
0
def login():
    uuid = LoginQrcodeUnikey()['unikey']
    url = f'https://music.163.com/login?codekey={uuid}'
    img = qrcode.make(url)
    print('Enter 以显示二维码')
    img.show()
    logger.debug(' '.join(('[-] UUID:', uuid)))
    while True:
        rsp = LoginQrcodeCheck(uuid)
        if rsp['code'] == 803 or rsp['code'] == 800: break
        message = f"[!] {rsp['code']} -- {rsp['message']}"
        print(message, next(dot), end='\r')
        time.sleep(1)
    WriteLoginInfo(GetCurrentLoginStatus())
    logger.debug(' '.join(
        ('[+] Logged in as %s (Last known IP: %s)' %
         (GetCurrentSession().login_info['content']['profile']['nickname'],
          GetCurrentSession().login_info['content']['profile']['lastLoginIP'])
         )))
    # testing search
    print('测试搜索 : hi')
    print(pyncm.apis.cloudsearch.GetSearchResult('hi'))
    return True
Ejemplo n.º 9
0
 def __setLoginInfo(self):
     if self.__isLogin():
         self.current_status.set(_("Login As ")+GetCurrentSession().login_info['content']['profile']['nickname'])
     else:
         self.current_status.set(_("Not Login"))
Ejemplo n.º 10
0
 def save():
     with open(SESSION_DUMP_FILENAME, 'w+') as f:
         f.write(pyncm.DumpSessionAsString(GetCurrentSession()))
     return True
Ejemplo n.º 11
0
async def ned(context):
    if len(context.parameter) < 1:
        # 使用方法
        await context.edit(ned_help_msg)
        return
    # 加载登录信息
    if isfile(f"data{sep}session.ncm"):
        with open(f"data{sep}session.ncm") as f:
            SetCurrentSession(LoadSessionFromString(f.read()))
    # 海外用户
    GetCurrentSession().headers['X-Real-IP'] = '118.88.88.88'
    # 处理账号登录
    if context.parameter[0] == "login":
        # 显示登录信息
        if len(context.parameter) == 1:
            login_info = GetCurrentSession().login_info
            if login_info["success"]:
                # 获取VIP类型
                if login_info['content']['account']['vipType'] != 0:
                    vip_type = "**VIP**"
                else:
                    vip_type = "**普通**"
                # 获取账号创建时间
                time = strftime(
                    "%Y-%m-%d %H:%M:%S",
                    localtime(login_info['content']['account']['createTime'] /
                              1000))
                if context.is_group:
                    await context.edit(f"[ned] 已登录{vip_type}账号,账号创建时间:`{time}`"
                                       )
                else:
                    await context.edit(
                        f"[ned] 已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
                        f"账号创建时间:`{time}`")
            else:
                await context.edit(
                    f"[ned] **未登录/登录失败**,额外信息:`{login_info['content']}`")
            return
        # 过滤空参数
        if len(context.parameter) == 2:
            # 登录命令格式错误
            await context.edit(f"**使用方法:** `-{alias_command('ned')} <账号> <密码>`"
                               )
            return
        # 开始登录
        try:
            apis.login.LoginViaCellphone(context.parameter[1],
                                         context.parameter[2])
        except LoginFailedException:
            await context.edit("**登录失败**,请检查账号密码是否正确。")
            return
        # 获取登录信息
        login_info = GetCurrentSession().login_info
        # 获取VIP类型
        if login_info['content']['account']['vipType'] != 0:
            vip_type = "**VIP**"
        else:
            vip_type = "**普通**"
        # 获取账号创建时间
        time = strftime(
            "%Y-%m-%d %H:%M:%S",
            localtime(login_info['content']['account']['createTime'] / 1000))
        if context.is_group:
            await context.edit(
                f"[ned] **登录成功**,已登录{vip_type}账号,账号创建时间:`{time}`")
        else:
            await context.edit(
                f"[ned] **登录成功**,已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
                f"账号创建时间:`{time}`")
        # 保存登录信息
        with open(f"data{sep}session.ncm", 'w+') as f:
            f.write(DumpSessionAsString(GetCurrentSession()))
        return
    elif context.parameter[0] == "logout":
        # 登出
        LoginLogout()
        if isfile(f"data{sep}session.ncm"):
            remove(f"data{sep}session.ncm")
        return await context.edit("[ned] 账号登出成功。")
    elif context.parameter[0] == "clear":
        # 清除歌曲缓存
        for i in listdir("data"):
            if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(
                    ".flac") != -1 or i.find(".ogg") != -1:
                remove(f"data{sep}{i}")
        await context.edit("[ned] **已清除缓存**")
        return
    elif context.parameter[0] == "outgoing":
        # 开关自动识别音乐链接
        if if_outgoing():
            remove(f"data{sep}ned.out")
            return await context.edit("[ned] 已关闭自动识别音乐链接")
        else:
            with open(f"data{sep}ned.out", 'w') as f:
                f.write('1')
            return await context.edit("[ned] 已开启自动识别音乐链接")
    # 搜索歌曲
    # 判断是否使用最高比特率解析
    flac_mode = True if context.arguments.find("-f") != -1 else False
    song_id = context.arguments.replace("-f", "").replace("\u200b", "").strip()
    # id
    if song_id.isdigit():
        song_id = int(song_id)
    else:
        search_data = apis.cloudsearch.GetSearchResult(song_id, 1, 1)
        if search_data.get("result", {}).get("songCount", 0) >= 1:
            song_id = search_data["result"]["songs"][0]["id"]
        else:
            await context.edit(f"**没有找到歌曲**,请检查歌曲名称是否正确。")
            return
    await start_download(context, song_id, flac_mode)
Ejemplo n.º 12
0
async def ned(context):
    if len(context.parameter) < 1:
        # 使用方法
        await context.edit(ned_help_msg)
        return
    # 加载登录信息
    if isfile(f"data{sep}session.ncm"):
        with open(f"data{sep}session.ncm") as f:
            SetCurrentSession(LoadSessionFromString(f.read()))
    # 海外用户
    GetCurrentSession().headers['X-Real-IP'] = '118.88.88.88'
    # 处理账号登录
    if context.parameter[0] == "login":
        # 显示登录信息
        if len(context.parameter) == 1:
            login_info = GetCurrentSession().login_info
            if login_info["success"]:
                # 获取VIP类型
                if login_info['content']['account']['vipType'] != 0:
                    vip_type = "**VIP**"
                else:
                    vip_type = "**普通**"
                # 获取账号创建时间
                time = strftime("%Y-%m-%d %H:%M:%S", localtime(login_info['content']['account']['createTime'] / 1000))
                if context.is_group:
                    await context.edit(f"[ned] 已登录{vip_type}账号,账号创建时间:`{time}`")
                else:
                    await context.edit(f"[ned] 已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
                                       f"账号创建时间:`{time}`")
            else:
                await context.edit(f"[ned] **未登录/登录失败**,额外信息:`{login_info['content']}`")
            return
        # 过滤空参数
        if len(context.parameter) == 2:
            # 登录命令格式错误
            await context.edit(f"**使用方法:** `-{alias_command('ned')} <账号> <密码>`")
            return
        # 开始登录
        try:
            apis.login.LoginViaCellphone(context.parameter[1], context.parameter[2])
        except LoginFailedException:
            await context.edit("**登录失败**,请检查账号密码是否正确。")
            return
        # 获取登录信息
        login_info = GetCurrentSession().login_info
        # 获取VIP类型
        if login_info['content']['account']['vipType'] != 0:
            vip_type = "**VIP**"
        else:
            vip_type = "**普通**"
        # 获取账号创建时间
        time = strftime("%Y-%m-%d %H:%M:%S", localtime(login_info['content']['account']['createTime'] / 1000))
        if context.is_group:
            await context.edit(f"[ned] **登录成功**,已登录{vip_type}账号,账号创建时间:`{time}`")
        else:
            await context.edit(f"[ned] **登录成功**,已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
                               f"账号创建时间:`{time}`")
        # 保存登录信息
        with open(f"data{sep}session.ncm", 'w+') as f:
            f.write(DumpSessionAsString(GetCurrentSession()))
        return
    elif context.parameter[0] == "logout":
        # 登出
        LoginLogout()
        if isfile(f"data{sep}session.ncm"):
            remove(f"data{sep}session.ncm")
        return await context.edit("[ned] 账号登出成功。")
    elif context.parameter[0] == "clear":
        # 清除歌曲缓存
        for i in listdir("data"):
            if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
                remove(f"data{sep}{i}")
        await context.edit("[ned] **已清除缓存**")
        return
    # 搜索歌曲
    # 判断是否使用最高比特率解析
    flac_mode = True if context.arguments.find("-f") != -1 else False
    song_id = context.arguments.replace("-f", "").replace("\u200b", "").strip()
    # id
    if song_id.isdigit():
        song_id = int(song_id)
    else:
        search_data = apis.cloudsearch.GetSearchResult(song_id, CloudSearchType(1), 1)
        if search_data.get("result", {}).get("songCount", 0) >= 1:
            song_id = search_data["result"]["songs"][0]["id"]
        else:
            await context.edit(f"**没有找到歌曲**,请检查歌曲名称是否正确。")
            return
    # 获取歌曲质量是否大于 320k HQ
    track_info = apis.track.GetTrackAudio([song_id], bitrate=3200 * 1000 if flac_mode else 320000)
    # 获取歌曲详情
    song_info = apis.track.GetTrackDetail([song_id])
    if track_info["data"][0]["code"] == 404:
        await context.edit(f"**没有找到歌曲**,请检查歌曲id是否正确。")
        return
    await context.edit(f"正在下载歌曲:**{song_info['songs'][0]['name']} - {gen_author(song_info)}** "
                       f"{round(track_info['data'][0]['size'] / 1000 / 1000, 2)} MB")
    # 下载歌曲并且设置歌曲标签
    song = TrackHelper(song_info['songs'][0])
    # 转义
    for char in song_info["songs"][0]["name"]:
        if char in ['/', '\\', ':', '*', '?', '"', '<', '>', '|']:
            song_info["songs"][0]["name"] = song_info["songs"][0]["name"].replace(char, '')
    path = await netease_down(track_info, song_info, song)
    await context.edit("正在上传歌曲。。。")
    # 上传歌曲
    cap_ = ""
    # 提醒登录VIP账号
    if track_info["data"][0]["freeTrialInfo"]:
        cap_ = f"**非VIP,正在试听 {track_info['data'][0]['freeTrialInfo']['start']}s ~ \n" \
               f"{track_info['data'][0]['freeTrialInfo']['end']}s**\n"
    cap = f"「**{song_info['songs'][0]['name']}**」\n" \
          f"{gen_author(song_info)}\n" \
          f"文件大小:{round(track_info['data'][0]['size'] / 1000 / 1000, 2)} MB\n" \
          f"\n{cap_}" \
          f"#netease #{int(track_info['data'][0]['br'] / 1000)}kbps #{track_info['data'][0]['type']}"
    await context.client.send_file(
        context.chat_id,
        path,
        reply_to=context.message.reply_to_msg_id,
        caption=cap,
        link_preview=False,
        force_document=False,
        thumb=f'data{sep}{song_info["songs"][0]["name"]}.jpg',
        attributes=(DocumentAttributeAudio(
            get_duration(song_info, track_info), False, song_info['songs'][0]['name'], gen_author(song_info)),)
    )
    await context.delete()
    # 过多文件自动清理
    if len(listdir("data")) > 100:
        for i in listdir("data"):
            if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
                remove(f"data{sep}{i}")
        msg = await context.respond("[ned] **已自动清除缓存**")
        await sleep(3)
        await msg.delete()
Ejemplo n.º 13
0
 def save():
     with open(session_file,'w+') as f:
         f.write(pyncm.DumpSessionAsString(GetCurrentSession()))
     return True