# Path: mod/_config.py

# 
# Path: mod/models/card_cache.py
# class CardCache(Base):
#     __tablename__ = 'card'
#     cardnum = Column(BIGINT, primary_key=True)
#     text = Column(LONGTEXT)
#     date = Column(Integer, nullable=False)
# 
# Path: mod/auth/handler.py
# def authApi(username,password):
#     data = {
#             'username':username,
#             'password':password
#         }
#     result = {'code':200,'content':''}
#     try:
#         client = HTTPClient()
#         request = HTTPRequest(
#             CHECK_URL,
#             method='POST',
#             body=urllib.urlencode(data),
#             validate_cert=False,
#             request_timeout=TIME_OUT)
#         response = client.fetch(request)
#         header = response.headers
#         if 'Ssocookie' in header.keys():
#             headertemp = json.loads(header['Ssocookie'])
#             cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
#             cookie += ";"+header['Set-Cookie'].split(";")[0]
#             result['content'] = cookie
#         else:
#             result['code'] = 400
#     except HTTPError as e:
#         if e.code == 401:
#           result['code'] = 401
#         else:
#           result['code'] = 500
#     except Exception,e:
#         result['code'] = 500
#     return result


from .._config import cardCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import IPython
                response = yield tornado.gen.Task(client.fetch, request)
                cookie += ';' + response.headers['Set-Cookie'].split(';')[0]
                request = HTTPRequest(
                    USERID_URL,
                    method='GET',
                    headers={'Cookie':cookie},
                    request_timeout=TIME_OUT)
                response = yield tornado.gen.Task(client.fetch, request)

                soup = BeautifulSoup(response.body)
                td = soup.findAll('td',{"class": "neiwen"})
                userid = td[3].text
                cardState = td[42].text
                cardLetf = td[46].text.encode('utf-8').split('元')[0]
                # do not need to get the detail
                if timedelta == 0:
                    retjson['content'] = {'state':cardState, 'left': cardLetf, 'cardLeft':cardLetf}
                    ret = json.dumps(retjson, ensure_ascii=False, indent=2)
                    self.write(retjson)
                    self.finish()

                    # refresh cache
                    if retjson['code'] == 200:
                        status.date = int(time())
                        status.text = base64.b64encode(ret)
                        self.db.add(status)
                        try:
                            self.db.commit()
                        except:
                            self.db.rollback()

# Path: mod/_config.py

# 
# Path: mod/models/card_cache.py
# class CardCache(Base):
#     __tablename__ = 'card'
#     cardnum = Column(BIGINT, primary_key=True)
#     text = Column(LONGTEXT)
#     date = Column(Integer, nullable=False)
# 
# Path: mod/auth/handler.py
# def authApi(username,password):
#     data = {
#             'username':username,
#             'password':password
#         }
#     result = {'code':200,'content':''}
#     try:
#         client = HTTPClient()
#         request = HTTPRequest(
#             CHECK_URL,
#             method='POST',
#             body=urllib.urlencode(data),
#             validate_cert=False,
#             request_timeout=TIME_OUT)
#         response = client.fetch(request)
#         header = response.headers
#         if 'Ssocookie' in header.keys():
#             headertemp = json.loads(header['Ssocookie'])
#             cookie = headertemp[0]['cookieName']+"="+headertemp[0]['cookieValue']
#             cookie += ";"+header['Set-Cookie'].split(";")[0]
#             result['content'] = cookie
#         else:
#             result['code'] = 400
#     except HTTPError as e:
#         if e.code == 401:
#           result['code'] = 401
#         else:
#           result['code'] = 500
#     except Exception,e:
#         result['code'] = 500
#     return result


# Path: mod/card/handler.py
from .._config import cardCacheTime
from config import *
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from BeautifulSoup import BeautifulSoup
from ..models.card_cache import CardCache
from sqlalchemy.orm.exc import NoResultFound
from time import time
from ..auth.handler import authApi
import tornado.web
import tornado.gen
import urllib, re
import json, base64
import datetime
import traceback
import IPython

                response = yield tornado.gen.Task(client.fetch, request)
                cookie += ';' + response.headers['Set-Cookie'].split(';')[0]
                request = HTTPRequest(
                    USERID_URL,
                    method='GET',
                    headers={'Cookie':cookie},
                    request_timeout=TIME_OUT)
                response = yield tornado.gen.Task(client.fetch, request)

                soup = BeautifulSoup(response.body)
                td = soup.findAll('td',{"class": "neiwen"})
                userid = td[3].text
                cardState = td[42].text
                cardLetf = td[46].text.encode('utf-8').split('元')[0]
                # do not need to get the detail
                if timedelta == 0:
                    retjson['content'] = {'state':cardState, 'left': cardLetf, 'cardLeft':cardLetf}
                    ret = json.dumps(retjson, ensure_ascii=False, indent=2)
                    self.write(retjson)
                    self.finish()

                    # refresh cache
                    if retjson['code'] == 200:
                        status.date = int(time())
                        status.text = base64.b64encode(ret)
                        self.db.add(status)
                        try:
                            self.db.commit()
                        except:
                            self.db.rollback()

                        finally: