Exemple #1
0
def new_links(request, id):
    trip = shortcuts.get_object_or_404(models.Trip, id=id, user=request.user)

    assert trip.visibility == models.Visibility.PUBLIC

    users = models.User.objects.filter(id__in=[int(id) for id in set(request.POST['user_ids'].split(","))])
    friends = list(trip.user.get_friends())
    users = [u for u in users if utils.find(friends, lambda f: f == u)] # filter out non-friends
    notifications = list(models.Notification.objects.filter(user__in=users, type=models.NotificationType.TRIP_LINK_REQUEST))
    for r in trip.triplink_lhs_set.all(): # filter out already linked or invited
        if r.rhs:
            if r.rhs.user in users:
                users.remove(r.rhs.user)
        else:
            notification = utils.find(notifications, lambda n: int(n.content) == r.id)
            if notification:
                users.remove(notification.user)
    for r in trip.triplink_rhs_set.all(): # filter out already linked reverse
        if r.lhs.user in users:
            users.remove(r.lhs.user)

    if not users:
        return http.HttpResponse()

    for user in users:
        link = models.TripLink(lhs=trip, status=models.RelationshipStatus.PENDING)
        link.save()
        notification = models.Notification(user=user, type=models.NotificationType.TRIP_LINK_REQUEST)
        notification.content = str(link.id)
        notification.save()
        notification.manager.send_email()

    return http.HttpResponse()
Exemple #2
0
def flickr_photos_getInfo(photo_id):
    dom = call('flickr.photos.getInfo', photo_id=photo_id)
    try:
        return [{'title': node.getElementsByTagName('title')[0].childNodes[0].nodeValue,
                 'date': datetime.strptime(node.getElementsByTagName('dates')[0].getAttribute('taken'), "%Y-%m-%d %H:%M:%S"),
                 'url': utils.find(node.getElementsByTagName('url'), lambda n: n.getAttribute('type') == 'photopage').childNodes[0].nodeValue}
                for node in dom.getElementsByTagName('photo')][0]
    except IndexError:
        return None
Exemple #3
0
 def copy(self, user):
     new_trip = Trip(user=user, name=self.name, start_date=self.start_date, end_date=self.end_date, visibility=Visibility.PUBLIC)
     new_trip.save()
     transportations = list(self.annotation_set.filter(content_type=ContentType.TRANSPORTATION))
     for p in self.point_set.all():
         new_point = Point(trip=new_trip, place=p.place, name=p.name, coords=p.coords,
                           date_arrived=p.date_arrived, date_left=p.date_left, visited=p.visited, order_rank=p.order_rank)
         new_point.save()
         transportation = Annotation(trip=new_trip, point=new_point, segment=True, title="", content_type=ContentType.TRANSPORTATION, visibility=Visibility.PUBLIC)
         transportation.content = utils.find(transportations, lambda t: t.point == p).content
         transportation.save()
     return new_trip
Exemple #4
0
def points_POST(request, id):
    trip = shortcuts.get_object_or_404(models.Trip, id=id)
    points = list(trip.point_set.all())
    new_points = [dict([npi.split("=") for npi in np.split(",")])
                  for np in request.POST['points'].split(";") if np]

    for point in points:
        if not utils.find(new_points, lambda p: p['id'] == "oldpoint_%s" % point.id):
            point.delete()

    for i in range(len(new_points)):
        new_point = new_points[i]
        op, id = points_re.match(new_point['id']).groups()
        id = int(id)
        if op == 'old':
            point = utils.find(points, lambda p: p.id == id)
            modified = False
            if point.order_rank != i:
                point.order_rank = i
                modified = True
            if len(new_point) != 1: # this point was edited
                point.date_arrived = utils.parse_date(new_point['date_arrived'])
                point.date_left = utils.parse_date(new_point['date_left'])
                point.visited = bool(int(new_point['visited']))
                modified = True
            if modified:
                point.save()
        elif op == 'new':
            place_id = int(id)
            place = models.Place.objects.get(id=place_id)
            point = models.Point(trip=trip, place=place, name=place.name, coords=place.coords)
            point.date_arrived = utils.parse_date(new_point['date_arrived'])
            point.date_left = utils.parse_date(new_point['date_left'])
            point.visited = bool(int(new_point['visited']))
            point.order_rank = i
            point.save()
            transportation = models.Annotation(trip=trip, point=point, segment=True, title="", content_type=models.ContentType.TRANSPORTATION)
            transportation.content = request.POST.get('default_transportation') or "0"
            transportation.save()
    return http.HttpResponse()
