<commit_before>__author__ = 'vladimir'

import time
import datetime
import uuid
import json
import random

import requests
from flask import Blueprint, Response, request

from . import VKID_NAME
from .decorators import check_cookie
from .models import Person, PersonSubscriptions, DoesNotExist


security = Blueprint("security_module", __name__)


def generate_cookie():
    return "wmfe-{0}".format(uuid.uuid4())


def get_friend_list(user_id, auth_token):
    base_url = "https://api.vk.com/method/"
    endpoint = "friends.get"
    data = {
        "user_id": user_id,
        "auth_token": auth_token,
        "v": "5.37",
    }
    r = requests.get(base_url + endpoint, params=data)
    print "Got VK status-code={0}".format(r.status_code)
    return r.json()


"""
@api {post} /register_user Register & get auth cookie in responce
@apiGroup User
@apiName RegisterUser
@apiDescription Pass everything to register a new user before using the API
@apiVersion 0.1.0

@apiParam {String} vkid User VK id
@apiParam {String} auth_token VK-API auth token
@apiParam {String} recovery_code VK-API code to renew auth token when expires
"""
@security.route("/register_user", methods=["POST"])
def reg_user():
    vkid = request.form.get(VKID_NAME, None)
    r_code = request.form.get("recovery_code", None)
    auth_token = request.form.get("auth_token", None)
    if vkid and r_code and auth_token:
        new_cookie = generate_cookie()
        try:
            p = Person.get(Person.vkid == vkid)
            p.auth_cookie = new_cookie
            p.save()

            message = "Person with VKID {0} was already registered, use /renew_cookie to get new auth cookie"
            r = Response(response=json.dumps({
                "auth": new_cookie,
                "message": message,
            }), mimetype="application/json")
            r.set_cookie("auth", new_cookie, expires=time.time()+datetime.timedelta(days=1).total_seconds())
            r.status_code = 200
            return r
        except DoesNotExist:
            p = Person.create(vkid=vkid, recovery_code=r_code, auth_token=auth_token, auth_cookie=new_cookie)
            # follow all friends and add all to followers
            do_save = False
            friend_id_list = get_friend_list(user_id=vkid, auth_token=auth_token)
            print friend_id_list
            for flwr in friend_id_list["response"]["items"]:
                p_id = flwr["id"]
                try:
                    f = Person.get(Person.vkid == p_id)
                    f.following += 1
                    f.my_followers += 1
                    f.save()
                    PersonSubscriptions.get_or_create(owner=vkid, follower=p_id)
                    PersonSubscriptions.get_or_create(owner=p_id, follower=vkid)

                    p.following += 1
                    p.my_followers += 1
                    do_save = True
                except DoesNotExist:
                    print "Friend '{0}' doesn't exist".format(flwr)
                except Exception as e:
                    print "Problem parsing JSON: {0}\n{1}".format(e, flwr)
            if do_save:
                p.save()
            message = "Save 'auth' value, put in cookies, use in every request until it expires"
            r = Response(response=json.dumps({
                "auth": new_cookie,
                "message": message,
            }), mimetype="application/json")
            r.set_cookie("auth", new_cookie, expires=time.time()+datetime.timedelta(days=1).total_seconds())
            r.status_code = 200
            return r
        except Exception as e:
            message = "Internal error: {0}".format(repr(e))
    else:
        message = "POST parameters 'vkid', 'recovery_code', 'auth_token' are required"
    return json.dumps({"message": message})


"""
@api {post} /renew_cookie Set new cookie
@apiDescription Sets new cookie in responce. Call if 401
@apiGroup User<commit_msg>update friend list on every login<commit_after>__author__ = 'vladimir'

import time
import datetime
import uuid
import json
import random

import requests
from flask import Blueprint, Response, request

from . import VKID_NAME
from .decorators import check_cookie
from .models import Person, PersonSubscriptions, DoesNotExist


security = Blueprint("security_module", __name__)


def generate_cookie():
    return "wmfe-{0}".format(uuid.uuid4())


def get_friend_list(user_id, auth_token):
    base_url = "https://api.vk.com/method/"
    endpoint = "friends.get"
    data = {
        "user_id": user_id,
        "auth_token": auth_token,
        "v": "5.37",
    }
    r = requests.get(base_url + endpoint, params=data)
    print "Got VK status-code={0}".format(r.status_code)
    return r.json()


"""
@api {post} /register_user Register & get auth cookie in responce
@apiGroup User
@apiName RegisterUser
@apiDescription Pass everything to register a new user before using the API
@apiVersion 0.1.0

@apiParam {String} vkid User VK id
@apiParam {String} auth_token VK-API auth token
@apiParam {String} recovery_code VK-API code to renew auth token when expires
"""
@security.route("/register_user", methods=["POST"])
def reg_user():
    vkid = request.form.get(VKID_NAME, None)
    r_code = request.form.get("recovery_code", None)
    auth_token = request.form.get("auth_token", None)
    if vkid and r_code and auth_token:
        new_cookie = generate_cookie()
        p = Person.get_or_create(Person.vkid == vkid)
        p.auth_cookie = new_cookie
        p.save()

        message = "Person with VKID {0} was already registered, use /renew_cookie to get new auth cookie"
        r = Response(response=json.dumps({
            "auth": new_cookie,
            "message": message,
        }), mimetype="application/json")
        r.set_cookie("auth", new_cookie, expires=time.time()+datetime.timedelta(days=1).total_seconds())
        r.status_code = 200

        # update friend list
        do_save = False
        friend_id_list = get_friend_list(user_id=vkid, auth_token=auth_token)
        print friend_id_list
        for flwr in friend_id_list["response"]["items"]:
            p_id = flwr["id"]
            try:
                f = Person.get(Person.vkid == p_id)
                f.following += 1
                f.my_followers += 1
                f.save()
                PersonSubscriptions.get_or_create(owner=vkid, follower=p_id)
                PersonSubscriptions.get_or_create(owner=p_id, follower=vkid)

                p.following += 1
                p.my_followers += 1
                do_save = True
            except DoesNotExist:
                print "Friend '{0}' doesn't exist".format(flwr)
            except Exception as e:
                print "Problem parsing JSON: {0}\n{1}".format(e, flwr)
        if do_save:
            p.save()
    else:
        message = "POST parameters 'vkid', 'recovery_code', 'auth_token' are required"
    return json.dumps({"message": message})


"""
@api {post} /renew_cookie Set new cookie
@apiDescription Sets new cookie in responce. Call if 401
@apiGroup User
{'fraction_non_alphanumeric': 0.10604558969276512, 'fraction_numerical': 0.007503893529661617, 'mean_word_length': 2.4815179891572203, 'pattern_counts': {'":': 14, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1512299', 'n_tokens_mistral': 2221, 'n_tokens_neox': 2090, 'n_words': 559}