def _operate1_bulk_by_id(operation, destination_parent_id, source_inclusion_ids, conflict_resolution): session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) if len(source_inclusion_ids) == 0: raise pyacd.PyAmazonCloudDriveError("No source ids %s" % str(source_inclusion_ids)) params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "destinationParentId": destination_parent_id, "conflictResolution": conflict_resolution, } params.update( dict([[ "sourceInclusionIds.member.%d" % (i + 1), source_inclusion_ids[i] ] for i in range(len(source_inclusion_ids))])) end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json)
def download_by_id(object_id, attachment=0): """Download file after can_device_download. :type object_id: string :param object_id: :type attachment: (?)int :param attachment: (?)header of "Content-disposition: attachment" :rtype: binary :return: data stored in S3 """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) if not can_device_download(): sys.stderr.write( "\n\n" + "You have exceeded the maximum number of devices allowed. " + "Downloading is disabled for this browser.\n\n" + "SEE ALSO http://www.amazon.com/gp/help/customer/display.html/?ie=UTF8&nodeId=200557340\n" + "Frequently Asked Questions\n" + "How many devices can I use to access the files I've stored in my Cloud Drive?\n" + "\n\n") raise pyacd.PyAmazonCloudDriveError( "device limit (up to eight devices.) can be reached.") params = {"downloadById": object_id, "attachment": attachment} end_point = pyacd.api_root[:-1 * len("/api/")] + "?" + urllib.urlencode(params) #print end_point return pyacd.conn.do_get(end_point)
def _do_request(req,body): """ return response string """ if not pyacd.session: raise pyacd.PyAmazonCloudDriveError("session is None.") domain = pyacd.amazon_domain[3:] if pyacd.session.cookies._cookies.get(domain) and\ pyacd.session.cookies._cookies[domain].get("/") and\ pyacd.session.cookies._cookies[domain]["/"].get("session-id"): req.add_header( "x-amzn-SessionId", pyacd.session.cookies._cookies[domain]["/"]["session-id"].value ) try: if body: res = pyacd.opener.open(req,body) else: res = pyacd.opener.open(req) html = res.read() res.close() return html except urllib2.HTTPError, e: raise pyacd.PyAmazonCloudDriveError("%s %s %s:%s"%( req.get_full_url(), req.headers, e.code, e.msg ))
def select_metadata(query): """Query metadata like SQL. :type query: string :param query: like SQL e.g. select count(*) from object where hidden != true and parentObjectId='xxx' and status != 'PENDING' and type != 'RECYCLE' and type = "FOLDER" select count(*) from object where hidden != true and parentObjectId='xxx' and status != 'PENDING' and type != 'RECYCLE' select distinct parentObjectId from object where parent.parentObjectId='xxx' and type != "RECYCLE" and hidden = false and status != "PENDING" select distinct parentObjectId from object where parent.parentObjectId='xxx' and type = 'FOLDER' and hidden = false select creationDate, extension, objectId, keyName, purchaseDate, parentObjectId, status, name, lastModifiedDate, version, type, size, parent.name from object where purchaseDate = null and type='FILE' and hidden=false and status='AVAILABLE' order by creationDate DESC,keyName limit 0, 2 select creationDate, extension, objectId, keyName, purchaseDate, parentObjectId, status, name, lastModifiedDate, version, type, size, parent.name from object where type='FILE' and hidden=false and status='AVAILABLE' order by creationDate DESC,keyName limit 0, 2 :rtype: :class:`pyacd.apiresponse.Metadata` :return: informations selected. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "selectMetadata" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "query": query } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return Metadata(result)
def can_device_download(): """Check whether downloading is allowed. :rtype: bool :return: whether downloading is allowed. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "canDeviceDownload" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "deviceId.deviceType": "ubid", "deviceId.deviceSerialNumber": session.cookies["ubid-main"] } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return result["canDownload"]
def get_upload_url_by_id(object_id, size, method="POST"): """Get uploading URL to S3 after create_by_xxx. :type object_id: string :param object_id: :type size: int :param size: like len(data) :type method: string :param method: I know only "POST". :rtype: :class:`pyacd.apiresponse.UploadUrl` :return: informations of uploading. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "getUploadUrlById" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "objectId": object_id, "size": size, "method": method } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return UploadUrl(result)
def complete_file_upload_by_id(object_id, storage_key): """Finalize uploading file. :type object_id: string :param object_id: upload_url.object_id :type storage_key: string :param storage_key: upload_url.storage_key """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "completeFileUploadById" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "objectId": object_id, "storageKey": storage_key, } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json)
def __init__(self, result_json): self.total_space = result_json.get("totalSpace") self.used_space = result_json.get("usedSpace") self.free_space = result_json.get("freeSpace") if self.total_space is None or self.used_space is None or self.free_space is None: raise pyacd.PyAmazonCloudDriveError("unexpected response %s" % str(result_json))
def get_info_by_id(object_id): """Get informations of file or folder(specified id). :type object_id: string :param object_id: :rtype: :class:`pyacd.apiresponse.Info` :return: information. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "getInfoById" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "objectId": object_id, "populatePath": "true" } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return Info(result)
def create_by_path(path, name, Type=pyacd.types.FILE, conflict_resolution="RENAME", overwrite=False, autoparent=True): """Create file or folder into somewhere(specified absolute path). :type path: string :param path: :type name: string :param name: :type Type: string :param Type: pyacd.types.FILE | pyacd.types.FOLDER :type conflict_resolution: string :param conflict_resolution: "RENAME" | "MERGE" :type overwrite: bool :param overwrite: whether override or not. :type autoparent: bool :param autoparent: (?) :rtype: :class:`pyacd.apiresponse.Info` :return: information of created one. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "createByPath" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "path": path, "name": name, "type": Type, "conflictResolution": conflict_resolution, "overwrite": "true" if overwrite else "false", "autoparent": "true" if autoparent else "false" } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return Info(result.get("info"))
def list_by_id(object_id, ordering=None, next_token=0, max_items=None, Filter=None): """List entities in somewhere. :type object_id: string :param object_id: :type ordering: string :param ordering: comma separated and like "order by" in SQL e.g. keyName type,keyName,creationDate :type next_token: (?)int :param next_token: (?) :type max_items: int :param max_items: None means unlimited :type Filter: string :param Filter: like "where" in SQL e.g. type = "FOLDER" and hidden = false type != "RECYCLE" and status != "PENDING" and hidden = false :rtype: :class:`pyacd.apiresponse.List` :return: informations listed. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "listById" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "objectId": object_id, "nextToken": next_token } if ordering: params["ordering"] = ordering if max_items: params["maxItems"] = max_items if Filter: params["filter"] = Filter end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return List(result)
def empty_recycle_bin(): """Empty out "/RecycleBin". """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "emptyRecycleBin" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json)
def create_by_id(parent_id, name, Type=pyacd.types.FOLDER, overwrite=False): """Create file or folder into somewhere(specified id). :type parent_id: string :param parent_id: :type name: string :param name: :type Type: string :param Type: pyacd.types.FILE | pyacd.types.FOLDER :type overwrite: bool :param overwrite: whether override or not. :rtype: :class:`pyacd.apiresponse.Info` :return: information of created one. """ session = pyacd.get_session() if not session.is_logged_in(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "createById" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "parentId": parent_id, "name": name, "type": Type, "overwrite": "true" if overwrite else "false" } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return Info(result.get("info"))
def get_subscription_problem(): """Get information of xxx. (I don't know) :rtype: :class:`pyacd.apiresponse.SubscriptionProblem` :return: (?) """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "getSubscriptionProblem" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON" } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return SubscriptionProblem(result)
def get_user_storage(): """Get informations of user storage. :rtype: :class:`pyacd.apiresponse.UserStorage` :return: information. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "getUserStorage" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON" } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json) result = resp_json.get(operation + "Response").get(operation + "Result") return UserStorage(result)
def move_by_id(source_id, destination_parent_id, destination_name, overwrite=False): """Move file or folder to to somewhere. :type source_id: string :param source_id: :type destination_parent_id: string :param destination_parent_id: :type destination_name: new name :param destination_name: :type overwrite: bool :param overwrite: whether override or not. """ session = pyacd.get_session() if not session.is_logined(): raise pyacd.PyAmazonCloudDriveError("Not logined %s" % session) operation = "moveById" params = { "_": int(time.time()), "Operation": operation, "customerId": session.customer_id, "ContentType": "JSON", "sourceId": source_id, "destinationParentId": destination_parent_id, "destinationName": destination_name, "overwrite": "true" if overwrite else "false" } end_point = pyacd.api_root + "?" + urllib.urlencode(params) resp_json = json.loads(pyacd.conn.do_get(end_point)) _error_check(resp_json)
def login(email=None,password=None,session=None): """Login either with email and password or session. :type email: string :param email: email address registered to Amazon :type password: string :param password: password :type session: pyacd.session.Session :param session: previous session :rtype: :class:`pyacd.session.Session` :return: Inclues cookies, username and customer_id. """ if session: pyacd.session=Session(session) elif email is None or password is None: raise TypeError("Invalid args, email:%s, password:%s"%(email,password)) else: pyacd.session=Session() end_point="https://"+pyacd.amazon_domain+"/clouddrive?sf=1&ref_=cd_home_sign_bnh" html=pyacd.do_get(end_point) NOT_LOGGED_INS=[r"ue_url='\/gp\/feature\.html",r'<form name="signIn" method="POST"',r'id="sign-in-container"'] CONTINUE_REQUIRED=r'<form action="\/clouddrive" id="continueForm"' if False in [re.search(x,html) is None for x in NOT_LOGGED_INS]: if not (email and password): raise pyacd.PyAmazonCloudDriveError("Both email and password are required.") link = re.search(r'"(\/gp\/drive\/files.*?)"',html) if link: html=pyacd.do_get("https://"+pyacd.amazon_domain+link.groups()[0]) form = re.search(r'<form name="signIn" method="POST" .*?<\/form>',re.sub(r"\n|\r","",html)).group() action = re.search('action="(.*?)"',form).groups()[0] inputs = [re.search(' name="(.*?)".*? value="(.*?)"',x) for x in re.findall('<input.*?>',form)] params = dict([x.groups() for x in inputs if x!=None]) params["create"]=0 params["email"]=email params["password"]=password body=urllib.urlencode(params) html=pyacd.do_post(action,body) if False in [re.search(x,html) is None for x in NOT_LOGGED_INS]: raise pyacd.PyAmazonCloudDriveError("Login failed.") if re.search(CONTINUE_REQUIRED,html): form = re.search(CONTINUE_REQUIRED+r".*?<\/form>",re.sub(r"\n|\r","",html)).group() action = re.search('action="(.*?)"',form).groups()[0] inputs = [re.search(' name="(.*?)".*? value="(.*?)"',x) for x in re.findall('<input.*?>',form)] params = dict([x.groups() for x in inputs if x!=None]) if action[0]=="/": action = "https://"+pyacd.amazon_domain+action body=urllib.urlencode(params) html=pyacd.do_post(action,body) try: pyacd.session.customer_id=re.search('customerId: "(.+)"', html).groups()[0] pyacd.session.username="******" if re.search(r"ADrive\.touValidate = true;",html): pyacd.session.agreed_with_terms = True except: pass return pyacd.session