def post(self): req = self.request data = populate_user() if not data['logged_in']: return self.redirect('/') user_id = data['nickname'] stream_name = req.get('name') stream_tags = req.get('tags').split(',') stream_cover = req.get('cover') or DEFAULT_COVER stream_add_subscribers_email_list = req.get('email_list').split(',') stream_email_body = req.get('email_body') if not stream_name or Stream.get_by_id(stream_name): data['msg'] = 'Sorry! Stream already exists/Name empty.' template = JINJA_ENVIRONMENT.get_template('error.html') return self.response.write(template.render(data)) stream = Stream(id=stream_name, tags=stream_tags, cover_url=stream_cover).put() user = User.get_by_id(user_id) user.owned_ids.append(stream) user.put() # on successful insert, send email if (Stream.get_by_id(stream_name)): send_subscribtion_invite_email(stream_add_subscribers_email_list, stream_email_body, stream_name, self.request.url) return self.redirect('/manage')
def post(self): stream_id = self.request.get('stream_id') template = JINJA_ENVIRONMENT.get_template('error.html') data = {} if not Stream.get_by_id(stream_id): data['msg'] = 'Stream id %s not found!' % stream_id return self.response.write(template.render(data)) if not self.request.get('files[]'): data['msg'] = 'Hey, Upload an image first!' return self.response.write(template.render(data)) results = [] for img in self.request.get_all('files[]'): results.append({'name': '', 'url': '', 'type': '', 'size': 64}) avatar = images.resize(img, 320, 320) lat = self.request.get('lat') lat = float(lat) if lat else None lng = self.request.get('lng') lng = float(lng) if lng else None image = Image(data=db.Blob(avatar), comment=self.request.get('comment'), lat=lat, lng=lng).put() Stream.append_image(stream_id, image) s = json.dumps({'files': results}, separators=(',', ':')) self.response.headers['Content-Type'] = 'application/json' return self.response.write(s)
def post(self): req = self.request data = populate_user() if not data['logged_in']: return self.redirect('/') user_id = data['nickname'] stream_name = req.get('name') stream_tags = req.get('tags').split(',') stream_cover = req.get('cover') or DEFAULT_COVER stream_add_subscribers_email_list = req.get( 'email_list').split(',') stream_email_body = req.get('email_body') if not stream_name or Stream.get_by_id(stream_name): data['msg'] = 'Sorry! Stream already exists/Name empty.' template = JINJA_ENVIRONMENT.get_template('error.html') return self.response.write(template.render(data)) stream = Stream(id=stream_name, tags=stream_tags, cover_url=stream_cover).put() user = User.get_by_id(user_id) user.owned_ids.append(stream) user.put() # on successful insert, send email if(Stream.get_by_id(stream_name)): send_subscribtion_invite_email(stream_add_subscribers_email_list, stream_email_body, stream_name, self.request.url) return self.redirect('/manage')
def main() : POST_LIMIT = 10 STREAMING_SUBS = ['mlbstreams', 'nbastreams', 'soccerstreams'] #, 'nflstreams', 'nhlstreams', 'cfbstreams', 'ncaabballstreams', 'boxingstreams', 'mmastreams'] db = DB.initialize(rebuild = False); # Connect to Reddit reddit_obj = Reddit.connect() # Create submissions and comments for sub in STREAMING_SUBS: submissions_with_comments = Reddit.scrape_posts(reddit_obj, sub, POST_LIMIT) Submission.create_with_comments(submissions_with_comments, db) # Parse comments for streams comment_data = Comment.get_all(db) stream_list = Reddit.parse_comments_for_streams(comment_data, db) # Create streams for stream in stream_list: Stream.create(stream, db) # Print the matches table from SQLite Submission.print_all(db) # Close the DB connection DB.close(db)
def get(self): user = users.get_current_user() if not user: template_values = { 'login_url': users.create_login_url(self.request.uri) } template = JINJA_ENVIRONMENT.get_template('views/login.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values)) else: owned_streams = ( Stream.query(Stream.owner == user.email().lower()) .order(-Stream.name).fetch() ) subscribed_streams = ( Stream.query(Stream.subscribers == user.email().lower()) .order(-Stream.name).fetch() ) template_values = { 'owned_streams': owned_streams, 'subscribed_streams': subscribed_streams } template = JINJA_ENVIRONMENT.get_template('views/manage.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def main(): POST_LIMIT = 10 STREAMING_SUBS = [ 'mlbstreams', 'nbastreams', 'soccerstreams' ] #, 'nflstreams', 'nhlstreams', 'cfbstreams', 'ncaabballstreams', 'boxingstreams', 'mmastreams'] db = DB.initialize(rebuild=False) # Connect to Reddit reddit_obj = Reddit.connect() # Create submissions and comments for sub in STREAMING_SUBS: submissions_with_comments = Reddit.scrape_posts( reddit_obj, sub, POST_LIMIT) Submission.create_with_comments(submissions_with_comments, db) # Parse comments for streams comment_data = Comment.get_all(db) stream_list = Reddit.parse_comments_for_streams(comment_data, db) # Create streams for stream in stream_list: Stream.create(stream, db) # Print the matches table from SQLite Submission.print_all(db) # Close the DB connection DB.close(db)
def post(self): stream_id = self.request.get('stream_id') img_blob = self.request.get('img_blob') template = JINJA_ENVIRONMENT.get_template('error.html') lat = self.request.get('lat') lat = float(lat) if lat else None lng = self.request.get('lng') lng = float(lng) if lng else None image = Image(data=img_blob,comment=' ',lat=lat, lng=lng).put() #logging.error('Stream ID:%s',str(stream_id)) Stream.append_image(stream_id, image)
def post(self): stream_id = self.request.get('stream_id') img_blob = self.request.get('img_blob') template = JINJA_ENVIRONMENT.get_template('error.html') lat = self.request.get('lat') lat = float(lat) if lat else None lng = self.request.get('lng') lng = float(lng) if lng else None image = Image(data=img_blob, comment=' ', lat=lat, lng=lng).put() #logging.error('Stream ID:%s',str(stream_id)) Stream.append_image(stream_id, image)
def post(self): # We set the same parent key on the 'Greeting' to ensure each # Greeting is in the same entity group. Queries across the # single entity group will be consistent. However, the write # rate to a single entity group should be limited to # ~1/second. name = self.request.get('name') stream = Stream(name=name, created_by_user_id=users.get_current_user().user_id()) stream.put() self.response.out.write("ok")
def delete(self): key = self.request.get('key') or '' if key: img = Image.getImage(key) Stream.getStream(img.stream_id).removeImage(img.image_id) blobstore.delete(key) s = json.dumps({key: True}, separators=(',', ':')) if 'application/json' in self.request.headers.get('Accept'): self.response.headers['Content-Type'] = 'application/json' self.response.write(s)
def get(self): stream_name = self.request.get('stream_name') if stream_name: key = ndb.Key('Stream', stream_name) stream = key.get() else: stream = None if stream: increment = self.request.get('increment') if increment: stream.views += int(increment) stream.recent_views.append(datetime.datetime.now()) stream.put() cursor = self.request.get('cursor') cursor = int(cursor) if cursor else 0 upload_url = blobstore.create_upload_url('/upload_photo') template_values = { 'stream': stream, 'cursor': cursor, 'upload_url': upload_url } template = JINJA_ENVIRONMENT.get_template('views/view-stream.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values)) else: streams = Stream.query().order(Stream.date).fetch() template_values = { 'streams': streams, } template = JINJA_ENVIRONMENT.get_template( 'views/view-streams.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def get_stream_owner(stream_name): stream_list = Stream.query(Stream.name == stream_name).fetch() d = {} if stream_list: stream = stream_list[0] d = {"Id": stream.key.parent().get().pigeon_id} return d
def get(self): MINUTES_PER_TICK = 5 TICKS_PER_HOUR = 60 / MINUTES_PER_TICK TICKS_PER_DAY = 24 * TICKS_PER_HOUR config = TrendingEmailConfig.query().fetch(1)[0] if config: if config.mode == "none": config.ticks = 0 elif config.mode == "minutes": config.ticks = 0 elif config.mode == "hourly": config.ticks += 1 config.ticks = config.ticks % TICKS_PER_HOUR elif config.mode == "daily": config.ticks += 1 config.ticks = config.ticks % TICKS_PER_DAY if config.mode != "none" and config.ticks == 0: sender_address = 'Matthew Halpern <*****@*****.**>' subject = '[mh33338-conexus] Trending' streams = Stream.query().fetch() sorted_streams = sorted(streams, key=lambda s: len(s.recent_views), reverse=True) body = "Trending Streams:\n\n" for idx, stream in enumerate(sorted_streams[:3]): body += "%d. %s %s" % (idx + 1, stream.name, "http://mh33338-connexus.appspot" + ".com/view?stream_name=%s" % stream.name + "&increment=1\n") mail.send_mail(sender_address, "*****@*****.**", subject, body)
def get_geoview_stream(name): stream_list = Stream.query(Stream.name == name).fetch() if not stream_list: return [] stream = stream_list[0] # return images img_list = Image.query(ancestor=stream.key).order( Image.upload_date).fetch() # make a list img_info = [] for img in img_list: # make a new dict single_img_dict = {} # store img_url single_img_dict['img_url'] = img.url # store img_date single_img_dict['img_date'] = str(img.upload_date) if not img.gps_lon: img.gps_lon = 0.0 if not img.gps_lat: img.gps_lat = 0.0 # store gps data - lon single_img_dict['img_lon'] = img.gps_lon # store gps data - lat single_img_dict['img_lat'] = img.gps_lat # append this dict to "return" list img_info.append(single_img_dict) return img_info
def get(self): stream_name = self.request.get('stream_name') if stream_name: key = ndb.Key('Stream', stream_name) stream = key.get() else: stream = None if stream: increment = self.request.get('increment') if increment: stream.views += int(increment) stream.recent_views.append(datetime.datetime.now()) stream.put() cursor = self.request.get('cursor') cursor = int(cursor) if cursor else 0 upload_url = blobstore.create_upload_url('/upload_photo') template_values = { 'stream': stream, 'cursor': cursor, 'upload_url': upload_url } template = JINJA_ENVIRONMENT.get_template('views/view-stream.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values)) else: streams = Stream.query().order(Stream.date).fetch() template_values = { 'streams': streams, } template = JINJA_ENVIRONMENT.get_template('views/view-streams.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def post(self): if REPORT_RATE_MINS == "0": return if not REPORT_LAST: REPORT_LAST = datetime.now() return td = (datetime.now() - REPORT_LAST).seconds if td < int(REPORT_RATE_MINS)*60: return REPORT_LAST = datetime.now() from google.appengine.api import mail as gmail form = [str(datetime.now())] streams = sorted(Stream.dump(),key=lambda x: len(x.views),reverse=True)[:3] streams = map(itemgetter('stream_id','views'),streams) form.extend(streams) message = gmail.EmailMessage() message.sender = "*****@*****.**" message.to = "*****@*****.**" message.subject = "[Connex.us] Trending report for %s." % form[0] message.body = """\ Here are the Top 3 streams for {0:} 1. {1[0]} ({1[1]} views) 2. {2[0]} ({2[1]} views) 3. {3[0]} ({3[1]} views) Connex.us\ """.format(*form) message.send() self.respond(status="Sent a trending report rate at %s"%form[0])
def is_subscribed(name, pigeon_id): pigeon_key = ndb.Key(Pigeon, pigeon_id) stream_list = Stream.query(Stream.name == name).fetch() stream_key = stream_list[0].key sub_list = Subscription.query( Subscription.Pigeon_key == pigeon_key, Subscription.Stream_key == stream_key).fetch() return True if sub_list else False
def get(self): tags = set() for stream in Stream.query().fetch(): tags.update(stream.tags) tags.add(stream.key.id()) meta = Meta.get_meta() meta.cached_tags = list(tags) meta.put()
def post(self): user = users.get_current_user() if not user: self.login_page() else: name = self.request.get('name') message = self.request.get('message') key = ndb.Key('Stream', name) stream = key.get() if stream: self.template( 'views/error.html', error='Error: you tried to create a new stream ' + 'whose name is the same as an existing ' + 'stream; operation did not complete') else: subscribers = filter( lambda s: s != '', map( unicode.lower, map(unicode.strip, self.request.get('subscribers').split(',')))) message = self.request.get('message') tags = filter( lambda t: t != '', map(unicode.strip, self.request.get('tags').split(','))) cover_image_url = self.request.get('cover_image_url') cover_image_url = cover_image_url if cover_image_url \ else 'http://placehold.it/190x190.png' stream = Stream(id=name, name=name, owner=user.email().lower(), subscribers=subscribers, tags=tags, cover_image_url=cover_image_url, images=[]) body = ('You are now subscribed to the %s stream:\n' + 'http://mh33338-connexus.appspot.com/view?' + 'stream_name=%s&increment=1\n%s' % (name, message)) sender_address = 'Matthew Halpern <*****@*****.**>' subject = '[mh33338-conexus] Subscription to %s Stream' % name stream.put() for subscriber in subscribers: mail.send_mail(sender_address, subscriber, subject, body) self.redirect('/manage')
def get(self): streams = Stream.query().fetch() logging.info("STREAMS %d" % len(streams)) now = datetime.datetime.now() for stream in streams: stream.recent_views = filter(lambda rv: (now - rv).seconds < SECS_PER_HOUR, stream.recent_views) stream.put()
def create_user_stream(): try: # parse arguments parser = reqparse.RequestParser() parser.add_argument('name') parser.add_argument('description', default="Just a stream") parser.add_argument('isPublic', default=True) form = parser.parse_args() # grab current user user = User.objects.get(id=g.user['id']) # create new stream stream = Stream() stream.name = form['name'] stream.description = form['description'] stream.isPublic = form['isPublic'] stream.user = user stream.save() tiny_id = tinyurl.encode(str(stream.id)) url = url_for('spa_web.single_stream', stream_id=tiny_id) return {'status': 'success', 'url': url}, 200 except Exception as err: print "Error while creating stream: " + repr(err) return {'status': 'failed', 'error': repr(err)}, 500
def create_subscription(pigeon_id, name): pigeon_key = ndb.Key(Pigeon, pigeon_id) stream_list = Stream.query(Stream.name == name).fetch() stream_key = stream_list[0].key sub = Subscription() sub.Pigeon_key = pigeon_key sub.Stream_key = stream_key sub.put() return
def get(self): streams = Stream.query().fetch() logging.info("STREAMS %d" % len(streams)) now = datetime.datetime.now() for stream in streams: stream.recent_views = filter( lambda rv: (now - rv).seconds < SECS_PER_HOUR, stream.recent_views) stream.put()
def get_trending_stream(): stream_list = Stream.query().fetch() for stream in stream_list: # count the number of views and discard the overtime logs delta = timedelta(hours=1) for i, dt in enumerate(stream.view_dates): if datetime.now() - dt < delta: stream.view_dates = stream.view_dates[i:] break stream.view_dates.append(datetime.now()) stream.num_of_views = len(stream.view_dates) stream.put() stream_list = Stream.query().order(Stream.num_of_views).fetch() return map( lambda s: { "Name": s.name, "CoverPage": s.cover_url, "NumberOfViews": s.num_of_views }, stream_list[::-1][:3])
def delete_subscription(pigeon_id, name): pigeon_key = ndb.Key(Pigeon, pigeon_id) stream_list = Stream.query(Stream.name == name).fetch() stream_key = stream_list[0].key sub_list = Subscription.query( Subscription.Pigeon_key == pigeon_key, Subscription.Stream_key == stream_key).fetch() if sub_list: sub_list[0].key.delete() return
def get(self): owner_streams = Stream.query_by_owner( users.get_current_user().user_id()).fetch() self.response.headers['Content-Type'] = 'application/json' self.response.out.write( json.dumps([ dict(g.to_dict(), **dict(id=g.key.id())) for g in owner_streams ], default=default_json_serializer))
def post(self): form = json.loads(self.request.body) stream = Stream.getStream(form['stream_id']) if not stream: return self.respond(error="Stream %(stream_id)r does not exist." % form) stream.addView() self.respond(status="Added new view to stream %r at %s." % (form['stream_id'] ,stream.views[0]))
def post(self): if not populate_user()['logged_in']: return self.redirect('/') user_id = populate_user()['nickname'] stream_id = self.request.get('stream_name') user = User.get_by_id(user_id) if not user: return self.response.out.write("Not Found!") user.subscribed_ids.append(Stream.get_by_id(stream_id).key) user.put() return self.redirect('/view?stream_name='+stream_id)
def post(self): form = json.loads(self.request.body) stream = Stream.getStream(form['stream_id']) if not stream: return self.respond(error="Stream %(stream_id)r does not exist" % form) for image_id in set(form['images']) & set(stream.images): stream.removeImage(image_id) return self.respond(status="Images %(images)r removed" % form)
def post(self): if not populate_user()['logged_in']: return self.redirect('/') user_id = populate_user()['nickname'] stream_id = self.request.get('stream_name') user = User.get_by_id(user_id) if not user: return self.response.out.write("Not Found!") user.subscribed_ids.append(Stream.get_by_id(stream_id).key) user.put() return self.redirect('/view?stream_name=' + stream_id)
def get_search_stream_two(stream_name_list): result = [] count = 0 for i, name in enumerate(stream_name_list): if count >= 10000: break stream_list = Stream.query(Stream.name == name).fetch() if stream_list: count += 1 stream = stream_list[0] result.append({"Name": stream.name, "CoverPage": stream.cover_url}) return result
def get(self): user = users.get_current_user() if not user: template_values = { 'login_url': users.create_login_url(self.request.uri) } template = JINJA_ENVIRONMENT.get_template('views/login.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values)) else: owned_streams = (Stream.query(Stream.owner == user.email().lower() ).order(-Stream.name).fetch()) subscribed_streams = (Stream.query( Stream.subscribers == user.email().lower()).order( -Stream.name).fetch()) template_values = { 'owned_streams': owned_streams, 'subscribed_streams': subscribed_streams } template = JINJA_ENVIRONMENT.get_template('views/manage.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def get(self): query = self.request.get('query') if query: streams = Stream.query().order(Stream.date).fetch() matches = filter(lambda s: query in s.name or query in s.tags, streams)[:5] else: query = '' matches = [] template_values = {'query': query, 'matches': matches} template = JINJA_ENVIRONMENT.get_template('views/search.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def post(self): user = users.get_current_user() if not user: self.login_page() else: name = self.request.get('name') message = self.request.get('message') key = ndb.Key('Stream', name) stream = key.get() if stream: self.template('views/error.html', error='Error: you tried to create a new stream ' + 'whose name is the same as an existing ' + 'stream; operation did not complete') else: subscribers = filter(lambda s: s != '', map(unicode.lower, map(unicode.strip, self.request.get('subscribers').split(',')) )) message = self.request.get('message') tags = filter(lambda t: t != '', map(unicode.strip, self.request.get('tags').split(','))) cover_image_url = self.request.get('cover_image_url') cover_image_url = cover_image_url if cover_image_url \ else 'http://placehold.it/190x190.png' stream = Stream(id=name, name=name, owner=user.email().lower(), subscribers=subscribers, tags=tags, cover_image_url=cover_image_url, images=[]) body = ('You are now subscribed to the %s stream:\n' + 'http://mh33338-connexus.appspot.com/view?' + 'stream_name=%s&increment=1\n%s' % (name, message)) sender_address = 'Matthew Halpern <*****@*****.**>' subject = '[mh33338-conexus] Subscription to %s Stream' % name stream.put() for subscriber in subscribers: mail.send_mail(sender_address, subscriber, subject, body) self.redirect('/manage')
def create_image(comment, name, url, stream_name, lon, lat): stream_list = Stream.query(Stream.name == stream_name).fetch() if stream_list: stream = stream_list[0] image_key = ndb.Key(Image, url, parent=stream.key) img = Image() img.key = image_key img.name = name img.url = url img.comments = comment img.gps_lon = lon img.gps_lat = lat img.put() return
def get(self): streams = Stream.query().fetch() sorted_streams = sorted(streams, key=lambda s: len(s.recent_views), reverse=True) config = TrendingEmailConfig.query().fetch(1)[0] if not config: config = TrendingEmailConfig() template_values = { 'streams': sorted_streams[:3], 'email_mode': config.mode } template = JINJA_ENVIRONMENT.get_template('views/trending.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def post(self): user = users.get_current_user() if user: stream_names = self.request.POST.getall('stream') if stream_names: streams = Stream.query(Stream.name.IN(stream_names)).fetch() ndb.delete_multi(map(lambda s: s.key, streams)) self.redirect('/manage') else: template_values = {'error': 'Error: user not logged in.'} template = JINJA_ENVIRONMENT.get_template('views/error.html') self.response.headers['Content-Type'] = \ 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def get(self): query = self.request.get('query') if query: streams = Stream.query().order(Stream.date).fetch() matches = filter(lambda s: query in s.name or query in s.tags, streams)[:5] else: query = '' matches = [] template_values = { 'query': query, 'matches': matches } template = JINJA_ENVIRONMENT.get_template('views/search.html') self.response.headers['Content-Type'] = 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def post(self): user = users.get_current_user() if user: stream_names = self.request.POST.getall('stream') if stream_names: streams = Stream.query(Stream.name.IN(stream_names)).fetch() ndb.delete_multi(map(lambda s: s.key, streams)) self.redirect('/manage') else: template_values = { 'error': 'Error: user not logged in.' } template = JINJA_ENVIRONMENT.get_template('views/error.html') self.response.headers['Content-Type'] = \ 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def get(self): self.response.headers['Content-Type'] = 'application/json' stream_name = self.request.get('stream_name') if not stream_name: return self.show_all_streams() stream = Stream.get_by_id(stream_name) if not stream: return self.error(404) # Increment View Count stream.view_count += 1 stream.put() View(stream_id=stream.key).put() return self.response.out.write(json.dumps(stream.to_dict(), cls=MyEncoder))
def get(self): self.response.headers['Content-Type'] = 'application/json' stream_name = self.request.get('stream_name') if not stream_name: return self.show_all_streams() stream = Stream.get_by_id(stream_name) if not stream: return self.error(404) # Increment View Count stream.view_count += 1 stream.put() View(stream_id=stream.key).put() return self.response.out.write( json.dumps(stream.to_dict(), cls=MyEncoder))
def post(self): user = users.get_current_user() if user: stream_names = self.request.POST.getall('stream') if stream_names: streams = Stream.query(Stream.name.IN(stream_names)).fetch() for stream in streams: stream.subscribers.append(user.email().lower()) stream.put() self.redirect('/view?stream_name=%s' % stream_names[0]) else: template_values = {'error': 'Error: user not logged in.'} template = JINJA_ENVIRONMENT.get_template('views/error.html') self.response.headers['Content-Type'] = \ 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def create_stream(pigeon_id, name, cover_url, sub_list, tag_list): pigeon_key = ndb.Key(Pigeon, pigeon_id) stream = Stream() stream.key = ndb.Key(Stream, name, parent=pigeon_key) stream.name = name stream.cover_url = cover_url stream.tags = tag_list stream.put() for pid in sub_list: if pid != pigeon_id: if not pigeon_exists(pid): create_pigeon(pid) suber_key = ndb.Key(Pigeon, pid) sub = Subscription() sub.Pigeon_key = suber_key sub.Stream_key = stream.key sub.put() return
def update_stream_tag(stream_name, new_tag_list): stream_list = Stream.query(Stream.name == stream_name).fetch() if stream_list: stream = stream_list[0] formal_tag_list = stream.tags if not formal_tag_list: formal_tag_list = [] formal_tag_list.extend(new_tag_list) # filter set final_tag_set = set() for tag in formal_tag_list: final_tag_set.add(tag) # convert set to list stream.tags = list(final_tag_set) stream.put() return
def post(self): body = json.loads(self.request.body) user_id = body['user_id'] if not user_id or not User.get_by_id(user_id): return self.redirect('/') user = User.get_by_id(user_id) stream_ids = body['stream_ids'] for stream_id in stream_ids: stream = Stream.get_by_id(stream_id) if not stream: continue stream_key = stream.key if user.is_owned(stream_id): stream_key.delete() user.owned_ids = [sub for sub in user.owned_ids if sub.id() not in stream_ids] user.put() Leaderboard.refresh()
def post(self): user = users.get_current_user() if user: stream_names = self.request.POST.getall('stream') if stream_names: streams = Stream.query(Stream.name.IN(stream_names)).fetch() for stream in streams: stream.subscribers.append(user.email().lower()) stream.put() self.redirect('/view?stream_name=%s' % stream_names[0]) else: template_values = { 'error': 'Error: user not logged in.' } template = JINJA_ENVIRONMENT.get_template('views/error.html') self.response.headers['Content-Type'] = \ 'text/html; charset=utf-8' self.response.write(template.render(template_values))
def get_single_stream(name): stream_list = Stream.query(Stream.name == name).fetch() if not stream_list: return [] stream = stream_list[0] # count the number of views and discard the overtime logs delta = timedelta(hours=1) for i, dt in enumerate(stream.view_dates): if datetime.now() - dt < delta: stream.view_dates = stream.view_dates[i:] break stream.view_dates.append(datetime.now()) stream.num_of_views = len(stream.view_dates) stream.put() # return images img_list = Image.query(ancestor=stream.key).order( Image.upload_date).fetch() return map(lambda img: img.url, img_list[::-1])
def post(self): form = json.loads(self.request.body) stream = Stream.getStream(form['stream_id']) if not stream: return self.respond(error="Stream %(stream_id)r does not exist." % form) outpages = [] images = [] for idx in form['page_range'].split(','): if not idx: break idx = int(idx) if idx >= len(stream.images): continue images.append(stream.images[idx]) outpages.append(idx) self.respond(page_range=outpages,images=images , status="Grabbed pages %r from stream %r" % (outpages,form['stream_id']))
def write_blob(self, data, info): blob = files.blobstore.create(mime_type=info['type'], _blobinfo_uploaded_filename=info['name']) with files.open(blob, 'a') as f: f.write(data) files.finalize(blob) print blob user_photo = Image(stream_id=self.request.get('stream_id') ,image_id=self.request.get('image_id') ,blob_key=files.blobstore.get_blob_key(blob)) stream = Stream.getStream(self.request.get('stream_id')) if stream: logging.debug("Adding image at %s (%r)" % (user_photo.create_date,str(user_photo.blob_key))) stream.addImage(user_photo) return files.blobstore.get_blob_key(blob)
def post(self): body = json.loads(self.request.body) user_id = body['user_id'] if not user_id or not User.get_by_id(user_id): return self.redirect('/') user = User.get_by_id(user_id) stream_ids = body['stream_ids'] for stream_id in stream_ids: stream = Stream.get_by_id(stream_id) if not stream: continue stream_key = stream.key if user.is_owned(stream_id): stream_key.delete() user.owned_ids = [ sub for sub in user.owned_ids if sub.id() not in stream_ids ] user.put() Leaderboard.refresh()
def post(self): form = json.loads(self.request.body) user = User.getUser(form['user_id']) if not user: return self.respond(error="User %(user_id)r does not exist" % form) if Stream.exists(form['stream_id']): return self.respond(error="Stream %(stream_id)r already exists" % form) # Create a new stream new_stream = Stream(user_id=form['user_id'] ,stream_id=form['stream_id'] ,last_add=None ,tags=form['tags'] ,cover_url=form['cover_url'] if 'cover_url' in form else '') # Update the user's stream list and insert stream into db user.addStream(new_stream) self.respond(status="Created stream %(stream_id)r for user %(user_id)r." % form)
def get(self): query = self.request.get('query') stream_list = [] if query: for stream in Stream.query().fetch(): if query in stream.key.id() or stream.check_tags(query): stream_dict = stream.to_dict() stream_list.append(stream_dict) data = populate_user() data['results'] = stream_list[:SEARCH_COUNT] data['results_count'] = len(stream_list) data['query'] = query if self.request.get('raw'): print data self.response.headers['Content-Type'] = 'application/json' for stream in data['results']: stream.pop('image_ids', None); stream.pop('date') print data return self.response.out.write(json.dumps(data)) template = JINJA_ENVIRONMENT.get_template('search.html') self.response.write(template.render(data))
def post(self): form = json.loads(self.request.body) if 'user_id' in form: user = User.getUser(form['user_id']) if not user: return self.respond(error="User %(user_id)r does not exist" % form) user_streams = [Stream.getStream(stream_id).dumpStream() for stream_id in user.user_streams if Stream.exists(stream_id)] sub_streams = [Stream.getStream(stream_id).dumpStream() for stream_id in user.subscribed_streams if Stream.exists(stream_id)] payload = {'user_streams': user_streams , 'subscribed_streams': sub_streams , 'status': "Grabbed streams for user %(user_id)r" % form} elif 'streams' in form: streams = [Stream.getStream(s_id).dumpStream() for s_id in form['streams'] if Stream.exists(s_id)] payload = {'streams': streams} self.respond(**payload)
def post(self): self.respond(streams=Stream.dump(),status="Grabbed all streams.")
def get(self): streams = Stream.query().order(Stream.date).fetch() for stream in streams: self.update_term(stream.name, stream.name) for tag in stream.tags: self.update_term(tag, stream.name)
def post(self): stream_token = self.request.get("stream_token") stream = Stream.query(Stream.streamSecret == stream_token).get() stream.key.delete() self.response.write("Disconnected") vars.stream_manager.message_room(stream.lecture_id,{'cmd': "removeUser", 'id': users.get_current_user().user_id()});