Esempio n. 1
0
def add_points(update: Update, context):
    points = update.message.text
    try:
        int(points)
    except:
        # Telegram clients will display a reply interface to the user
        # (act as if the user has selected the bot’s message and tapped ‘Reply’)
        force_reply = ForceReply(force_reply=True, selective=True)
        update.message.reply_text(
            f'{points} is not a number. Please enter number 😊',
            reply_markup=force_reply)
        return POINTS
    else:

        context.user_data[POINTS] = points
        update.message.reply_text(
            f'Ok. Activity {context.user_data[ACTIVITY]} gives {context.user_data[POINTS]} points 😎',
            quote=False)

        # Saving activity to the database
        act = Activity(activity_name=context.user_data[ACTIVITY],
                       points=context.user_data[POINTS],
                       author_user_id=update.effective_user.id,
                       leaderboard_id=update.effective_chat.id)
        act.save_activity()

        # Get new user input
        return wait_for_input(update, context)
Esempio n. 2
0
    def post(self):
        json = request.json['activity']
        print dateutil.parser.parse(json['date'])

        activity = Activity(
            user_id=json['user'],
            work_order=json['work_order'],
            date=dateutil.parser.parse(json['date']),
            type=json['type'],
            note=json['note']
        )

        if not activity.save():
            abort(400)

        model = {
            'activity': {
                'id': activity.id,
                'work-order': activity.work_order_id,
                'user': activity.user_id,
                'date': activity.date.isoformat(),
                'type': activity.type
            }
        }
        print model
        return jsonify(model)
Esempio n. 3
0
def add_activity():

    new_activity = Activity(**request.json)

    db.session.add(new_activity)
    db.session.commit()

    return jsonify(new_activity.to_dict())
Esempio n. 4
0
def create_signup_activity(youtify_user_model):
    target = simplejson.dumps({})
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model,
                 verb='signup',
                 actor=actor,
                 target=target,
                 type='outgoing')
    m.put()
Esempio n. 5
0
 def post(self, event_id):
     activity_obj = json.loads(self.request.body)
     activity = Activity(
         parent=ndb.Key("Event", event_id),
         activityName=activity_obj["activityName"],
         createDateTime=datetime.now(),
         activityTips=activity_obj["activityTips"] if "activityTips" in activity_obj else None,
         healthTips=activity_obj["healthTips"] if "healthTips" in activity_obj else None,
         relationToOtherActivities=activity_obj["relationToOtherActivities"] if "relationToOtherActivities" in activity_obj else None)
     activity.put()
     self.response.out.write(json.dumps({"200":"Activity stored successfully.",
         "Details": activity_obj}))
Esempio n. 6
0
def create_activity(itinerary_id,
                    activity_name,
                    address,
                    lat,
                    lng,
                    activity_day=None,
                    activity_time=None,
                    activity_note=None):
    """Create and return a new activity."""

    activity = Activity(
        itinerary_id=itinerary_id,
        activity_name=activity_name,
        address=address,
        #place_id=place_id,
        lat=lat,
        lng=lng,
        activity_day=activity_day,
        activity_time=activity_time,
        activity_note=activity_note,
    )

    db.session.add(activity)
    db.session.commit()

    return activity
Esempio n. 7
0
    def get(self):
        stats = Stats()

        stats.nr_of_users = 0
        stats.nr_of_active_users = 0
        stats.nr_of_playlists = len([i for i in Playlist.all()])
        stats.nr_of_users_with_flattr_account = 0
        stats.nr_of_flattrs = 0
        stats.nr_of_playlist_subscriptions = 0
        stats.nr_of_follow_relations = len([i for i in FollowRelation.all()])

        for user in YoutifyUser.all():
            stats.nr_of_users += 1
            
            if user.flattr_user_name:
                stats.nr_of_users_with_flattr_account += 1

            if user.playlist_subscriptions:
                stats.nr_of_playlist_subscriptions += len(user.playlist_subscriptions)

            if user.last_login:
                delta = datetime.now() - user.last_login
                if delta.seconds < 3600 * 24 * 7:
                    stats.nr_of_active_users += 1

            stats.nr_of_flattrs += len([i for i in Activity.all().filter('owner =', user).filter('verb =', 'flattr')])

        stats.put()
