예제 #1
0
def get_twitter_today_detail() -> HTTPResponse:
    user = request.get_cookie("user_id")  # , secret=PASSWORD)
    q = request.params.q
    *_, err = get_validation(request)
    if err:
        return err.response
    if user is None:
        return Error(400, "parameter `user` is required").response()
    twitter, err = fetch_twitter_info(user)
    if err:
        return err.response
    oauth = OAuth1Session(CK, CS, twitter["access_token"], twitter["access_secret"])
    res, new_tweets = get_new_tweets(oauth, twitter["latest_id"])
    if res.status_code == 401 and res.json()["errors"][0]["code"] == 89:
        return Error(401, "The registered token is invalid. It may have expired. Please re-login.").response
    elif res.status_code != 200:
        return json_response(res.status_code, res.json())
    body = update_tweets(user, new_tweets)
    hashtags = list(set(hstg for tw in body for hstg in tw["hashtags"]))
    detail = {
        "event": [],
        "morning": [],
        "breakfast": [],
        "lunch": [],
        "dinner": [],
        "night": []
    }
    for h in sorted(hashtags):
        detail[h] = []
    detail["other"] = []
    used = set()
    for idx, tw in enumerate(body):
        if sum([t in tw["text"] for t in MORNING]) > 0:
            detail["morning"].append(tw)
            used.add(idx)
        if sum([t in tw["text"] for t in NIGHT]) > 0:
            detail["night"].append(tw)
            used.add(idx)
        if sum([t in tw["text"] for t in BREAKFAST]) > 0:
            detail["breakfast"].append(tw)
            used.add(idx)
        if sum([t in tw["text"] for t in LUNCH]) > 0:
            detail["lunch"].append(tw)
            used.add(idx)
        if sum([t in tw["text"] for t in DINNER]) > 0:
            detail["dinner"].append(tw)
            used.add(idx)
        if len(tw["hashtags"]) > 0:
            for hs in tw["hashtags"]:
                detail[hs].append(tw)
                used.add(idx)
        if idx not in used:
            detail["other"].append(tw)
    if q != "":
        detail = detail.get(q, {})
    return json_response(200, detail)
예제 #2
0
def get_events_today() -> HTTPResponse:
    user = request.get_cookie("user_id", secret=PASSWORD)
    if user is None:
        return Error(400, "parameter `user` is required").response
    token, err = fetch_google_token(user)
    if err:
        return err.response
    if float(token.get("expires_at")) < datetime.now().timestamp():
        token, err = refresh_token_flow(user, token.get("refresh_token"))
        if err:
            return err.response
    today = datetime.now(timezone("Asia/Tokyo")).date()
    params = {
        "orderBy":
        "startTime",
        "singleEvents":
        True,
        "timeMin":
        datetime(today.year, today.month, today.day, 0, 0, 0, 0,
                 timezone("Asia/Tokyo")).isoformat(),
        "timeMax":
        datetime(today.year, today.month, today.day + 1, 0, 0, 0, 0,
                 timezone("Asia/Tokyo")).isoformat()
    }
    header = {"Authorization": f"Bearer {token['access_token']}"}
    req = requests.get(CALENDAR_EP + token["id"] + "/events",
                       params=params,
                       headers=header)
    if req.status_code != 200:
        return json_response(req.status_code, req.json())
    result = req.json().get("items")
    body = []
    for item in result:
        location = item.get("location")
        body.append({
            "title":
            item.get("summary"),
            "start":
            datetime_object(item.get("start", {}).get("dateTime")),
            "end":
            datetime_object(item.get("end", {}).get("dateTime")),
            "location": {
                "name": location
            },
            "link":
            item.get("htmlLink"),
        })
        if location is not None:
            map_info, err = get_map(location)
            if err is None:
                body[-1]["location"]["photo"] = map_info["photo_url"]
                body[-1]["location"]["latitude"] = map_info["latitude"]
                body[-1]["location"]["longitude"] = map_info["longitude"]
    return json_response(200, body)
예제 #3
0
def get_weather(lat: int = None, lng: int = None) -> HTTPResponse:
    if lat is None or lng is None:
        lat, lng, err = get_validation(request, "lat", "lng")
        if err:
            return err.response
    if not float_check(lat, 90):
        return Error(400,
                     "lat must be a real number between -90 and 90").response
    if not float_check(lng, 180):
        return Error(400,
                     "lng must be a real number between -180 and 180").response
    weather_get_url = f"http://api.openweathermap.org/data/2.5/weather?APPID={WEATHER_API_KEY}&lat={lat}&lon={lng}"
    req = requests.get(weather_get_url)
    if req.status_code != 200:
        return Error(req.status_code, req.json()).response
    body = req.json()

    weather_id = body['weather'][0]['id']
    weather = WEATHER_TABLE.get(weather_id)
    return json_response(
        200, {
            "weather": weather["main_ja"],
            "icon_url":
            f"http://openweathermap.org/img/wn/{weather['icon']}@2x.png",
            "temp": int(body["main"]["temp"] - 273.15),
            "humid": body["main"]["humidity"]
        })
