def reprint_force(self, vid, skip_download=False):
     video = self._get_video(vid)
     if not skip_download:
         log.logger.info("开始下载视频,地址:{}".format(video.url))
         bot.send_group_msg(group_id=TWITCH_GROUP,
                            message="开始下载视频,地址:{}".format(video.url))
         self._download_video(video)
     log.logger.info("开始上传视频")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="开始上传视频")
     self._upload_video(video)
 def _reprint(self, user):
     vid = self._get_last_video(user.get_id())
     video = self._get_video(vid)
     log.logger.info("开始下载视频,地址:{}".format(video.url))
     bot.send_group_msg(group_id=TWITCH_GROUP,
                        message="开始下载视频,地址:{}".format(video.url))
     self._download_video(video)
     log.logger.info("开始上传视频")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="开始上传视频")
     self._upload_video(video)
 def _get_video(self, vid):
     response = requests.get(
         url="https://api.twitch.tv/helix/videos?id={}".format(vid),
         headers={"Client-ID": self.__client_id},
         proxies=self.__proxies,
         timeout=10)
     data = json.loads(response.text)["data"][0]
     video = TwitchVideo(data["id"], data["user_name"], data["url"],
                         self.__utc2local(data["created_at"]),
                         self.__utc2local_sec(data["published_at"]),
                         data["duration"], data["title"])
     log.logger.info("已获取视频信息:\n{}".format(str(video)))
     bot.send_group_msg(group_id=TWITCH_GROUP,
                        message="已获取视频信息:\n{}".format(str(video)))
     return video
 def _upload_video(self, video):
     snapshot(video.get_id(), "00:00:15")
     log.logger.info("生成缩略图完成")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="生成缩略图完成")
     uper = Uploader()
     uper.upload(
         '{}.flv'.format(video.get_id()),
         '{} {} 直播录像'.format(video.name, video.create_time), 136,
         "idke,OSU,直播,录像", "{}直播间:https://www.twitch.tv/{}\n{}".format(
             video.name, video.name,
             str(video)), "", '{}.jpg'.format(video.get_id()))
     log.logger.info("上传完成")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="上传完成")
     os.remove('{}.flv'.format(video.get_id()))
     log.logger.info("删除文件完成")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="删除文件完成")
 def check_streams(self):
     log.logger.info("开始检查直播情况")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="开始检查直播情况")
     for name in self.__live_status:
         user = self.__live_status[name]
         is_live = self._check_stream(user.get_id())
         was_live = user.is_live
         user.is_live = is_live
         if bool(was_live) != bool(is_live):
             log.logger.info("{} 直播{}".format(name,
                                              "开始" if is_live else "结束"))
             bot.send_group_msg(group_id=TWITCH_GROUP,
                                message="{} 直播{}".format(
                                    name, "开始" if is_live else "结束"))
             if not is_live:
                 p = Process(target=self._reprint, args=(user, ))
                 p.start()
         log.logger.info("{} 直播状态:{}".format(name,
                                             "直播中" if is_live else "未直播"))
         bot.send_group_msg(group_id=TWITCH_GROUP,
                            message="{} 直播状态:{}".format(
                                name, "直播中" if is_live else "未直播"))
    def _upload(self, filepath):
        """执行上传文件操作"""
        if not os.path.isfile(filepath):
            print('FILE NOT EXISTS: {}'.format(filepath))
            return

        filename = os.path.basename(filepath)
        filesize = os.path.getsize(filepath)

        # 1.获取本次上传所需信息
        preupload_url = 'https://member.bilibili.com/preupload'
        params = {
            'os': 'upos',
            'r': 'upos',
            'ssl': '0',
            'name': filename,
            'size': filesize,
            'upcdn': self.cdn,
            'profile': self.profile,
        }
        response = self.session.get(preupload_url, params=params)
        upload_info = response.json()

        # 本次上传bilibili端文件名
        upload_info['bili_filename'] = upload_info['upos_uri'].split(
            '/')[-1].split('.')[0]
        # 本次上传url
        endpoint = 'http:%s/' % upload_info['endpoint']
        upload_url = re.sub(r'^upos://', endpoint, upload_info['upos_uri'])
        print('UPLOAD URL: {}'.format(upload_url))
        # 本次上传session
        upload_session = requests.session()
        upload_session.mount('http://',
                             HTTPAdapter(max_retries=self.MAX_RETRYS))
        upload_session.headers['X-Upos-Auth'] = upload_info['auth']

        # 2.获取本次上传的upload_id
        response = upload_session.post(upload_url + '?uploads&output=json')
        upload_info['upload_id'] = response.json()['upload_id']

        print('UPLOAD INFO: {}'.format(upload_info))

        # 3.分块上传文件
        CHUNK_SIZE = 4 * 1024 * 1024
        total_chunks = math.ceil(filesize * 1.0 / CHUNK_SIZE)
        offset = 0
        chunk = 0
        parts_info = {'parts': []}
        fp = open(filepath, 'rb')
        progress = 0.05
        while True:
            blob = fp.read(CHUNK_SIZE)
            if not blob:
                break
            params = {
                'partNumber': chunk + 1,
                'uploadId': upload_info['upload_id'],
                'chunk': chunk,
                'chunks': total_chunks,
                'size': len(blob),
                'start': offset,
                'end': offset + len(blob),
                'total': filesize,
            }
            response = upload_session.put(upload_url,
                                          params=params,
                                          data=blob,
                                          timeout=1200)
            print('UPLOAD CHUNK {}/{}'.format(chunk + 1, total_chunks))
            if chunk / total_chunks >= progress:
                bot.send_group_msg(group_id=TWITCH_GROUP,
                                   message="上传进度超过:{}|{}/{}".format(
                                       progress, chunk + 1, total_chunks))
                progress += 0.05

            parts_info['parts'].append({
                'partNumber': chunk + 1,
                'eTag': 'etag'
            })
            chunk += 1
            offset += len(blob)

        # 4.标记本次上传完成
        params = {
            'output': 'json',
            'name': filename,
            'profile': self.profile,
            'uploadId': upload_info['upload_id'],
            'biz_id': upload_info['biz_id']
        }
        response = upload_session.post(upload_url,
                                       params=params,
                                       data=parts_info)
        print('UPLOAD RESULT')
        print('UPLOAD INFO: {}'.format(upload_info))
        bot.send_group_msg(group_id=TWITCH_GROUP, message="上传视频完成")
        return upload_info
    def upload(self,
               filepath,
               title,
               tid,
               tag='',
               desc='',
               source='',
               cover_path='',
               dynamic='',
               no_reprint=1):
        """视频投稿
        Args:
            filepath   : 视频文件路径
            title      : 投稿标题
            tid        : 投稿频道id,详见https://member.bilibili.com/x/web/archive/pre
            tag        : 视频标签,多标签使用','号分隔
            desc       : 视频描述信息
            source     : 转载视频出处url
            cover_path : 封面图片路径
            dynamic    : 分享动态, 比如:"#周五##放假# 劳资明天不上班"
            no_reprint : 1表示不允许转载,0表示允许
        """
        # TODO:
        # 1.增加多P上传
        # 2.对已投稿视频进行删改, 包括删除投稿,修改信息,加P删P等

        # 上传文件, 获取上传信息
        upload_info = self._upload(filepath)
        if not upload_info:
            return
        # 获取图片链接
        cover_url = self._cover_up(
            cover_path) if cover_path else self._cover_default(
                upload_info["bili_filename"], 20)
        bot.send_group_msg(group_id=TWITCH_GROUP, message="获取封面完成")
        # 版权判断, 转载无版权
        copyright = 2 if source else 1
        # tag设置
        if isinstance(tag, list):
            tag = ','.join(tag)
        # 设置视频基本信息
        params = {
            'copyright':
            copyright,
            'source':
            source,
            'title':
            title,
            'tid':
            tid,
            'tag':
            tag,
            'no_reprint':
            no_reprint,
            'desc':
            desc,
            'desc_format_id':
            0,
            'dynamic':
            dynamic,
            'cover':
            cover_url,
            'videos': [{
                'filename': upload_info['bili_filename'],
                'title': title,
                'desc': '',
            }]
        }
        if source:
            del params['no_reprint']
        url = 'https://member.bilibili.com/x/vu/web/add?csrf=' + self.csrf
        response = self.session.post(url, json=params)
        print('SET VIDEO INFO')
        bot.send_group_msg(group_id=TWITCH_GROUP, message="上传工作全部完成")
        return response.json()
 def _download_video(self, video):
     os.system(
         'streamlink -o {}.flv --http-proxy 127.0.0.1:1080 --https-proxy 127.0.0.1:1080 --force {} best'
         .format(video.get_id(), video.url))
     log.logger.info("下载完成")
     bot.send_group_msg(group_id=TWITCH_GROUP, message="下载完成")