Esempio n. 8
0
def load_activities():
    """Load chidlren from c.user into database."""

    print("activities")

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be trying to add duplicate children

    # Read a.user file and insert data
    for row in open("data/a.user"):
        row = row.rstrip()
        activity_id, activity_name, for_parents, for_children = row.split("|")

        for_parents = bool(for_parents)
        for_children = bool(for_children)

        activity = Activity(activity_id=activity_id,
                            activity_name=activity_name,
                            for_parents=for_parents,
                            for_children=for_children)

        # We need to add to the session or it won't ever be stored
        db.session.add(activity)

    # commit our work
    db.session.commit()
def get_activity():
    """Process adding a new activity."""

    user = User.query.get(session["user_id"])

    # Get form variables
    activity = request.form["activity"]
    unit = request.form["unit"]

    act_exists = Activity.query.filter_by(act_name=activity, act_unit=unit).first()

    if act_exists:
        flash("Activity already exists")

    if not act_exists:

        new_act = Activity(act_name=activity, act_unit=unit)
        user.activities.append(new_act)

        db.session.add(new_act)
        db.session.commit()

        flash(f"Activity {activity} added.")

    print(act_exists)
    return redirect("/activity")
Esempio n. 10
0
def user_trip_update_activity(trip_id):
    """Allow user to update an activity for a unique trip."""

    user_id = session.get("user_id")
    user_trip_to_update = UserTrip.query.filter_by(trip_id=trip_id).first()
    print "This is the trip: ", user_trip_to_update

    if user_id and user_trip_to_update:

        if request.form:
            print request.form.get("category")
            old_trip_activity_query = Activity.query.filter_by(
                category=request.form.get("category"),
                description=request.form.get("description")).first()
            print "This is the old activity via query: ", old_trip_activity_query
            old_trip_activity_query.category = (request.form.get("category"))
            print "This is the old category: ", old_trip_activity_query.category
            old_trip_activity_query.description = (
                request.form.get("description"))
            print "This is the old description: ", old_trip_activity_query.description
            new_activity = Activity(
                category=request.form.get("category"),
                description=request.form.get("description"),
                trip_id=trip_id)
            db.session.add(new_activity)
            db.session.commit()
            flash('You have successfully updated an activity for this trip.')
            print "Trip activity update has been committed to db", new_activity

    return redirect("/user/" + str(trip_id))
Esempio n. 11
0
 def get(self):
     json = simplejson.dumps({
         'nr_of_users': len([i for i in YoutifyUser.all().filter('flattr_access_token !=', None)]),
         'nr_of_flattrs': len([i for i in Activity.all().filter('type =', 'outgoing').filter('verb =', 'flattr')]),
     })
     memcache.delete('flattr_stats')
     memcache.add('flattr_stats', json, 3600*24)
Esempio n. 12
0
    def get(self):
        stats = Stats()

        stats.nr_of_users = 0
        stats.nr_of_active_users = 0
        try:
            stats.nr_of_playlists = Playlist.all(keys_only=True).count(read_policy=EVENTUAL_CONSISTENCY)
        except:
            pass
        stats.nr_of_users_with_flattr_account = 0
        stats.nr_of_users_with_dropbox = 0
        try:
            stats.nr_of_flattrs = Activity.all().filter('type =', 'outgoing').filter('verb =', 'flattr').count(read_policy=EVENTUAL_CONSISTENCY)
        except:
            pass
        stats.nr_of_playlist_subscriptions = 0
        try:
            stats.nr_of_follow_relations = FollowRelation.all(keys_only=True).count(read_policy=EVENTUAL_CONSISTENCY)
        except:
            pass

        try:
            for user in YoutifyUser.all():
                stats.nr_of_users += 1
                
                if user.flattr_user_name:
                    stats.nr_of_users_with_flattr_account += 1
                
                if user.dropbox_user_name:
                    stats.nr_of_users_with_dropbox += 1

                if user.playlist_subscriptions:
                    stats.nr_of_playlist_subscriptions += len(user.playlist_subscriptions)

                if user.last_login:
                    delta = datetime.now() - user.last_login
                    if delta.seconds < 3600 * 24 * 7:
                        stats.nr_of_active_users += 1
        except:
            pass
        
        pings = []
        last_ping = None

        try:
            for m in PingStats.all().order('-date').fetch(6*24*7):
                if last_ping is not None and last_ping.date.hour is not m.date.hour:
                    pings.append({
                        'date': str(last_ping.date),
                        'pings': last_ping.pings
                    })
                    last_ping = m
                elif last_ping is None or m.pings > last_ping.pings:
                    last_ping = m
        except:
            pass
            
        stats.pings = simplejson.dumps(pings)
        
        stats.put()
