#!/usr/bin/env python3
"""Mega.nz Public-File-Download (nur filekey im Link)."""
import requests, json, base64, struct, sys, os
from Crypto.Cipher import AES
from Crypto.Util import Counter

def b64d(s):
    s += '=' * (-len(s) % 4)
    s = s.replace('-', '+').replace('_', '/')
    return base64.b64decode(s)

def decrypt_key(ek, sk):
    ctr = Counter.new(128, initial_value=0, little_endian=False)
    aes = AES.new(sk, AES.MODE_CTR, counter=ctr)
    return aes.decrypt(ek)

def decrypt_file(data, k, nonce):
    ctr = Counter.new(128, initial_value=int.from_bytes(nonce + b'\0'*4, 'big'), little_endian=False)
    aes = AES.new(k, AES.MODE_CTR, counter=ctr)
    return aes.decrypt(data)

def mega_download(url, out):
    # https://mega.nz/file/<id>#<key>
    frag = url.split('/file/')[1]
    fid, key = frag.split('#')
    k = b64d(key)
    if len(k) == 32:
        # composite key
        sk = k[:16]
        ek = k[16:]
        fk = decrypt_key(ek, sk)
    else:
        fk = k
    # API: get file info
    r = requests.post('https://g.api.mega.co.nz/cs', json=[{'a': 'g', 'p': fid, 'n': fid}], timeout=60)
    d = r.json()[0]
    print('size:', d.get('s'), 'at:', d.get('at'))
    if 'e' in d and d['e']:
        print('ERROR:', d['e']); return False
    nonce = struct.pack('>Q', d['p'] & 0xFFFFFFFFFFFFFFFF) if False else None
    # attr: base64 name; nonce for file CTR comes from the attr blob first 8 bytes? Standard: nonce = at[:8]
    at = b64d(d['at'])
    nonce = at[:8]
    name_b = decrypt_file(at[8:], fk[:16] if len(fk)==32 else fk, b'\0'*8)  # attr decrypt uses zero IV
    # attr decrypt: AES-CTR with iv=0
    from Crypto.Util import Counter as C2
    fk16 = fk[:16] if len(fk) == 32 else fk
    ctr0 = C2.Counter.new(128, initial_value=0, little_endian=False)
    attr = AES.new(fk16, AES.MODE_CTR, counter=ctr0).decrypt(at[8:])
    m = __import__('re').search(rb'"n":"([^"]+)"', attr)
    name = m.group(1).decode() if m else 'mega_file'
    print('name:', name)
    # download
    dl = requests.get(d['g'], timeout=1800).content
    nonce2 = struct.unpack('>Q', at[:8])[0] >> 16  # not used; proper: nonce from g response?
    ctr = Counter.new(128, initial_value=int.from_bytes(at[:8]+b'\0\0\0\0', 'big'), little_endian=False)
    aes = AES.new(fk16, AES.MODE_CTR, counter=ctr)
    dec = aes.decrypt(dl)
    open(out, 'wb').write(dec)
    print('saved', out, len(dec))
    return True

if __name__ == '__main__':
    mega_download(sys.argv[1], sys.argv[2])