예제 #4
0
def get_map(q: str = None) -> HTTPResponse:
    *_, err = get_validation(request)
    if err:
        return err.response
    if q is None:
        q = request.params.q
    if q == "":
        return Error(400, "parameter `q` is required.").response
    client = googlemaps.Client(key=MAP_API_KEY)
    req = client.places(q)
    if req['status'] != 'OK':
        return Error(400,
                     f"Google Maps API returns `{req['status']}`").response
    if len(req["results"]) != 1:
        return Error(
            500,
            f"Invalid number of result ({len(req['results'])}) are returned."
        ).response
    result = req["results"][0]
    body = {}
    photos = result.get("photos")
    if photos:
        body["photo_url"] = (
            f"https://maps.googleapis.com/maps/api/place/photo"
            f"?maxwidth={PHOTO_WIDTH}"
            f"&photoreference={photos[0]['photo_reference']}"
            f"&key={MAP_API_KEY}")
    body["latitude"] = result["geometry"]["location"]["lat"]
    body["longitude"] = result["geometry"]["location"]["lng"]
    return json_response(200, body)
예제 #5
0
def post_sign_up() -> HTTPResponse:
    user, err = post_validation(request, "name", "google", "twitter")
    if err:
        return err.response
    user, err = sign_up(user.get("name"), user.get("google"), user.get("twitter"))
    if err:
        return err.response
    return json_response(200, user, user["user_id"])
예제 #6
0
def get_twitter_today() -> HTTPResponse:
    user = request.get_cookie("user_id")  # , secret=PASSWORD)
    q = request.params.q
    *_, err = get_validation(request)
    if err:
        return err.response
    if user is None:
        return Error(400, "parameter `user` is required").response
    twitter, err = fetch_twitter_info(user)
    if err:
        return err.response
    oauth = OAuth1Session(CK, CS, twitter["access_token"], twitter["access_secret"])
    res, new_tweets = get_new_tweets(oauth, twitter["latest_id"])
    if res.status_code == 401 and res.json()["errors"][0]["code"] == 89:
        return Error(401, "The registered token is invalid. It may have expired. Please re-login.").response
    elif res.status_code != 200:
        return json_response(res.status_code, res.json())
    body = update_tweets(user, new_tweets)
    if q is not None:
        body = [b for b in body if q in b["text"]]
    return json_response(200, body)
예제 #7
0
def twitter_oauth_callback():
    oauth_session = OAuth1Session(CK, CS)
    oauth_session.parse_authorization_response(request.url)
    token = oauth_session.fetch_access_token(ACCESS_TOKEN_EP)
    oauth = OAuth1Session(CK, CS, token["oauth_token"], token["oauth_token_secret"])
    req = oauth.get(VERIFY_EP)
    if req.status_code != 200:
        return json_response(req.status_code, req.json())
    twitter = req.json()
    user, err = link_twitter_account(twitter["id_str"],
                                     twitter["screen_name"],
                                     token["oauth_token"],
                                     token["oauth_token_secret"])
    if err:
        return redirect(f"{ERROR_URL}?code={err.code}&message={err.message}")
    # if user["google_id"] is None:
    #     return redirect("https://hacku-techlion.herokuapp.com/twitter/login")
    return template(SUCCESS_URL)
예제 #8
0
def google_oauth_callback():
    oauth = OAuth2Session(client_id=CLIENT_ID, redirect_uri=REDIRECT_URL)
    token = oauth.fetch_token(token_url=TOKEN_URI,
                              authorization_response=request.url,
                              client_secret=CLIENT_SECRET)
    req = oauth.get(
        VERIFY_EP,
        headers={"Authorization": f"Bearer {token['access_token']}"})
    if req.status_code != 200:
        return json_response(req.status_code, req.json())
    google = req.json()
    user, err = link_google_account(google["email"], token["access_token"],
                                    token.get("refresh_token"),
                                    token["expires_at"])
    if err:
        return redirect(f"{ERROR_URL}?code={err.code}&message={err.message}")
    # if user["twitter_id"] is None:
    #     return redirect("https://hacku-techlion.herokuapp.com/twitter/login")
    return template(SUCCESS_URL)
예제 #9
0
def post_login() -> HTTPResponse:
    *_, err = post_validation(request)
    if err:
        return err.response
    body = request.json
    google = body.get("google")
    if google:
        user, err = fetch_user_info(google, "google")
        if err:
            return err.response
    else:
        twitter = body.get("twitter")
        if twitter is not None:
            user, err = fetch_user_info(twitter, "twitter")
            if err:
                return err.response
        else:
            return Error(400, "Either google or twitter is required.").response
    return json_response(200, user, user["user_id"])