def register_process():
    """Process registration."""

    # Get form variables
    email    = request.form["email"]
    password = request.form["password"]
    username = request.form["username"]
    
    user_exists = User.query.filter_by(email=email).first()

    if user_exists:
        flash(f"""User {email} already exists. 
            Please log in, you don't need to register! :)""")
        return redirect("/")

    new_user = User(email=email, password=password, username=username)

    for act_name, act_unit in Activity.DEFAULT_ACTIVITIES:
        activity = Activity(act_name=act_name, act_unit=act_unit)
        new_user.activities.append(activity)

    db.session.add(new_user)
    db.session.commit()

    flash(f"User {email} added. Now please log in.")
    return redirect("/")
Esempio n. 14
0
def load_activities():
    """Load activities from activities.csv into database"""

    print "Activities"

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be adding duplicate categories
    Activity.query.delete()

    # Read category.csv file and insert data
    for row in open("seed_data/activities.csv"):
        row = row.rstrip()
        act_id, cat_id, eb_cat_id, name, act_type, eb_format_id, sub_cat, mu_id, img_url = row.split(
            ",")

        activity = Activity(act_id=act_id,
                            cat_id=cat_id,
                            eb_cat_id=eb_cat_id,
                            name=name,
                            act_type=act_type,
                            eb_format_id=eb_format_id,
                            sub_cat=sub_cat,
                            mu_id=mu_id,
                            img_url=img_url)

        # Need to add to session to store
        db.session.add(activity)

    # Commit my work

    db.session.commit()
Esempio n. 15
0
def save_activity():
    """Save recipe and movie user chose to the database and user's profile"""
    ### FROM random_recipe_and_movie_results.html

    user_id = session.get("user_id")

    if user_id:
        recipe_id = session.get("recipe_id")
        movie_id = session.get("movie_id")

        date_today = (datetime.today() -
                      timedelta(hours=8)).strftime("%Y-%m-%d")

        activity = Activity.query.filter_by(user_id=user_id,
                                            movie_id=movie_id,
                                            recipe_id=recipe_id).first()

        if not activity:
            new_entry = Activity(user_id=user_id,
                                 movie_id=movie_id,
                                 recipe_id=recipe_id,
                                 date=date_today)
            db.session.add(new_entry)
            db.session.commit()
            flash("Activity successfully saved!", 'alert-success')

    return ('', 204)
Esempio n. 16
0
def recommend(time, category):
    start, end = map(lambda x: datetime.datetime.strptime(x, '%H:%M').time(),
                     time.split('-'))
    category = _get_item_by_name(Category, category)

    # Get the day of the week. Now it is fixed to the timezone Europe/Madrid, but if the city was passed
    # it could be calculated for it, loading its timezone from the database.
    day = datetime.datetime.now(pytz.timezone('Europe/Madrid'))
    day = WEEK_DAYS[day.weekday()]

    # User's interval bounds expressed in hours
    user_start_hour = start.hour + start.minute / 60
    user_end_hour = end.hour + end.minute / 60

    # Activities opening intervals bounds expressed in hours
    activity_start_hour = OpeningInterval.start.hour + OpeningInterval.start.minute / 60
    activity_end_hour = OpeningInterval.end.hour + OpeningInterval.end.minute / 60

    q = Activity.select().join(OpeningInterval).where(
        (Activity.category == category) & (OpeningInterval.day == day) &
        # There's enough time to make the visit before it closes
        ((
            # Activity start <= user interval start
            (OpeningInterval.start <= start) &
            (user_start_hour + Activity.hours_spent <= activity_end_hour) &
            (user_start_hour + Activity.hours_spent <= user_end_hour)) | (
                # Activity start >= user interval start
                (OpeningInterval.start >= start) &
                (activity_start_hour + Activity.hours_spent <= user_end_hour)))
    ).order_by(Activity.hours_spent.desc())

    if q.exists():
        return q[0].geojson
    return abort(404)
