|
#!/usr/bin/env python3 |
|
|
|
import json |
|
import datetime |
|
import sys |
|
import os |
|
|
|
def convert_json_to_netscape(json_data): |
|
netscape_cookies = [] |
|
|
|
for cookie in json_data: |
|
domain = cookie.get('domain', '') |
|
include_subdomain = 'TRUE' if cookie.get('includeSubdomain', False) else 'FALSE' |
|
path = cookie.get('path', '/') |
|
secure = 'TRUE' if cookie.get('secure', False) else 'FALSE' |
|
expiry = cookie.get('expiry', 0) |
|
name = cookie.get('name', '') |
|
value = cookie.get('value', '') |
|
|
|
# Convert expiry to Netscape format (epoch time) |
|
if isinstance(expiry, str): |
|
try: |
|
expiry_date = datetime.datetime.strptime(expiry, '%Y-%m-%dT%H:%M:%SZ') |
|
expiry = int(expiry_date.timestamp()) |
|
except ValueError: |
|
expiry = 0 |
|
|
|
netscape_cookie = f"{domain}\t{include_subdomain}\t{path}\t{secure}\t{expiry}\t{name}\t{value}" |
|
netscape_cookies.append(netscape_cookie) |
|
|
|
return netscape_cookies |
|
|
|
def prepend_netscape_header(file): |
|
header = ( |
|
"# Netscape HTTP Cookie File\n" |
|
"# http://curl.haxx.se/rfc/cookie_spec.html\n" |
|
"# This is a generated file! Do not edit.\n\n" |
|
) |
|
file.write(header) |
|
|
|
def main(): |
|
if len(sys.argv) < 2: |
|
print("Usage: cookies-converter.py <json_file> [-n|--netscape]") |
|
return |
|
|
|
json_file = sys.argv[1] |
|
add_netscape_header = '-n' in sys.argv or '--netscape' in sys.argv |
|
|
|
try: |
|
with open(json_file, 'r') as file: |
|
json_data = json.load(file) |
|
except FileNotFoundError: |
|
print(f"Error: File '{json_file}' not found.") |
|
return |
|
except json.JSONDecodeError: |
|
print(f"Error: File '{json_file}' is not a valid JSON file.") |
|
return |
|
|
|
netscape_cookies = convert_json_to_netscape(json_data) |
|
|
|
# Create the output file name |
|
base_name, _ = os.path.splitext(json_file) |
|
output_file = f"{base_name}-netscape.txt" |
|
|
|
try: |
|
with open(output_file, 'w') as file: |
|
if add_netscape_header: |
|
prepend_netscape_header(file) |
|
for cookie in netscape_cookies: |
|
file.write(cookie + '\n') |
|
print(f"Netscape cookies saved to '{output_file}'") |
|
except IOError as e: |
|
print(f"Error: Could not write to file '{output_file}'. {e}") |
|
|
|
if __name__ == "__main__": |
|
main() |