more PEP8 generally

This commit is contained in:
richard 2013-06-27 22:25:02 +01:00
parent 42a20b710d
commit 7c88b34a48

View file

@ -7,7 +7,6 @@ import os
import random import random
import binascii import binascii
import requests import requests
import time
import shutil import shutil
from .errors import ValidationError, RequestError from .errors import ValidationError, RequestError
from .crypto import * from .crypto import *
@ -29,15 +28,15 @@ class Mega(object):
def login(self, email=None, password=None): def login(self, email=None, password=None):
if email: if email:
self.login_user(email, password) self._login_user(email, password)
else: else:
self.login_anonymous() self.login_anonymous()
return self return self
def login_user(self, email, password): def _login_user(self, email, password):
password_aes = prepare_key(str_to_a32(password)) password_aes = prepare_key(str_to_a32(password))
uh = stringhash(email, password_aes) uh = stringhash(email, password_aes)
resp = self.api_request({'a': 'us', 'user': email, 'uh': uh}) resp = self._api_request({'a': 'us', 'user': email, 'uh': uh})
#if numeric error code response #if numeric error code response
if isinstance(resp, int): if isinstance(resp, int):
raise RequestError(resp) raise RequestError(resp)
@ -48,14 +47,14 @@ class Mega(object):
password_key = [random.randint(0, 0xFFFFFFFF)] * 4 password_key = [random.randint(0, 0xFFFFFFFF)] * 4
session_self_challenge = [random.randint(0, 0xFFFFFFFF)] * 4 session_self_challenge = [random.randint(0, 0xFFFFFFFF)] * 4
user = self.api_request({ user = self._api_request({
'a': 'up', 'a': 'up',
'k': a32_to_base64(encrypt_key(master_key, password_key)), 'k': a32_to_base64(encrypt_key(master_key, password_key)),
'ts': base64_url_encode(a32_to_str(session_self_challenge) + 'ts': base64_url_encode(a32_to_str(session_self_challenge) +
a32_to_str(encrypt_key(session_self_challenge, master_key))) a32_to_str(encrypt_key(session_self_challenge, master_key)))
}) })
resp = self.api_request({'a': 'us', 'user': user}) resp = self._api_request({'a': 'us', 'user': user})
#if numeric error code response #if numeric error code response
if isinstance(resp, int): if isinstance(resp, int):
raise RequestError(resp) raise RequestError(resp)
@ -93,7 +92,7 @@ class Mega(object):
sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid) sid = binascii.unhexlify('0' + sid if len(sid) % 2 else sid)
self.sid = base64_url_encode(sid[:43]) self.sid = base64_url_encode(sid[:43])
def api_request(self, data): def _api_request(self, data):
params = {'id': self.sequence_num} params = {'id': self.sequence_num}
self.sequence_num += 1 self.sequence_num += 1
@ -116,16 +115,16 @@ class Mega(object):
raise RequestError(json_resp) raise RequestError(json_resp)
return json_resp[0] return json_resp[0]
def parse_url(self, url): def _parse_url(self, url):
#parse file id and key from url #parse file id and key from url
if ('!' in url): if '!' in url:
match = re.findall(r'/#!(.*)', url) match = re.findall(r'/#!(.*)', url)
path = match[0] path = match[0]
return path return path
else: else:
raise RequestError('Url key missing') raise RequestError('Url key missing')
def process_file(self, file, shared_keys): def _process_file(self, file, shared_keys):
""" """
Process a file Process a file
""" """
@ -180,7 +179,7 @@ class Mega(object):
file['a'] = {'n': 'Rubbish Bin'} file['a'] = {'n': 'Rubbish Bin'}
return file return file
def init_shared_keys(self, files, shared_keys): def _init_shared_keys(self, files, shared_keys):
""" """
Init shared key not associated with a user. Init shared key not associated with a user.
Seems to happen when a folder is shared, Seems to happen when a folder is shared,
@ -213,12 +212,12 @@ class Mega(object):
""" """
Get all files in account Get all files in account
""" """
files = self.api_request({'a': 'f', 'c': 1}) files = self._api_request({'a': 'f', 'c': 1})
files_dict = {} files_dict = {}
shared_keys = {} shared_keys = {}
self.init_shared_keys(files, shared_keys) self._init_shared_keys(files, shared_keys)
for file in files['f']: for file in files['f']:
processed_file = self.process_file(file, shared_keys) processed_file = self._process_file(file, shared_keys)
#ensure each file has a name before returning #ensure each file has a name before returning
if processed_file['a']: if processed_file['a']:
files_dict[file['h']] = processed_file files_dict[file['h']] = processed_file
@ -231,7 +230,7 @@ class Mega(object):
""" """
if 'f' in file: if 'f' in file:
file = file['f'][0] file = file['f'][0]
public_handle = self.api_request({'a': 'l', 'n': file['h']}) public_handle = self._api_request({'a': 'l', 'n': file['h']})
file_key = file['k'][file['k'].index(':') + 1:] file_key = file['k'][file['k'].index(':') + 1:]
decrypted_key = a32_to_base64(decrypt_key(base64_to_a32(file_key), decrypted_key = a32_to_base64(decrypt_key(base64_to_a32(file_key),
self.master_key)) self.master_key))
@ -249,7 +248,7 @@ class Mega(object):
""" """
file = file[1] file = file[1]
if 'h' in file and 'k' in file: if 'h' in file and 'k' in file:
public_handle = self.api_request({'a': 'l', 'n': file['h']}) public_handle = self._api_request({'a': 'l', 'n': file['h']})
if public_handle == -11: if public_handle == -11:
raise RequestError("Can't get a public link from that file (is this a shared file?)") raise RequestError("Can't get a public link from that file (is this a shared file?)")
decrypted_key = a32_to_base64(file['key']) decrypted_key = a32_to_base64(file['key'])
@ -261,7 +260,7 @@ class Mega(object):
raise ValidationError('File id and key must be present') raise ValidationError('File id and key must be present')
def get_user(self): def get_user(self):
user_data = self.api_request({'a': 'ug'}) user_data = self._api_request({'a': 'ug'})
return user_data return user_data
def get_node_by_type(self, type): def get_node_by_type(self, type):
@ -275,7 +274,7 @@ class Mega(object):
""" """
nodes = self.get_files() nodes = self.get_files()
for node in nodes.items(): for node in nodes.items():
if (node[1]['t'] == type): if node[1]['t'] == type:
return node return node
def get_files_in_node(self, target): def get_files_in_node(self, target):
@ -288,19 +287,19 @@ class Mega(object):
else: else:
node_id = [target] node_id = [target]
files = self.api_request({'a': 'f', 'c': 1}) files = self._api_request({'a': 'f', 'c': 1})
files_dict = {} files_dict = {}
shared_keys = {} shared_keys = {}
self.init_shared_keys(files, shared_keys) self._init_shared_keys(files, shared_keys)
for file in files['f']: for file in files['f']:
processed_file = self.process_file(file, shared_keys) processed_file = self._process_file(file, shared_keys)
if processed_file['a'] and processed_file['p'] == node_id[0]: if processed_file['a'] and processed_file['p'] == node_id[0]:
files_dict[file['h']] = processed_file files_dict[file['h']] = processed_file
return files_dict return files_dict
def get_id_from_public_handle(self, public_handle): def get_id_from_public_handle(self, public_handle):
#get node data #get node data
node_data = self.api_request({'a': 'f', 'f': 1, 'p': public_handle}) node_data = self._api_request({'a': 'f', 'f': 1, 'p': public_handle})
node_id = self.get_id_from_obj(node_data) node_id = self.get_id_from_obj(node_data)
return node_id return node_id
@ -319,7 +318,7 @@ class Mega(object):
""" """
Get current remaining disk quota in MegaBytes Get current remaining disk quota in MegaBytes
""" """
json_resp = self.api_request({'a': 'uq', 'xfer': 1}) json_resp = self._api_request({'a': 'uq', 'xfer': 1})
#convert bytes to megabyes #convert bytes to megabyes
return json_resp['mstrg'] / 1048576 return json_resp['mstrg'] / 1048576
@ -340,7 +339,7 @@ class Mega(object):
unit_coef = 1048576 unit_coef = 1048576
if giga: if giga:
unit_coef = 1073741824 unit_coef = 1073741824
json_resp = self.api_request({'a': 'uq', 'xfer': 1, 'strg': 1}) json_resp = self._api_request({'a': 'uq', 'xfer': 1, 'strg': 1})
return { return {
'used': json_resp['cstrg'] / unit_coef, 'used': json_resp['cstrg'] / unit_coef,
'total': json_resp['mstrg'] / unit_coef, 'total': json_resp['mstrg'] / unit_coef,
@ -350,7 +349,7 @@ class Mega(object):
""" """
Get account monetary balance, Pro accounts only Get account monetary balance, Pro accounts only
""" """
user_data = self.api_request({"a": "uq", "pro": 1}) user_data = self._api_request({"a": "uq", "pro": 1})
if 'balance' in user_data: if 'balance' in user_data:
return user_data['balance'] return user_data['balance']
@ -366,7 +365,7 @@ class Mega(object):
""" """
Delete a file by its url Delete a file by its url
""" """
path = self.parse_url(url).split('!') path = self._parse_url(url).split('!')
public_handle = path[0] public_handle = path[0]
file_id = self.get_id_from_public_handle(public_handle) file_id = self.get_id_from_public_handle(public_handle)
return self.move(file_id, 4) return self.move(file_id, 4)
@ -375,7 +374,7 @@ class Mega(object):
""" """
Destroy a file by its private id Destroy a file by its private id
""" """
return self.api_request({'a': 'd', return self._api_request({'a': 'd',
'n': file_id, 'n': file_id,
'i': self.request_id}) 'i': self.request_id})
@ -383,7 +382,7 @@ class Mega(object):
""" """
Destroy a file by its url Destroy a file by its url
""" """
path = self.parse_url(url).split('!') path = self._parse_url(url).split('!')
public_handle = path[0] public_handle = path[0]
file_id = self.get_id_from_public_handle(public_handle) file_id = self.get_id_from_public_handle(public_handle)
return self.destroy(file_id) return self.destroy(file_id)
@ -399,7 +398,7 @@ class Mega(object):
post_list.append({"a": "d", post_list.append({"a": "d",
"n": file, "n": file,
"i": self.request_id}) "i": self.request_id})
return self.api_request(post_list) return self._api_request(post_list)
########################################################################## ##########################################################################
# DOWNLOAD # DOWNLOAD
@ -407,31 +406,31 @@ class Mega(object):
""" """
Download a file by it's file object Download a file by it's file object
""" """
self.download_file(None, None, file=file[1], dest_path=dest_path, dest_filename=dest_filename, is_public=False) self._download_file(None, None, file=file[1], dest_path=dest_path, dest_filename=dest_filename, is_public=False)
def download_url(self, url, dest_path=None, dest_filename=None): def download_url(self, url, dest_path=None, dest_filename=None):
""" """
Download a file by it's public url Download a file by it's public url
""" """
path = self.parse_url(url).split('!') path = self._parse_url(url).split('!')
file_id = path[0] file_id = path[0]
file_key = path[1] file_key = path[1]
self.download_file(file_id, file_key, dest_path, dest_filename, is_public=True) self._download_file(file_id, file_key, dest_path, dest_filename, is_public=True)
def download_file(self, file_handle, file_key, dest_path=None, dest_filename=None, is_public=False, file=None): def _download_file(self, file_handle, file_key, dest_path=None, dest_filename=None, is_public=False, file=None):
if file is None: if file is None:
if is_public: if is_public:
file_key = base64_to_a32(file_key) file_key = base64_to_a32(file_key)
file_data = self.api_request({'a': 'g', 'g': 1, 'p': file_handle}) file_data = self._api_request({'a': 'g', 'g': 1, 'p': file_handle})
else: else:
file_data = self.api_request({'a': 'g', 'g': 1, 'n': file_handle}) file_data = self._api_request({'a': 'g', 'g': 1, 'n': file_handle})
k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5], k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5],
file_key[2] ^ file_key[6], file_key[3] ^ file_key[7]) file_key[2] ^ file_key[6], file_key[3] ^ file_key[7])
iv = file_key[4:6] + (0, 0) iv = file_key[4:6] + (0, 0)
meta_mac = file_key[6:8] meta_mac = file_key[6:8]
else: else:
file_data = self.api_request({'a': 'g', 'g': 1, 'n': file['h']}) file_data = self._api_request({'a': 'g', 'g': 1, 'n': file['h']})
k = file['k'] k = file['k']
iv = file['iv'] iv = file['iv']
meta_mac = file['meta_mac'] meta_mac = file['meta_mac']
@ -518,7 +517,7 @@ class Mega(object):
#request upload url, call 'u' method #request upload url, call 'u' method
input_file = open(filename, 'rb') input_file = open(filename, 'rb')
file_size = os.path.getsize(filename) file_size = os.path.getsize(filename)
ul_url = self.api_request({'a': 'u', 's': file_size})['p'] ul_url = self._api_request({'a': 'u', 's': file_size})['p']
#generate random aes key (128) for file #generate random aes key (128) for file
ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)] ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)]
@ -579,7 +578,7 @@ class Mega(object):
ul_key[4], ul_key[5], meta_mac[0], meta_mac[1]] ul_key[4], ul_key[5], meta_mac[0], meta_mac[1]]
encrypted_key = a32_to_base64(encrypt_key(key, self.master_key)) encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
#update attributes #update attributes
data = self.api_request({'a': 'p', 't': dest, 'n': [{ data = self._api_request({'a': 'p', 't': dest, 'n': [{
'h': completion_file_handle, 'h': completion_file_handle,
't': 0, 't': 0,
'a': encrypt_attribs, 'a': encrypt_attribs,
@ -607,7 +606,7 @@ class Mega(object):
encrypted_key = a32_to_base64(encrypt_key(ul_key[:4], self.master_key)) encrypted_key = a32_to_base64(encrypt_key(ul_key[:4], self.master_key))
#update attributes #update attributes
data = self.api_request({'a': 'p', data = self._api_request({'a': 'p',
't': dest, 't': dest,
'n': [{ 'n': [{
'h': 'xxxxxxxx', 'h': 'xxxxxxxx',
@ -628,7 +627,7 @@ class Mega(object):
encrypted_key = a32_to_base64(encrypt_key(file['key'], self.master_key)) encrypted_key = a32_to_base64(encrypt_key(file['key'], self.master_key))
#update attributes #update attributes
data = self.api_request([{ data = self._api_request([{
'a': 'a', 'a': 'a',
'attr': encrypt_attribs, 'attr': encrypt_attribs,
'key': encrypted_key, 'key': encrypted_key,
@ -666,7 +665,7 @@ class Mega(object):
else: else:
file = target[1] file = target[1]
target_node_id = file['h'] target_node_id = file['h']
return self.api_request({'a': 'm', return self._api_request({'a': 'm',
'n': file_id, 'n': file_id,
't': target_node_id, 't': target_node_id,
'i': self.request_id}) 'i': self.request_id})
@ -697,7 +696,7 @@ class Mega(object):
if not re.match(r"[^@]+@[^@]+\.[^@]+", email): if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
ValidationError('add_contact requires a valid email address') ValidationError('add_contact requires a valid email address')
else: else:
return self.api_request({'a': 'ur', return self._api_request({'a': 'ur',
'u': email, 'u': email,
'l': l, 'l': l,
'i': self.request_id}) 'i': self.request_id})
@ -722,21 +721,21 @@ class Mega(object):
""" """
Get size and name from a public url, dict returned Get size and name from a public url, dict returned
""" """
file_handle, file_key = self.parse_url(url).split('!') file_handle, file_key = self._parse_url(url).split('!')
return self.get_public_file_info(file_handle, file_key) return self.get_public_file_info(file_handle, file_key)
def import_public_url(self, url, dest_node=None, dest_name=None): def import_public_url(self, url, dest_node=None, dest_name=None):
""" """
Import the public url into user account Import the public url into user account
""" """
file_handle, file_key = self.parse_url(url).split('!') file_handle, file_key = self._parse_url(url).split('!')
return self.import_public_file(file_handle, file_key, dest_node=dest_node, dest_name=dest_name) return self.import_public_file(file_handle, file_key, dest_node=dest_node, dest_name=dest_name)
def get_public_file_info(self, file_handle, file_key): def get_public_file_info(self, file_handle, file_key):
""" """
Get size and name of a public file Get size and name of a public file
""" """
data = self.api_request({ data = self._api_request({
'a': 'g', 'a': 'g',
'p': file_handle, 'p': file_handle,
'ssm': 1}) 'ssm': 1})
@ -753,7 +752,7 @@ class Mega(object):
size = data['s'] size = data['s']
unencrypted_attrs = decrypt_attr(base64_url_decode(data['at']), k) unencrypted_attrs = decrypt_attr(base64_url_decode(data['at']), k)
if not(unencrypted_attrs): if not unencrypted_attrs:
return None return None
result = { result = {
@ -783,7 +782,7 @@ class Mega(object):
encrypted_key = a32_to_base64(encrypt_key(key, self.master_key)) encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
encrypted_name = base64_url_encode(encrypt_attr({'n': dest_name}, k)) encrypted_name = base64_url_encode(encrypt_attr({'n': dest_name}, k))
data = self.api_request({ data = self._api_request({
'a': 'p', 'a': 'p',
't': dest_node['h'], 't': dest_node['h'],
'n': [{ 'n': [{