Esempio n. 17
0
def load_activities():
    """Retrieve activities information from recreation.gov and load into database. Refers to Activity."""

    # if there's an existing table, delete and reload it
    Activity.query.delete()

    # returns a dictionary with a list of dictionaries nested
    results = json.load(
        urllib.urlopen(
            'https://ridb.recreation.gov/api/v1/activities/?apikey={}'.format(
                key)))

    # returns a list of dictionaries
    activities = results[u'RECDATA']

    # line is a dictionary
    for line in activities:

        activity_id = line[u'ActivityID']
        activity_name = line[u'ActivityName'].lower()

        activity = Activity(activity_id=activity_id,
                            activity_name=activity_name)

        db.session.add(activity)

    db.session.commit()
Esempio n. 18
0
def create_activity(activity_name, min_cost, max_cost, min_age, max_age, location, effort_rating, keywords, activity_description):
    """Create and return a new activity."""

    activity = Activity(activity_name=activity_name,min_cost=min_cost, max_cost=max_cost, min_age=min_age, max_age=max_age, location=location, effort_rating=effort_rating, keywords=keywords, activity_description=activity_description)

    db.session.add(activity)
    db.session.commit()

    return activity
Esempio n. 19
0
def create_activity(title, user): # pass grade and subject here...
    """Create and return a new movie."""

    activity = Activity(title = title, user = user)

    db.session.add(activity)
    db.session.commit()

    return activity
Esempio n. 20
0
def create_activity(activity_name):
    """Create and return a new activity."""

    activity = Activity(activity_name=activity_name)
    
    db.session.add(activity)
    db.session.commit()

    return activity
Esempio n. 21
0
    def get(self):
        activities = []
        for activity in Activity.list():
            activities.append({
                'id': activity.id,
                'work_order': activity.work_order_id,
                'date': activity.date,
                'type': activity.type,
                'note': activity.note
            })

        return jsonify({'activities': activities})
Esempio n. 22
0
def create_activity(dog_id, activity_type, activity_date, activity_month,
                    activity_time, activity_duration, activity_note):
    activity = Activity(dog_id=dog_id,
                        activity_type=activity_type,
                        activity_date=activity_date,
                        activity_month=activity_month,
                        activity_time=activity_time,
                        activity_duration=activity_duration,
                        activity_note=activity_note)
    db.session.add(activity)
    db.session.commit()
    return activity
Esempio n. 23
0
    def get(self):
        activities = []
        for activity in Activity.list():
            activities.append({
                'id': activity.id,
                'work_order': activity.work_order_id,
                'date': activity.date,
                'type': activity.type,
                'note': activity.note
            })

        return jsonify({'activities': activities})
Esempio n. 24
0
def load_activities():
    print "Activities"

    Activity.query.delete()

    with open('seed_data/activities.csv', 'rb') as activities_csvfile:
        activities = csv.reader(activities_csvfile, delimiter=',')
        for a in activities:
            category_id, name = a
            db_activity = Activity(category_id=category_id, activity_name=name)
            db.session.add(db_activity)
        db.session.commit()
Esempio n. 25
0
 def get(self):
     json = simplejson.dumps({
         'nr_of_users':
         len([
             i for i in YoutifyUser.all().filter('flattr_access_token !=',
                                                 None)
         ]),
         'nr_of_flattrs':
         len([
             i for i in Activity.all().filter('type =', 'outgoing').filter(
                 'verb =', 'flattr')
         ]),
     })
     memcache.delete('flattr_stats')
     memcache.add('flattr_stats', json, 3600 * 24)
Esempio n. 26
0
    def post(self):
        json = request.json['activity']
        print dateutil.parser.parse(json['date'])

        activity = Activity(user_id=json['user'],
                            work_order=json['work_order'],
                            date=dateutil.parser.parse(json['date']),
                            type=json['type'],
                            note=json['note'])

        if not activity.save():
            abort(400)

        model = {
            'activity': {
                'id': activity.id,
                'work-order': activity.work_order_id,
                'user': activity.user_id,
                'date': activity.date.isoformat(),
                'type': activity.type
            }
        }
        print model
        return jsonify(model)
Esempio n. 27
0
def create_external_subscribe_activity(youtify_user_model, external_user_model):
    target = simplejson.dumps(get_external_user_subscription_struct(external_user_model))
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model, verb='external_subscribe', actor=actor, target=target, type='outgoing')
    m.put()

    for relation in FollowRelation.all().filter('user2 =', youtify_user_model.key().id()):
        m = Activity(owner=YoutifyUser.get_by_id(relation.user1), verb='external_subscribe', actor=actor, target=target, type='incoming')
        m.put()
