def __init__(self):
        current_subject = Subject().get_current()
        if current_subject is None:
            logging.error("Cannot find current subject!!!")

        now = datetime.datetime.now()
        if now <= current_subject.active_to:
            return

        # invalidate currect subject
        current_subject.is_current = False

        # new subject to pick
        new_subject = (
            Subject.all().filter("active_from =", datetime.datetime(now.year, now.month, now.day, 0, 0, 0)).get()
        )
        if new_subject is None:
            logging.error("Cannot find next subject!!!")
        new_subject.is_current = True

        s = SaveState().get_by_k("recalc_subject_id")
        if s is not None and s.v != "0":
            logging.error(
                "Cannot start recalculating new subject (%s), because old one (%s) is still active!!!"
                % (new_subject.key().id(), current_subject.key().id())
            )
            return

        # ready to go!
        current_subject.put()
        new_subject.put()

        s = SaveState().get_by_k("recalc_subject_id")
        if s is None:
            s = SaveState()
            s.k = "recalc_subject_id"
            s.v = str(current_subject.key().id())
            s.put()
        else:
            s.v = str(current_subject.key().id())
            s.put()

        s = SaveState().get_by_k("recalc_action")
        if s is None:
            s = SaveState()
            s.k = "recalc_action"
            s.v = "points"
            s.put()
        else:
            s.v = "points"
            s.put()
    def get(self, username):
        subjects = []

        current_subject = SubjectModel().get_current()
        current_best_photo = (
            Photo.all()
            .filter("user ="******"subject_id =", current_subject.key().id())
            .filter("is_active =", True)
            .filter("is_user_active =", True)
            .filter("is_blocked =", False)
            .order("-total_score")
            .get()
        )
        if current_best_photo:
            current_best_photo = current_best_photo.to_dict()

        subjects.append({"subject": current_subject.to_dict(), "best_photo": current_best_photo, "points": 0})
        for us in UserSubject().get_by_user(username):
            subjects.append(us.to_dict())

        self.response.out.write(json.dumps({"subjects": subjects}))
    def get(self):
        subject = SubjectModel().get_current()

        photos = (
            Photo.all()
            .filter("user ="******"subject_id =", subject.key().id())
            .filter("is_active =", True)
            .order("date_instagram")
        )

        blocked = []
        fetched_ids = []
        ps = {"active": [], "inactive": []}
        for p in photos:
            fetched_ids.append(p.instagram_id)

            if p.is_blocked:
                continue
            if p.is_active and p.is_user_active:
                ps["active"].append(p.to_dict())
            else:
                ps["inactive"].append(p.to_dict())

        # get latest photos from instagram
        url = (
            "https://api.instagram.com/v1/users/%s/media/recent/?access_token=%s&min_timestamp=%s&max_timestamp=%s"
            % (
                self.user.instagram_id,
                self.user.access_token,
                int(time.mktime(subject.active_from.utctimetuple())),
                int(time.mktime(subject.active_to.utctimetuple())),
            )
        )

        f = urlfetch.fetch(url)
        try:
            data = json.loads(f.content)
        except urlfetch.DownloadError:
            return self.response.out.write(json.dumps({"photos": ps}))

        # TODO: pagination

        if not data.has_key("data"):
            logging.error("No data in fetched url: %s" % url)
            return self.response.out.write(json.dumps({"photos": ps}))

        for photo in data["data"]:
            if photo["id"] in fetched_ids:
                continue
            d = datetime.datetime.fromtimestamp(float(photo["created_time"]))
            if d < subject.active_from or d > subject.active_to:
                continue
            # logging.info('%s < %s > %s' % (str(d), str(subject.active_from), str(subject.active_to)))

            p = Photo().to_dict(photo)
            if p["active"] and ["user_active"]:
                Photo().add_or_update(photo)
                ps["active"].append(p)
            else:
                ps["inactive"].append(p)

        self.response.out.write(json.dumps({"photos": ps}))