Exemple #5
0
    def run(self):
        user_id = int(self.task.parameters)
        max_id = self.task.state

        while True:
            limit = twitter.rate_limit()
            if limit:
                break
            time.sleep(5)

        user = models.User.objects.get(id=user_id)
        trips = list(user.trip_set.all())

        if not trips:
            self.finish()
            return

        page = 1
        while limit:
            tweets = twitter.user_timeline(user.userprofile.twitter_username, page=page, max_id=max_id)
            if not tweets:
                self.finish()
                return
            for tweet in tweets:
                date = tweet["created_at"]
                if date.date() < trips[-1].start_date:
                    self.finish()
                    return
                trip = utils.find(trips, lambda t: t.start_date <= date.date() <= t.end_date)
                if trip:
                    if (
                        models.Annotation.objects.filter(
                            content_type=models.ContentType.TWEET, external_id=str(tweet["id"])
                        ).count()
                        == 0
                    ):
                        annotation = models.Annotation(
                            trip=trip, date=tweet["created_at"], title="", content_type=models.ContentType.TWEET
                        )
                        annotation.external_id = str(tweet["id"])
                        annotation.content = annotation.manager.clean_content(tweet["text"])
                        annotation.save()
            self.save_state(tweets[-1]["id"])
            limit -= 1
            page += 1
            time.sleep(1)
Exemple #6
0
def stats(request, username):
    user = models.User.objects.get(username=username)
    trips = list(user.trip_set.all())
    points = list(models.Point.objects.filter(trip__user=user).select_related('trip').select_related('place').select_related('place__country'))
    transportations = dict((t.point_id, int(t.content)) for t in models.Annotation.objects.filter(trip__user=user, content_type=models.ContentType.TRANSPORTATION))

    stats = {None: {}}

    def add_stat(year, stat, value, init):
        if not isinstance(year, int) and year is not None:
            for year in year:
                add_stat(year, stat, value, init)
        else:
            if not year in stats:
                stats[year] = {}
            if not stat in stats[year]:
                stats[year][stat] = init
            if isinstance(init, list):
                stats[year][stat].append(value)
            elif isinstance(init, set):
                stats[year][stat].add(value)
            else:
                stats[year][stat] += value

    for trip in trips:
        add_stat(range(trip.start_date.year, trip.end_date.year + 1), 'trip_count', 1, 0)
	add_stat(None, 'trip_count', 1, 0)

    extreme_N, extreme_S, extreme_E, extreme_W = None, None, None, None
    for point in points:
        if point.visited:
            year_arrived = point.date_arrived.date().year if point.date_arrived else point.trip.start_date.year
            add_stat(year_arrived, 'places', point.place, set())
	    add_stat(None, 'places', point.place, set())
            add_stat(year_arrived, 'countries', point.place.country, set())
	    add_stat(None, 'countries', point.place.country, set())
            if extreme_N is None or point.coords.coords[0] > extreme_N.coords.coords[0]:
                extreme_N = point.place
            if extreme_S is None or point.coords.coords[0] < extreme_S.coords.coords[0]:
                extreme_S = point.place
            if extreme_E is None or point.coords.coords[1] > extreme_E.coords.coords[1]:
                extreme_E = point.place
            if extreme_W is None or point.coords.coords[1] < extreme_W.coords.coords[1]:
                extreme_W = point.place
        next_point = utils.find(points, lambda p: p.trip_id == point.trip_id and p.order_rank > point.order_rank)
        if next_point:
            dist = distance(point.coords, next_point.coords).km
            year_left = point.date_left.date().year if point.date_left else point.trip.start_date.year
            transportation = annotationtypes.Transportation.Means.get_name(transportations[point.id])
            add_stat(year_left, 'distance', dist, 0)
	    add_stat(None, 'distance', dist, 0)
            add_stat(year_left, 'distance_' + transportation, dist, 0)
	    add_stat(None, 'distance_' + transportation, dist, 0)

    for year_stats in stats.values():
        year_stats['places'] = sorted(year_stats.get('places', []))
        year_stats['countries'] = sorted(year_stats.get('countries', []))

    stats[None]['extreme_places'] = {'N': extreme_N, 'S': extreme_S, 'E': extreme_E, 'W': extreme_W}

    return views.render("user_stats.html", request, {'for_user': user,
                                                     'years': [None] + list(sorted(set(stats.keys()) - set([None]), reverse=True)),
                                                     'stats': stats.items()})