Esempio n. 28
0
def query(**kwargs):
    q = Activity.select()

    if 'category' in kwargs:
        category = _get_item_by_name(Category, kwargs.get('category', None))
        q = q.where(Activity.category == category)
    if 'location' in kwargs:
        location = _get_item_by_name(Location, kwargs.get('location', None))
        q = q.where(Activity.location == location)
    if 'district' in kwargs:
        district = _get_item_by_name(District, kwargs.get('district', None))
        q = q.where(Activity.district == district)

    return {
        'type': 'FeatureCollection',
        'features': list(map(lambda act: act.geojson, q))
    }
Esempio n. 29
0
def load_activities():
    """Load activity ideas into database"""
    # Delete rows in table to prevent duplicates if file run again
    Activity.query.delete()

    for row in open("activities.txt"):
        row = row.rstrip().split("|")
        activity, description, img = row

        activity = Activity(
            activity=activity,
            description=description,
            img=img,
        )

        db.session.add(activity)
    db.session.commit()
Esempio n. 30
0
 def get(self, event_id):
     FORECAST_APIKEY = "0daceb1cb82c10ac44a5850b009b2124"
     ancestor_key = ndb.Key("Event", event_id)
     all_activities = Activity.all_activities(ancestor_key)
     self.response.headers['Content-Type'] = 'application/json'
     if all_activities.count() == 0:
         empty_reminder = {"Empty Datastore": "No activities for " + event_id + " available"}
         self.response.out.write(json.dumps(empty_reminder))
     else:
         # forecast = requests.get("https://api.forecast.io/forecast/" + 
         #     FORECAST_APIKEY +"/37.8267,-122.423")
         activity_list = []
         for a in all_activities:
             a_dict = a.to_dict()
             # result = forecast.json()
             # a_dict["weather"] = result
             activity_list.append(a_dict)
         self.response.out.write(json.dumps(activity_list, cls=MyEncoder))
Esempio n. 31
0
    def get(self):
        stats = Stats()

        stats.nr_of_users = 0
        stats.nr_of_active_users = 0
        stats.nr_of_playlists = len([i for i in Playlist.all()])
        stats.nr_of_users_with_flattr_account = 0
        stats.nr_of_flattrs = len([
            i for i in Activity.all().filter('type =', 'outgoing').filter(
                'verb =', 'flattr')
        ])
        stats.nr_of_playlist_subscriptions = 0
        stats.nr_of_follow_relations = len([i for i in FollowRelation.all()])

        for user in YoutifyUser.all():
            stats.nr_of_users += 1

            if user.flattr_user_name:
                stats.nr_of_users_with_flattr_account += 1

            if user.playlist_subscriptions:
                stats.nr_of_playlist_subscriptions += len(
                    user.playlist_subscriptions)

            if user.last_login:
                delta = datetime.now() - user.last_login
                if delta.seconds < 3600 * 24 * 7:
                    stats.nr_of_active_users += 1

        pings = []
        last_ping = None
        for m in PingStats.all().order('-date').fetch(6 * 24 * 7):
            if last_ping is not None and last_ping.date.hour is not m.date.hour:
                pings.append({
                    'date': str(last_ping.date),
                    'pings': last_ping.pings
                })
                last_ping = m
            elif last_ping is None or m.pings > last_ping.pings:
                last_ping = m

        stats.pings = simplejson.dumps(pings)

        stats.put()
Esempio n. 32
0
def create_subscribe_activity(youtify_user_model, playlist_model):
    """ user subscribed to playlist

    Both user and playlists owner gets a new activity
    """
    target = simplejson.dumps(get_playlist_struct_from_playlist_model(playlist_model))
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model, verb='subscribe', actor=actor, target=target, type='outgoing')
    m.put()

    m = Activity(owner=playlist_model.owner, verb='subscribe', actor=actor, target=target, type='incoming')
    m.put()
Esempio n. 33
0
def create_follow_activity(owner, other_user):
    """ owner started following other_user 

    Both owner and other_user gets a new activity
    """
    target = simplejson.dumps(get_youtify_user_struct(other_user))
    actor = simplejson.dumps(get_youtify_user_struct(owner))

    m = Activity(owner=owner, verb='follow', actor=actor, target=target, type='outgoing')
    m.put()

    m = Activity(owner=other_user, verb='follow', actor=actor, target=target, type='incoming')
    m.put()
