def populate(self, form): self.info = form.info.data tc = form.twitch_channel_extract() # delete inapropriate tstream if tc != self.twitch_channel: ts = self.streams.filter_by(type='twitch_stream').first() if ts: ts.streamer = None # rebind tstream streamer = Streamer.query.filter_by(twitch_channel=tc).first() if streamer and streamer != current_user: streamer.twitch_channel = None for ts in streamer.streams.filter_by(type='twitch_stream'): ts.streamer = self self.twitch_channel = tc if tc else None yc = get_or_create(YoutubeChannel, channel_id=form.youtube_channel_extract()) # delete inapropriate ystreams if yc != self.youtube_channel_class: for ys in self.streams.filter_by(type='youtube_stream'): ys.streamer = None # rebind ystreams streamer = yc.streamer if streamer and streamer != current_user: del streamer.youtube_channel for ys in yc.streams: ys.streamer = self self.youtube_channel_class = yc if yc else None
def _subscribe_to_streamer(): if ('email' not in request.form and not current_user.is_authenticated()) or\ 'streamer_id' not in request.form: abort(400) streamer_id = request.form['streamer_id'] if current_user.is_anonymous() or not current_user.as_subscriber: email = request.form['email'] else: email = current_user.as_subscriber.email streamer = Streamer.query.get_or_404(streamer_id) subscriber = get_or_create(Subscriber, email=email) if current_user.is_authenticated(): current_user.as_subscriber = subscriber if request.method == "PUT": if subscriber not in streamer.subscribers: streamer.subscribers.append(subscriber) else: if subscriber in streamer.subscribers: streamer.subscribers.remove(subscriber) db.session.commit() response = app.make_response(jsonify(result="OK")) response.set_cookie("email", value=email) return response
def generate_rtmp_stuff(self): self.rtmp_secret = str(uuid.uuid4()) wpcs = get_or_create(WPCStream, channel_name=current_user.reddit_username) current_user.streams.append(wpcs) db.session.add(wpcs) wpcs.status = 'completed' if not wpcs.status else wpcs.status db.session.commit()
def authenticate_streamer(): streamer_username = request.values.get('name', '') rtmp_secret = request.values.get('pass', '') streamer = Streamer.query.filter_by( reddit_username=streamer_username).first() if not streamer or not streamer.rtmp_secret or streamer.rtmp_secret != rtmp_secret: app.logger.info(u"Fail to check credentials for streamer {}".format( streamer_username)) return None, None return get_or_create(WPCStream, channel_name=streamer_username), streamer
def populate_email(self, email): if not self.as_subscriber or len(self.as_subscriber.as_streamer) > 1: self.as_subscriber = get_or_create(Subscriber, email=email) else: alredy_existing_subscriber = Subscriber.query.filter_by(email=email).first() if alredy_existing_subscriber: db.session.delete(self.as_subscriber) self.as_subscriber = alredy_existing_subscriber else: self.as_subscriber.email = email
def validate_youtube_channel(form, field): yc = form.youtube_channel_extract() if yc is None: # FIXME: add explanation here or hint to page raise ValidationError("This field should contain a valid YouTube channel.") streamer = get_or_create(YoutubeChannel, channel_id=yc).streamer if streamer and streamer.checked and streamer != current_user: raise ValidationError( "There is another user with this channel. If it is your channel, please message about that to /r/WatchPeoplecode moderators." )
def validate_youtube_channel(form, field): yc = form.youtube_channel_extract() if yc is None: # FIXME: add explanation here or hint to page raise ValidationError( "This field should contain a valid YouTube channel.") streamer = get_or_create(YoutubeChannel, channel_id=yc).streamer if streamer and streamer.checked and streamer != current_user: raise ValidationError( "There is another user with this channel. If it is your channel, please message about that to /r/WatchPeoplecode moderators." )
def _update_status(self): app.logger.info("Updating status for {}".format(self)) print "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet,liveStreamingDetails&key={}".format(self.ytid, app.config['YOUTUBE_KEY']) r = requests_get_with_retries( "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet,liveStreamingDetails&key={}".format( self.ytid, app.config['YOUTUBE_KEY']), retries_num=15) r.raise_for_status() if not r.json()['items']: self.status = 'completed' self.current_viewers = None return for item in r.json()['items']: self.youtube_channel = get_or_create(YoutubeChannel, channel_id=item['snippet']['channelId']) self.youtube_channel.title = item['snippet']['channelTitle'] # if there is streamer with this channel if self.youtube_channel.streamer is not None: self.streamer = self.youtube_channel.streamer elif self.streamer is not None: # if streamer has no yc and didn't ever checked profile if not self.streamer.checked: self.streamer.youtube_channel_class = self.youtube_channel # otherwise else: self.streamer = None self.title = item['snippet']['title'] if 'liveStreamingDetails' in item: self.scheduled_start_time = item['liveStreamingDetails'].get('scheduledStartTime', None) if 'concurrentViewers' in item['liveStreamingDetails']: self.current_viewers = item['liveStreamingDetails']['concurrentViewers'] if item['snippet']['liveBroadcastContent'] == "none" and not self.actual_start_time: # TODO: it is probably better to have a separate column for vids self.actual_start_time = item['snippet'].get('publishedAt') if item['snippet']['liveBroadcastContent'] == 'live': self._go_live() if 'actualStartTime' in item['liveStreamingDetails']: self.actual_start_time = item['liveStreamingDetails'].get('actualStartTime', None) else: # Youtube is weird, and sometimes this happens. If there is no actual start time, then we fall back to scheduledStartTime self.actual_start_time = item['liveStreamingDetails'].get('scheduledStartTime', None) elif item['snippet']['liveBroadcastContent'] == 'upcoming': self.status = 'upcoming' else: self.status = 'completed' self.current_viewers = None
def _update_status(self): app.logger.info("Updating status for {}".format(self)) r = requests_get_with_retries( "https://www.googleapis.com/youtube/v3/videos?id={}&part=snippet,liveStreamingDetails&key={}".format( self.ytid, app.config['YOUTUBE_KEY']), retries_num=15) r.raise_for_status() if not r.json()['items']: self.status = 'completed' self.current_viewers = None return for item in r.json()['items']: self.youtube_channel = get_or_create(YoutubeChannel, channel_id=item['snippet']['channelId']) self.youtube_channel.title = item['snippet']['channelTitle'] # if there is streamer with this channel if self.youtube_channel.streamer is not None: self.streamer = self.youtube_channel.streamer elif self.streamer is not None: # if streamer has no yc and didn't ever checked profile if not self.streamer.checked: self.streamer.youtube_channel_class = self.youtube_channel # otherwise else: self.streamer = None self.title = item['snippet']['title'] if 'liveStreamingDetails' in item: self.scheduled_start_time = item['liveStreamingDetails'].get('scheduledStartTime', None) if 'concurrentViewers' in item['liveStreamingDetails']: self.current_viewers = item['liveStreamingDetails']['concurrentViewers'] if item['snippet']['liveBroadcastContent'] == "none" and not self.actual_start_time: # TODO: it is probably better to have a separate column for vids self.actual_start_time = item['snippet'].get('publishedAt') if item['snippet']['liveBroadcastContent'] == 'live': self._go_live() if 'actualStartTime' in item['liveStreamingDetails']: self.actual_start_time = item['liveStreamingDetails'].get('actualStartTime', None) else: # Youtube is weird, and sometimes this happens. If there is no actual start time, then we fall back to scheduledStartTime self.actual_start_time = item['liveStreamingDetails'].get('scheduledStartTime', None) elif item['snippet']['liveBroadcastContent'] == 'upcoming': self.status = 'upcoming' else: self.status = 'completed' self.current_viewers = None
def dashboard(tab): rtmp_redirect_form = RtmpRedirectForm(prefix='rtmpform') email_form = DashboardEmailForm(prefix='emailform') add_video_form = DashboardAddVideoForm(prefix='addvideoform') if request.method == "GET": rtmp_redirect_form.prepopulate(current_user) email_form.prepopulate(current_user) if rtmp_redirect_form.validate_on_submit(): rtmp_redirect_form.populate_obj(current_user) db.session.commit() flash('Successfully updated your RTMP redirects!', 'success') return redirect(url_for("dashboard", tab="streaming")) if email_form.validate_on_submit(): current_user.populate_email(email_form.email.data) db.session.commit() flash('Successfully updated your email address!', 'success') return redirect(url_for("dashboard", tab="email")) if add_video_form.validate_on_submit(): ytid = youtube_video_id(add_video_form.link.data) ys = get_or_create(YoutubeStream, ytid=ytid) ys.streamer = current_user for i in xrange(10): try: ys._update_status() db.session.commit() flash( u'Successfully added YouTube video "{}"'.format( Markup.escape(ys.title)), 'success') break except Exception as e: app.logger.error("Failed to add YouTube video {}".format(ys)) app.logger.exception(e) else: flash("Failed to add YouTube video! Try again?", 'error') app.logger.error( "Failed to add YouTube video multiple times {}".format(ys)) return redirect(url_for("dashboard", tab="video-archive")) return render_template("dashboard.html", rtmp_redirect_form=rtmp_redirect_form, email_form=email_form, add_video_form=add_video_form, tab=tab)
def reddit_authorize_callback(): r = praw.Reddit(user_agent=app.config["REDDIT_WEB_APP_USER_AGENT"]) r.set_oauth_app_info(app.config['REDDIT_API_ID'], app.config['REDDIT_API_SECRET'], url_for('.reddit_authorize_callback', _external=True)) name = None code = request.args.get('code', '') if code: r.get_access_information(code) name = r.get_me().name if name: user = get_or_create(Streamer, reddit_username=name) db.session.commit() login_user(user, remember=True) flash("Logged in successfully!", 'success') if not name: flash("An error occurred while trying to log in.", 'error') next_url = session.pop('next_url_after_login', url_for("streamer_page", streamer_name=name)) return redirect(next_url)
def already_subscribed(self, streamer): email = request.cookies.get("email") return email and streamer and get_or_create(Subscriber, email=email) in streamer.subscribers
def youtube_channel(self, channel_id): self.youtube_channel_class = get_or_create(YoutubeChannel, channel_id=channel_id)
def dispatch_request(self, streamer_name, page): streamer = Streamer.query.filter_by( reddit_username=streamer_name).first_or_404() wpc_stream = streamer.streams.filter_by(type='wpc_stream').first() # glm_talkshow stuff if streamer_name == 'glm_talkshow': subscribe_form = GLMSubscribeForm(prefix='streamer_subscribe') if subscribe_form.validate_on_submit(): subscriber = get_or_create(Subscriber, email=subscribe_form.email.data) if subscriber not in streamer.subscribers: streamer.subscribers.append(subscriber) flash("Subscribed successfully!", category='success') else: flash("You're already subscribed!") db.session.commit() yt_recording_ep1 = YoutubeStream.query.filter_by( ytid='f968E8eZmvM').one() yt_recording_ep2 = YoutubeStream.query.filter_by( ytid='87SfA1sw7vY').one() yt_recording_ep3 = YoutubeStream.query.filter_by( ytid='R7z2GQr9-tg').one() yt_recording_ep4 = YoutubeStream.query.filter_by( ytid='zU7ltY9Dmnk').one() yt_recording_ep5 = YoutubeStream.query.filter_by( ytid='3A_oTuzGoeE').one() how_to_learn_programming = YoutubeStream.query.filter_by( ytid='6XtSPvjt87w').one() return render_template( 'streamers/glm_talkshow.html', streamer=streamer, wpc_stream=wpc_stream, yt_stream_ep1=yt_recording_ep1, yt_stream_ep2=yt_recording_ep2, yt_stream_ep3=yt_recording_ep3, yt_stream_ep4=yt_recording_ep4, yt_stream_ep5=yt_recording_ep5, how_to_learn_programming=how_to_learn_programming, subscribe_form=subscribe_form) # all stuff streams = streamer.streams if wpc_stream: streams = streams.filter(Stream.id != wpc_stream.id) streams = streams.order_by( Stream.actual_start_time.desc().nullslast()).paginate(page, per_page=5) check_profile_alert = False info_form = EditStreamerInfoForm(prefix='info') title_form = EditStreamTitleForm(prefix='title') if current_user.is_authenticated() and current_user == streamer: if request.method == 'POST': if info_form.submit_button.data: if info_form.validate_on_submit(): current_user.populate(info_form) db.session.commit() flash("Updated successfully", category='success') return redirect( url_for('.streamer_page', streamer_name=streamer_name, page=page)) elif title_form.submit_button.data: if title_form.validate_on_submit(): wpc_stream.title = title_form.title.data db.session.commit() return jsonify( newTitle=Markup.escape(title_form.title.data)) else: if not streamer.checked: streamer.checked = True db.session.commit() if (streamer.youtube_channel or streamer.twitch_channel): check_profile_alert = True info_form.youtube_channel.data = current_user.youtube_channel info_form.twitch_channel.data = current_user.twitch_channel info_form.info.data = current_user.info if wpc_stream: title_form.title.data = wpc_stream.title return render_template('streamer.html', streamer=streamer, streams=streams, info_form=info_form, title_form=title_form, wpc_stream=wpc_stream, check_profile_alert=check_profile_alert)