from html2text import html2text
import requests
import json
from flask import jsonify, Blueprint, request
from namecoin.namecoind_api import error_reply
from namecoin.namecoind_wrapper import get_full_profile

from config import MEMCACHED_ENABLED, MEMCACHED_PORT, MEMCACHED_TIMEOUT, DEFAULT_HOST
from config import MONGODB_URI

import pylibmc
from time import time
mc = pylibmc.Client([DEFAULT_HOST + ':' + MEMCACHED_PORT],binary=True)

checker_api = Blueprint('checker_api', __name__)

import hashlib 

#-----------------------------------
from pymongo import MongoClient

remote_client = MongoClient(MONGODB_URI)
remote_db = remote_client.get_default_database()
users = remote_db.user

#-----------------------------------------
def is_valid_proof(key, value, username, proof_url):

    #check if username is actually on that service (and not some other user)
    if "username" in value:
        site_username = value["username"].lower()
        if site_username not in proof_url.lower():
            return False
    try:
        r = requests.get(proof_url)
    except:
        return False

    search_text = html2text(r.text)
    if key == "twitter":    
        search_text = search_text.replace("<s>", "").replace("</s>", "").replace("**", "")
    elif key == "github":
        pass
    elif key == "facebook":
        pass
    search_text = search_text.lower()

    if "verifymyonename" in search_text and ("+" + username) in search_text:
        return True
    elif "verifying myself" in search_text and "bitcoin username" in search_text and ("+" + username) in search_text:
        return True
    elif "verifying myself" in search_text and "bitcoin username" in search_text and username in search_text:
        return True
 
    return False

#-----------------------------------------
def get_proof_url(proof, username):

    proof_url = None
    if "url" in proof:
        proof_url = proof["url"]
    elif "id" in proof:
        if key == "twitter":
            proof_url = "https://twitter.com/" + username + "/status/" + proof["id"]
        elif key == "github":
            proof_url = "https://gist.github.com/" + username + "/" + proof["id"]
        elif key == "facebook":
            proof_url = "https://www.facebook.com/" + username + "/posts/" + proof["id"]
    return proof_url

#-----------------------------------------
@checker_api.route('/checker/get_verifications')
def get_verifications():

    verifications = {}
    proof_sites = ["twitter", "github", "facebook"]

    username = request.args.get('username')

    try:
        refresh = int(request.args.get('refresh'))
    except:
        refresh = 0 

    if refresh == 1:
        USE_CACHE = False
    else:
        USE_CACHE = MEMCACHED_ENABLED

    if username is None:
        return error_reply("username not given")

    try: 
        user = users.find_one({"username":username})
        profile = user["profile"]
    except Exception as e:
        profile = get_full_profile('u/' + username)
 
    for key, value in profile.items():
        if key in proof_sites and type(value) is dict and "proof" in value:
        
            try:
                proof_username = value['username'].lower()
                proof_url = get_proof_url(value["proof"], proof_username)
                proof_url_hash = hashlib.md5(proof_url).hexdigest()

            except Exception as e:
                continue 

            if USE_CACHE: 
                cache_reply = mc.get("proof_" + proof_url_hash)
            else:
                cache_reply = None 
                #print "cache off"

            if cache_reply is None: 
              
                if is_valid_proof(key, value, username, proof_url):

                    verifications[key] = True
    
                    if USE_CACHE:
                        mc.set("proof_" + proof_url_hash,username,int(time() + MEMCACHED_TIMEOUT))
                        #print "cache miss"
            else:
                #print "cache hit"
                if cache_reply == username:
                    verifications[key] = True

    return jsonify(verifications)
@@ -681,16 +681,192 @@
 b.user%0A%0A
+#-----------------------------------------%0Adef get_json(data):%0A%0A    if isinstance(data,dict):%0A        pass %0A    else:%0A        data = json.loads(data)%0A        %0A    return data%0A%0A
 #-------
@@ -949,24 +949,24 @@
 proof_url):%0A
-
 %0A    #check 
@@ -1181,24 +1181,204 @@
 eturn False%0A
+%0A        if key == %22twitter%22 and %22twitter.com%22 not in proof_url:%0A            return False%0A        elif key == %22github%22 and %22github.com%22 not in proof_url:%0A            return False%0A%0A
     try:%0A   
@@ -1647,44 +1647,8 @@
     
-elif key == %22facebook%22:%0A        pass
 %0A   
@@ -3203,16 +3203,25 @@
 ofile = 
+get_json(
 user%5B%22pr
@@ -3227,16 +3227,18 @@
 rofile%22%5D
+)%0A
 %0A    exc
@@ -3309,18 +3309,17 @@
 ername)%0A
- 
 %0A
+
     for 
@@ -3933,16 +3933,16 @@
  None: %0A
-
         
@@ -3940,32 +3940,91 @@
 %0A              %0A
+                proof_url = %22http://onename.io/ryaneshea%22%0A%0A
                 

fix for recursion bug, check if it's a twitter or github URL