Esempio n. 34
0
def create_flattr_activity(youtify_user_model, thing_id, thing_title):
    target = simplejson.dumps({
        'thing_id': thing_id,
        'thing_title': thing_title,
    })
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model, verb='flattr', actor=actor, target=target, type='outgoing')
    m.put()

    for relation in FollowRelation.all().filter('user2 =', youtify_user_model.key().id()):
        m = Activity(owner=YoutifyUser.get_by_id(relation.user1), verb='flattr', actor=actor, target=target, type='incoming')
        m.put()
Esempio n. 35
0
def create_follow_activity(owner, other_user):
    """ owner started following other_user 

    Both owner and other_user gets a new activity
    """
    target = simplejson.dumps(get_youtify_user_struct(other_user))
    actor = simplejson.dumps(get_youtify_user_struct(owner))

    m = Activity(owner=owner,
                 verb='follow',
                 actor=actor,
                 target=target,
                 type='outgoing')
    m.put()

    m = Activity(owner=other_user,
                 verb='follow',
                 actor=actor,
                 target=target,
                 type='incoming')
    m.put()
Esempio n. 36
0
def create_external_subscribe_activity(youtify_user_model,
                                       external_user_model):
    target = simplejson.dumps(
        get_external_user_subscription_struct(external_user_model))
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model,
                 verb='external_subscribe',
                 actor=actor,
                 target=target,
                 type='outgoing')
    m.put()

    for relation in FollowRelation.all().filter('user2 =',
                                                youtify_user_model.key().id()):
        m = Activity(owner=YoutifyUser.get_by_id(relation.user1),
                     verb='external_subscribe',
                     actor=actor,
                     target=target,
                     type='incoming')
        m.put()
Esempio n. 37
0
def display_activity():
    """ Activity Page """

    activity_query = request.form["activity_query"]
    playlist_name = request.form["playlist_name"]
    # Processes form data from HTML

    user_id = session.get('logged_user')['username']
     
    token = session.get('access_token')

    new_activity = Activity(activity_name=activity_query, user_id=user_id)
    db.session.add(new_activity)
    db.session.commit()
    activity_id = new_activity.activity_id
    # Seed activities table 

    auth_header = session['auth_header'] 
    # Generates authorization headers

    spotify_user_id = spotifyutils.get_spotify_user_id(auth_header)
    # Find logged user's spotify account

    playlist_id = spotifyutils.create_playlist(auth_header, spotify_user_id, playlist_name, activity_id)
    # Creates empty playlist that is stored as a playlist object locally and pushes to user's Spotify account    

    playlists_ids = spotifyutils.search_spotify_playlists(activity_query)
    # API call to query Spotify's playlists based off user's inputted activity 
    # returns list of playlist uris; NONE ARE STORED
    
    spotifyutils.search_playlists_tracks(playlists_ids, playlist_id)
    # API call to respective playlist ids; seeds locally

    playlist_uri = spotifyutils.seed_spotify_playlist(auth_header, playlist_id)
    # Pushes songs to playlist on user's Spotify account

    playlist_view_src = {'playlist':"https://open.spotify.com/embed/user/"+spotify_user_id+"/playlist/"+playlist_uri}
    # iframe/spotify widget passed into HTML via jinja 

    user_playlists = spotifyutils.users_playlists(user_id)

    return jsonify(playlist_view_src)
Esempio n. 38
0
def create_flattr_activity(youtify_user_model, thing_id, thing_title):
    target = simplejson.dumps({
        'thing_id': thing_id,
        'thing_title': thing_title,
    })
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model,
                 verb='flattr',
                 actor=actor,
                 target=target,
                 type='outgoing')
    m.put()

    for relation in FollowRelation.all().filter('user2 =',
                                                youtify_user_model.key().id()):
        m = Activity(owner=YoutifyUser.get_by_id(relation.user1),
                     verb='flattr',
                     actor=actor,
                     target=target,
                     type='incoming')
        m.put()
