from setup import *


class authentication():
    def __init__(self, path_cookies='', username='', password=''):
        self._path_cookies = path_cookies
        self._username = username
        self._password = password
        self._headers = HEADERS
        self.session = session

    def auth_with_cookies(self):
        file = open(self._path_cookies, 'r', encoding='utf-8')
        cookies = {}
        out = ''
        for line in file:
            line = line.strip()
            if '#' not in line:
                item = re.findall(r'[0-9]\s(.*)', line)
                if item:
                    item = item[0].split('\t')
                    if len(item) == 1:
                        cookies[item[0]] = ''
                        out += "%s=''; " % item[0]
                    else:
                        cookies[item[0]] = item[1]
        self.session.cookies.update(cookies)
        res = self.session.get(url='https://www.fshare.vn/account/profile', headers={
            'user-agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/85.0.134 Chrome/79.0.3945.134 Safari/537.36",
            "sec-fetch-site": "same-origin",
            'sec-fetch-mode': "navigate",
            'referer': "https://www.fshare.vn/file/manager",
            'sec-fetch-user': '?1'
        })
        if 'login' in res.url:
            sys.stdout.write(
                fc + sd + "\n[" + fr + sb + "-" + fc + sd + "] : " + fr + sd + "Cookies die, pls try again.\n")
            sys.exit(0)
            return False
        return True


class extractFshare():
    def __init__(self, link):
        self._url = link
        self._headers = HEADERS
        self._regex_url = "(?x)^((http[s]?|fpt):)\/?\/(www\.|m\.|)fshare\.vn\/(file)\/(?P<id>.*?)(\W|$)"
        self._api = "https://www.fshare.vn/download/get"
        self.session = session

    def run(self):
        mobj = re.match(self._regex_url, self._url)
        if not mobj:
            return "Invalid url"
        fshare_id = mobj.group('id')
        self._headers.update({
            'upgrade-insecure-requests': '1',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
        })
        res = self.session.get(url=self._url, headers=self._headers)
        content = res.text
        soup = get_soup(content, 'html5lib')
        tag_input = soup.findAll('input', attrs={'type': "hidden"})
        acstk, csrf_token, withFcode5 = [None] * 3
        for input in tag_input:
            if input.get('id') == 'acstk':
                acstk = input.get('data-value')
            elif input.get('name') == '_csrf-app':
                csrf_token = input.get('value')
            elif input.get('name') == 'withFcode5':
                withFcode5 = input.get('value')
        if not csrf_token or not acstk:
            return "Can not extract data of file."
        session.cookies.update({
            'fshare-app': acstk
        })
        self._headers = HEADERS.update({
            "x-csrf-token":csrf_token,
            'x-requested-with':"XMLHttpRequest",
            'sec-fetch-site':"same-origin",
            "sec-fetch-mode":"cors",
            'referer':self._url,
            'origin':"https://www.fshare.vn"
        })
        info = session.post(url=self._api, headers=self._headers, data={
            '_csrf-app': csrf_token,
            'linkcode': fshare_id,
            'withFcode5': withFcode5
        })
        return merge_dicts(info.json(),info.headers)


def main(argv):
    parser = argparse.ArgumentParser(description='Getlink fshare.')
    parser.add_argument('url', type=str, help='Url.')

    authen = parser.add_argument_group('Authentication')
    authen.add_argument('-c', '--cookies', dest='path_cookies', type=str, help='Cookies for authenticate with.',
                        metavar='')

    opts = parser.add_argument_group("Options")
    opts.add_argument('-j', '--json', default=False, action='store_true', help="Show json of info .",
                      dest='show_json_info')

    args = parser.parse_args()
    status_auth = False
    if args.path_cookies:
        auth = authentication(path_cookies=args.path_cookies)
        status_auth = auth.auth_with_cookies()
        if status_auth:
            sys.stdout.write(fg + '[' + fc + '*' + fg + '] : Login oki.\n')
        else:
            sys.stdout.write(fg + '[' + fc + '*' + fg + '] : Login false.\n')
    auth = authentication(path_cookies='cookies.txt')
    auth.auth_with_cookies()

    extract = extractFshare(link=args.url)
    print(json.dumps(extract.run(),indent=4,ensure_ascii=False))


if __name__ == '__main__':
    try:
        if sys.stdin.isatty():
            main(sys.argv)
        else:
            argv = sys.stdin.read().split(' ')
            main(argv)
    except KeyboardInterrupt:
        sys.stdout.write(
            fc + sd + "\n[" + fr + sb + "-" + fc + sd + "] : " + fr + sd + "User Interrupted..\n")
        sys.exit(0)