Esempio n. 39
0
def log_new_activity():

    user = session.get("user")
    item_id = request.form["item_id"]
    timestamp = datetime.now()

    item = Item.query.get(item_id)

    if item:
        new_activity = Activity(user_id=user['id'], item_id=item_id, date_logged=timestamp)
        #TODO: Error Handling
        db.session.add(new_activity)
        db.session.commit()
    else:
        return "Error: Item ID not found"

    list_url = "/list/" + str(item.list_id)

    #return jsonify(new_activity)
    return redirect(list_url)
Esempio n. 40
0
def create_subscribe_activity(youtify_user_model, playlist_model):
    """ user subscribed to playlist

    Both user and playlists owner gets a new activity
    """
    target = simplejson.dumps(
        get_playlist_struct_from_playlist_model(playlist_model))
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model,
                 verb='subscribe',
                 actor=actor,
                 target=target,
                 type='outgoing')
    m.put()

    m = Activity(owner=playlist_model.owner,
                 verb='subscribe',
                 actor=actor,
                 target=target,
                 type='incoming')
    m.put()
Esempio n. 41
0
def user_trip_add_activity(trip_id):
    """Allow user to add activities for a unique trip."""

    user_id = session.get("user_id")
    user_trip_to_update = UserTrip.query.filter_by(trip_id=trip_id).first()
    print "This is the trip: ", user_trip_to_update

    if user_id and user_trip_to_update:

        if request.form:
            new_activity = Activity(
                category=request.form.get("category"),
                description=request.form.get("description"),
                trip_id=trip_id)
            db.session.add(new_activity)
            db.session.commit()
            flash('You have successfully added an activity to this trip.')
            print "Trip activity has been committed to db", new_activity

    return redirect("/user/" + str(trip_id))
Esempio n. 42
0
    def get(self):
        stats = Stats()

        stats.nr_of_users = 0
        stats.nr_of_active_users = 0
        stats.nr_of_playlists = len([i for i in Playlist.all()])
        stats.nr_of_users_with_flattr_account = 0
        stats.nr_of_flattrs = len([i for i in Activity.all().filter('type =', 'outgoing').filter('verb =', 'flattr')])
        stats.nr_of_playlist_subscriptions = 0
        stats.nr_of_follow_relations = len([i for i in FollowRelation.all()])

        for user in YoutifyUser.all():
            stats.nr_of_users += 1
            
            if user.flattr_user_name:
                stats.nr_of_users_with_flattr_account += 1

            if user.playlist_subscriptions:
                stats.nr_of_playlist_subscriptions += len(user.playlist_subscriptions)

            if user.last_login:
                delta = datetime.now() - user.last_login
                if delta.seconds < 3600 * 24 * 7:
                    stats.nr_of_active_users += 1
        
        pings = []
        last_ping = None
        for m in PingStats.all().order('-date').fetch(6*24*7):
            if last_ping is not None and last_ping.date.hour is not m.date.hour:
                pings.append({
                    'date': str(last_ping.date),
                    'pings': last_ping.pings
                })
                last_ping = m
            elif last_ping is None or m.pings > last_ping.pings:
                last_ping = m
            
        stats.pings = simplejson.dumps(pings)
        
        stats.put()
Esempio n. 43
0
 def modify(self, activity):
     val = self.request.get("value")
     activity.tags = Activity.parsetags(self.require("value")) if val else []
     return activity
Esempio n. 44
0
def create_signup_activity(youtify_user_model):
    target = simplejson.dumps({})
    actor = simplejson.dumps(get_youtify_user_struct(youtify_user_model))

    m = Activity(owner=youtify_user_model, verb='signup', actor=actor, target=target, type='outgoing')
    m.put()
Esempio n. 45
0
 def json(self):
     result = self.modify(Activity.get(db.Key(self.require("key"))))
     if result:
         result.put()
         return {"activity":render("activity", activity=result)}
     return {}
Esempio n. 46
0
 def json(self):
     activity = Activity(name=self.require("name"), user=user(),
         tags=Activity.parsetags(self.request.get("tags", "")))
     activity.put()
     return {"activity":render("activity", activity=activity)}
Esempio n. 47
0
def activity(slug):
    act = Activity.objects(slug=slug).first()
    if not act:
        abort(404)
    app.logger.debug(act)
    return render_template("activity.html", act=act)
Esempio n. 48
0
def activities():
    today = datetime.datetime.combine(datetime.date.today(), datetime.time())
    acts = Activity.objects(starts_at__gte=today)
    app.logger.debug(acts)
    return render_template("activities.html", acts=acts)