prompt_id
int64
0
941
project
stringclasses
24 values
module
stringlengths
7
49
class
stringlengths
0
32
method
stringlengths
2
37
focal_method_txt
stringlengths
43
41.5k
focal_method_lines
listlengths
2
2
in_stack
bool
2 classes
globals
listlengths
0
16
type_context
stringlengths
79
41.9k
has_branch
bool
2 classes
total_branches
int64
0
3
845
typesystem
typesystem.json_schema
all_of_from_json_schema
def all_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: all_of = [from_json_schema(item, definitions=definitions) for item in data["allOf"]] kwargs = {"all_of": all_of, "default": data.get("default", NO_DEFAULT)} return AllOf(**kwargs)
[ 351, 354 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.schemas import Reference, Schema, SchemaDefinitions TYPE_CONSTRAINTS = { "additionalItems", "additionalProperties", "boolean_schema", "contains", "dependencies", "exclusiveMaximum", "exclusiveMinimum", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "pattern", "patternProperties", "properties", "propertyNames", "required", "type", "uniqueItems", } definitions["JSONSchema"] = JSONSchema JSONSchema = ( Object( properties={ "$ref": String(), "type": String() | Array(items=String()), "enum": Array(unique_items=True, min_items=1), "definitions": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), # String "minLength": Integer(minimum=0), "maxLength": Integer(minimum=0), "pattern": String(format="regex"), "format": String(), # Numeric "minimum": Number(), "maximum": Number(), "exclusiveMinimum": Number(), "exclusiveMaximum": Number(), "multipleOf": Number(exclusive_minimum=0), # Object "properties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "minProperties": Integer(minimum=0), "maxProperties": Integer(minimum=0), "patternProperties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "additionalProperties": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "required": Array(items=String(), unique_items=True), # Array "items": ( Reference("JSONSchema", definitions=definitions) | Array( items=Reference("JSONSchema", definitions=definitions), min_items=1 ) ), "additionalItems": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "minItems": Integer(minimum=0), "maxItems": Integer(minimum=0), "uniqueItems": Boolean(), } ) | Boolean() ) def all_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: all_of = [from_json_schema(item, definitions=definitions) for item in data["allOf"]] kwargs = {"all_of": all_of, "default": data.get("default", NO_DEFAULT)} return AllOf(**kwargs)
false
0
846
typesystem
typesystem.json_schema
any_of_from_json_schema
def any_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: any_of = [from_json_schema(item, definitions=definitions) for item in data["anyOf"]] kwargs = {"any_of": any_of, "default": data.get("default", NO_DEFAULT)} return Union(**kwargs)
[ 357, 360 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.schemas import Reference, Schema, SchemaDefinitions TYPE_CONSTRAINTS = { "additionalItems", "additionalProperties", "boolean_schema", "contains", "dependencies", "exclusiveMaximum", "exclusiveMinimum", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "pattern", "patternProperties", "properties", "propertyNames", "required", "type", "uniqueItems", } definitions["JSONSchema"] = JSONSchema JSONSchema = ( Object( properties={ "$ref": String(), "type": String() | Array(items=String()), "enum": Array(unique_items=True, min_items=1), "definitions": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), # String "minLength": Integer(minimum=0), "maxLength": Integer(minimum=0), "pattern": String(format="regex"), "format": String(), # Numeric "minimum": Number(), "maximum": Number(), "exclusiveMinimum": Number(), "exclusiveMaximum": Number(), "multipleOf": Number(exclusive_minimum=0), # Object "properties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "minProperties": Integer(minimum=0), "maxProperties": Integer(minimum=0), "patternProperties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "additionalProperties": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "required": Array(items=String(), unique_items=True), # Array "items": ( Reference("JSONSchema", definitions=definitions) | Array( items=Reference("JSONSchema", definitions=definitions), min_items=1 ) ), "additionalItems": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "minItems": Integer(minimum=0), "maxItems": Integer(minimum=0), "uniqueItems": Boolean(), } ) | Boolean() ) def any_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: any_of = [from_json_schema(item, definitions=definitions) for item in data["anyOf"]] kwargs = {"any_of": any_of, "default": data.get("default", NO_DEFAULT)} return Union(**kwargs)
false
0
847
typesystem
typesystem.json_schema
one_of_from_json_schema
def one_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: one_of = [from_json_schema(item, definitions=definitions) for item in data["oneOf"]] kwargs = {"one_of": one_of, "default": data.get("default", NO_DEFAULT)} return OneOf(**kwargs)
[ 363, 366 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.schemas import Reference, Schema, SchemaDefinitions TYPE_CONSTRAINTS = { "additionalItems", "additionalProperties", "boolean_schema", "contains", "dependencies", "exclusiveMaximum", "exclusiveMinimum", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "pattern", "patternProperties", "properties", "propertyNames", "required", "type", "uniqueItems", } definitions["JSONSchema"] = JSONSchema JSONSchema = ( Object( properties={ "$ref": String(), "type": String() | Array(items=String()), "enum": Array(unique_items=True, min_items=1), "definitions": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), # String "minLength": Integer(minimum=0), "maxLength": Integer(minimum=0), "pattern": String(format="regex"), "format": String(), # Numeric "minimum": Number(), "maximum": Number(), "exclusiveMinimum": Number(), "exclusiveMaximum": Number(), "multipleOf": Number(exclusive_minimum=0), # Object "properties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "minProperties": Integer(minimum=0), "maxProperties": Integer(minimum=0), "patternProperties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "additionalProperties": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "required": Array(items=String(), unique_items=True), # Array "items": ( Reference("JSONSchema", definitions=definitions) | Array( items=Reference("JSONSchema", definitions=definitions), min_items=1 ) ), "additionalItems": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "minItems": Integer(minimum=0), "maxItems": Integer(minimum=0), "uniqueItems": Boolean(), } ) | Boolean() ) def one_of_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: one_of = [from_json_schema(item, definitions=definitions) for item in data["oneOf"]] kwargs = {"one_of": one_of, "default": data.get("default", NO_DEFAULT)} return OneOf(**kwargs)
false
0
848
typesystem
typesystem.json_schema
not_from_json_schema
def not_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: negated = from_json_schema(data["not"], definitions=definitions) kwargs = {"negated": negated, "default": data.get("default", NO_DEFAULT)} return Not(**kwargs)
[ 369, 372 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.schemas import Reference, Schema, SchemaDefinitions TYPE_CONSTRAINTS = { "additionalItems", "additionalProperties", "boolean_schema", "contains", "dependencies", "exclusiveMaximum", "exclusiveMinimum", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "pattern", "patternProperties", "properties", "propertyNames", "required", "type", "uniqueItems", } definitions["JSONSchema"] = JSONSchema JSONSchema = ( Object( properties={ "$ref": String(), "type": String() | Array(items=String()), "enum": Array(unique_items=True, min_items=1), "definitions": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), # String "minLength": Integer(minimum=0), "maxLength": Integer(minimum=0), "pattern": String(format="regex"), "format": String(), # Numeric "minimum": Number(), "maximum": Number(), "exclusiveMinimum": Number(), "exclusiveMaximum": Number(), "multipleOf": Number(exclusive_minimum=0), # Object "properties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "minProperties": Integer(minimum=0), "maxProperties": Integer(minimum=0), "patternProperties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "additionalProperties": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "required": Array(items=String(), unique_items=True), # Array "items": ( Reference("JSONSchema", definitions=definitions) | Array( items=Reference("JSONSchema", definitions=definitions), min_items=1 ) ), "additionalItems": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "minItems": Integer(minimum=0), "maxItems": Integer(minimum=0), "uniqueItems": Boolean(), } ) | Boolean() ) def not_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: negated = from_json_schema(data["not"], definitions=definitions) kwargs = {"negated": negated, "default": data.get("default", NO_DEFAULT)} return Not(**kwargs)
false
0
849
typesystem
typesystem.json_schema
if_then_else_from_json_schema
def if_then_else_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: if_clause = from_json_schema(data["if"], definitions=definitions) then_clause = ( from_json_schema(data["then"], definitions=definitions) if "then" in data else None ) else_clause = ( from_json_schema(data["else"], definitions=definitions) if "else" in data else None ) kwargs = { "if_clause": if_clause, "then_clause": then_clause, "else_clause": else_clause, "default": data.get("default", NO_DEFAULT), } return IfThenElse(**kwargs)
[ 375, 393 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.schemas import Reference, Schema, SchemaDefinitions TYPE_CONSTRAINTS = { "additionalItems", "additionalProperties", "boolean_schema", "contains", "dependencies", "exclusiveMaximum", "exclusiveMinimum", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "pattern", "patternProperties", "properties", "propertyNames", "required", "type", "uniqueItems", } definitions["JSONSchema"] = JSONSchema JSONSchema = ( Object( properties={ "$ref": String(), "type": String() | Array(items=String()), "enum": Array(unique_items=True, min_items=1), "definitions": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), # String "minLength": Integer(minimum=0), "maxLength": Integer(minimum=0), "pattern": String(format="regex"), "format": String(), # Numeric "minimum": Number(), "maximum": Number(), "exclusiveMinimum": Number(), "exclusiveMaximum": Number(), "multipleOf": Number(exclusive_minimum=0), # Object "properties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "minProperties": Integer(minimum=0), "maxProperties": Integer(minimum=0), "patternProperties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "additionalProperties": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "required": Array(items=String(), unique_items=True), # Array "items": ( Reference("JSONSchema", definitions=definitions) | Array( items=Reference("JSONSchema", definitions=definitions), min_items=1 ) ), "additionalItems": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "minItems": Integer(minimum=0), "maxItems": Integer(minimum=0), "uniqueItems": Boolean(), } ) | Boolean() ) def if_then_else_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: if_clause = from_json_schema(data["if"], definitions=definitions) then_clause = ( from_json_schema(data["then"], definitions=definitions) if "then" in data else None ) else_clause = ( from_json_schema(data["else"], definitions=definitions) if "else" in data else None ) kwargs = { "if_clause": if_clause, "then_clause": then_clause, "else_clause": else_clause, "default": data.get("default", NO_DEFAULT), } return IfThenElse(**kwargs)
false
0
850
typesystem
typesystem.json_schema
to_json_schema
def to_json_schema( arg: typing.Union[Field, typing.Type[Schema]], _definitions: dict = None ) -> typing.Union[bool, dict]: if isinstance(arg, Any): return True elif isinstance(arg, NeverMatch): return False data: dict = {} is_root = _definitions is None definitions = {} if _definitions is None else _definitions if isinstance(arg, Field): field = arg elif isinstance(arg, SchemaDefinitions): field = None for key, value in arg.items(): definitions[key] = to_json_schema(value, _definitions=definitions) else: field = arg.make_validator() if isinstance(field, Reference): data["$ref"] = f"#/definitions/{field.target_string}" definitions[field.target_string] = to_json_schema( field.target, _definitions=definitions ) elif isinstance(field, String): data["type"] = ["string", "null"] if field.allow_null else "string" data.update(get_standard_properties(field)) if field.min_length is not None or not field.allow_blank: data["minLength"] = field.min_length or 1 if field.max_length is not None: data["maxLength"] = field.max_length if field.pattern_regex is not None: if field.pattern_regex.flags != re.RegexFlag.UNICODE: flags = re.RegexFlag(field.pattern_regex.flags) raise ValueError( f"Cannot convert regular expression with non-standard flags " f"to JSON schema: {flags!s}" ) data["pattern"] = field.pattern_regex.pattern if field.format is not None: data["format"] = field.format elif isinstance(field, (Integer, Float, Decimal)): base_type = "integer" if isinstance(field, Integer) else "number" data["type"] = [base_type, "null"] if field.allow_null else base_type data.update(get_standard_properties(field)) if field.minimum is not None: data["minimum"] = field.minimum if field.maximum is not None: data["maximum"] = field.maximum if field.exclusive_minimum is not None: data["exclusiveMinimum"] = field.exclusive_minimum if field.exclusive_maximum is not None: data["exclusiveMaximum"] = field.exclusive_maximum if field.multiple_of is not None: data["multipleOf"] = field.multiple_of elif isinstance(field, Boolean): data["type"] = ["boolean", "null"] if field.allow_null else "boolean" data.update(get_standard_properties(field)) elif isinstance(field, Array): data["type"] = ["array", "null"] if field.allow_null else "array" data.update(get_standard_properties(field)) if field.min_items is not None: data["minItems"] = field.min_items if field.max_items is not None: data["maxItems"] = field.max_items if field.items is not None: if isinstance(field.items, (list, tuple)): data["items"] = [ to_json_schema(item, _definitions=definitions) for item in field.items ] else: data["items"] = to_json_schema(field.items, _definitions=definitions) if field.additional_items is not None: if isinstance(field.additional_items, bool): data["additionalItems"] = field.additional_items else: data["additionalItems"] = to_json_schema( field.additional_items, _definitions=definitions ) if field.unique_items is not False: data["uniqueItems"] = True elif isinstance(field, Object): data["type"] = ["object", "null"] if field.allow_null else "object" data.update(get_standard_properties(field)) if field.properties: data["properties"] = { key: to_json_schema(value, _definitions=definitions) for key, value in field.properties.items() } if field.pattern_properties: data["patternProperties"] = { key: to_json_schema(value, _definitions=definitions) for key, value in field.pattern_properties.items() } if field.additional_properties is not None: if isinstance(field.additional_properties, bool): data["additionalProperties"] = field.additional_properties else: data["additionalProperties"] = to_json_schema( field.additional_properties, _definitions=definitions ) if field.property_names is not None: data["propertyNames"] = to_json_schema( field.property_names, _definitions=definitions ) if field.max_properties is not None: data["maxProperties"] = field.max_properties if field.min_properties is not None: data["minProperties"] = field.min_properties if field.required: data["required"] = field.required elif isinstance(field, Choice): data["enum"] = [key for key, value in field.choices] data.update(get_standard_properties(field)) elif isinstance(field, Const): data["const"] = field.const data.update(get_standard_properties(field)) elif isinstance(field, Union): data["anyOf"] = [ to_json_schema(item, _definitions=definitions) for item in field.any_of ] data.update(get_standard_properties(field)) elif isinstance(field, OneOf): data["oneOf"] = [ to_json_schema(item, _definitions=definitions) for item in field.one_of ] data.update(get_standard_properties(field)) elif isinstance(field, AllOf): data["allOf"] = [ to_json_schema(item, _definitions=definitions) for item in field.all_of ] data.update(get_standard_properties(field)) elif isinstance(field, IfThenElse): data["if"] = to_json_schema(field.if_clause, _definitions=definitions) if field.then_clause is not None: data["then"] = to_json_schema(field.then_clause, _definitions=definitions) if field.else_clause is not None: data["else"] = to_json_schema(field.else_clause, _definitions=definitions) data.update(get_standard_properties(field)) elif isinstance(field, Not): data["not"] = to_json_schema(field.negated, _definitions=definitions) data.update(get_standard_properties(field)) elif field is not None: name = type(field).__qualname__ raise ValueError(f"Cannot convert field type {name!r} to JSON Schema") if is_root and definitions: data["definitions"] = definitions return data
[ 396, 561 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.schemas import Reference, Schema, SchemaDefinitions TYPE_CONSTRAINTS = { "additionalItems", "additionalProperties", "boolean_schema", "contains", "dependencies", "exclusiveMaximum", "exclusiveMinimum", "items", "maxItems", "maxLength", "maxProperties", "maximum", "minItems", "minLength", "minProperties", "minimum", "multipleOf", "pattern", "patternProperties", "properties", "propertyNames", "required", "type", "uniqueItems", } definitions["JSONSchema"] = JSONSchema JSONSchema = ( Object( properties={ "$ref": String(), "type": String() | Array(items=String()), "enum": Array(unique_items=True, min_items=1), "definitions": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), # String "minLength": Integer(minimum=0), "maxLength": Integer(minimum=0), "pattern": String(format="regex"), "format": String(), # Numeric "minimum": Number(), "maximum": Number(), "exclusiveMinimum": Number(), "exclusiveMaximum": Number(), "multipleOf": Number(exclusive_minimum=0), # Object "properties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "minProperties": Integer(minimum=0), "maxProperties": Integer(minimum=0), "patternProperties": Object( additional_properties=Reference("JSONSchema", definitions=definitions) ), "additionalProperties": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "required": Array(items=String(), unique_items=True), # Array "items": ( Reference("JSONSchema", definitions=definitions) | Array( items=Reference("JSONSchema", definitions=definitions), min_items=1 ) ), "additionalItems": ( Reference("JSONSchema", definitions=definitions) | Boolean() ), "minItems": Integer(minimum=0), "maxItems": Integer(minimum=0), "uniqueItems": Boolean(), } ) | Boolean() ) def to_json_schema( arg: typing.Union[Field, typing.Type[Schema]], _definitions: dict = None ) -> typing.Union[bool, dict]: if isinstance(arg, Any): return True elif isinstance(arg, NeverMatch): return False data: dict = {} is_root = _definitions is None definitions = {} if _definitions is None else _definitions if isinstance(arg, Field): field = arg elif isinstance(arg, SchemaDefinitions): field = None for key, value in arg.items(): definitions[key] = to_json_schema(value, _definitions=definitions) else: field = arg.make_validator() if isinstance(field, Reference): data["$ref"] = f"#/definitions/{field.target_string}" definitions[field.target_string] = to_json_schema( field.target, _definitions=definitions ) elif isinstance(field, String): data["type"] = ["string", "null"] if field.allow_null else "string" data.update(get_standard_properties(field)) if field.min_length is not None or not field.allow_blank: data["minLength"] = field.min_length or 1 if field.max_length is not None: data["maxLength"] = field.max_length if field.pattern_regex is not None: if field.pattern_regex.flags != re.RegexFlag.UNICODE: flags = re.RegexFlag(field.pattern_regex.flags) raise ValueError( f"Cannot convert regular expression with non-standard flags " f"to JSON schema: {flags!s}" ) data["pattern"] = field.pattern_regex.pattern if field.format is not None: data["format"] = field.format elif isinstance(field, (Integer, Float, Decimal)): base_type = "integer" if isinstance(field, Integer) else "number" data["type"] = [base_type, "null"] if field.allow_null else base_type data.update(get_standard_properties(field)) if field.minimum is not None: data["minimum"] = field.minimum if field.maximum is not None: data["maximum"] = field.maximum if field.exclusive_minimum is not None: data["exclusiveMinimum"] = field.exclusive_minimum if field.exclusive_maximum is not None: data["exclusiveMaximum"] = field.exclusive_maximum if field.multiple_of is not None: data["multipleOf"] = field.multiple_of elif isinstance(field, Boolean): data["type"] = ["boolean", "null"] if field.allow_null else "boolean" data.update(get_standard_properties(field)) elif isinstance(field, Array): data["type"] = ["array", "null"] if field.allow_null else "array" data.update(get_standard_properties(field)) if field.min_items is not None: data["minItems"] = field.min_items if field.max_items is not None: data["maxItems"] = field.max_items if field.items is not None: if isinstance(field.items, (list, tuple)): data["items"] = [ to_json_schema(item, _definitions=definitions) for item in field.items ] else: data["items"] = to_json_schema(field.items, _definitions=definitions) if field.additional_items is not None: if isinstance(field.additional_items, bool): data["additionalItems"] = field.additional_items else: data["additionalItems"] = to_json_schema( field.additional_items, _definitions=definitions ) if field.unique_items is not False: data["uniqueItems"] = True elif isinstance(field, Object): data["type"] = ["object", "null"] if field.allow_null else "object" data.update(get_standard_properties(field)) if field.properties: data["properties"] = { key: to_json_schema(value, _definitions=definitions) for key, value in field.properties.items() } if field.pattern_properties: data["patternProperties"] = { key: to_json_schema(value, _definitions=definitions) for key, value in field.pattern_properties.items() } if field.additional_properties is not None: if isinstance(field.additional_properties, bool): data["additionalProperties"] = field.additional_properties else: data["additionalProperties"] = to_json_schema( field.additional_properties, _definitions=definitions ) if field.property_names is not None: data["propertyNames"] = to_json_schema( field.property_names, _definitions=definitions ) if field.max_properties is not None: data["maxProperties"] = field.max_properties if field.min_properties is not None: data["minProperties"] = field.min_properties if field.required: data["required"] = field.required elif isinstance(field, Choice): data["enum"] = [key for key, value in field.choices] data.update(get_standard_properties(field)) elif isinstance(field, Const): data["const"] = field.const data.update(get_standard_properties(field)) elif isinstance(field, Union): data["anyOf"] = [ to_json_schema(item, _definitions=definitions) for item in field.any_of ] data.update(get_standard_properties(field)) elif isinstance(field, OneOf): data["oneOf"] = [ to_json_schema(item, _definitions=definitions) for item in field.one_of ] data.update(get_standard_properties(field)) elif isinstance(field, AllOf): data["allOf"] = [ to_json_schema(item, _definitions=definitions) for item in field.all_of ] data.update(get_standard_properties(field)) elif isinstance(field, IfThenElse): data["if"] = to_json_schema(field.if_clause, _definitions=definitions) if field.then_clause is not None: data["then"] = to_json_schema(field.then_clause, _definitions=definitions) if field.else_clause is not None: data["else"] = to_json_schema(field.else_clause, _definitions=definitions) data.update(get_standard_properties(field)) elif isinstance(field, Not): data["not"] = to_json_schema(field.negated, _definitions=definitions) data.update(get_standard_properties(field)) elif field is not None: name = type(field).__qualname__ raise ValueError(f"Cannot convert field type {name!r} to JSON Schema") if is_root and definitions: data["definitions"] = definitions return data
true
2
851
typesystem
typesystem.schemas
set_definitions
def set_definitions(field: Field, definitions: SchemaDefinitions) -> None: """ Recursively set the definitions that string-referenced `Reference` fields should use. """ if isinstance(field, Reference) and field.definitions is None: field.definitions = definitions elif isinstance(field, Array): if field.items is not None: if isinstance(field.items, (tuple, list)): for child in field.items: set_definitions(child, definitions) else: set_definitions(field.items, definitions) elif isinstance(field, Object): for child in field.properties.values(): set_definitions(child, definitions)
[ 31, 47 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class SchemaDefinitions(MutableMapping): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._definitions = dict(*args, **kwargs) class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._target_string = to else: assert issubclass(to, Schema) self._target = to def set_definitions(field: Field, definitions: SchemaDefinitions) -> None: """ Recursively set the definitions that string-referenced `Reference` fields should use. """ if isinstance(field, Reference) and field.definitions is None: field.definitions = definitions elif isinstance(field, Array): if field.items is not None: if isinstance(field.items, (tuple, list)): for child in field.items: set_definitions(child, definitions) else: set_definitions(field.items, definitions) elif isinstance(field, Object): for child in field.properties.values(): set_definitions(child, definitions)
true
2
852
typesystem
typesystem.schemas
SchemaDefinitions
__setitem__
def __setitem__(self, key: typing.Any, value: typing.Any) -> None: assert ( key not in self._definitions ), r"Definition for {key!r} has already been set." self._definitions[key] = value
[ 21, 25 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class SchemaDefinitions(MutableMapping): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._definitions = dict(*args, **kwargs) def __setitem__(self, key: typing.Any, value: typing.Any) -> None: assert ( key not in self._definitions ), r"Definition for {key!r} has already been set." self._definitions[key] = value
false
0
853
typesystem
typesystem.schemas
SchemaMetaclass
__new__
def __new__( cls: type, name: str, bases: typing.Sequence[type], attrs: dict, definitions: SchemaDefinitions = None, ) -> type: fields: typing.Dict[str, Field] = {} for key, value in list(attrs.items()): if isinstance(value, Field): attrs.pop(key) fields[key] = value # If this class is subclassing other Schema classes, add their fields. for base in reversed(bases): base_fields = getattr(base, "fields", {}) for key, value in base_fields.items(): if isinstance(value, Field) and key not in fields: fields[key] = value # Add the definitions to any `Reference` fields that we're including. if definitions is not None: for field in fields.values(): set_definitions(field, definitions) #  Sort fields by their actual position in the source code, # using `Field._creation_counter` attrs["fields"] = dict( sorted(fields.items(), key=lambda item: item[1]._creation_counter) ) new_type = super(SchemaMetaclass, cls).__new__( # type: ignore cls, name, bases, attrs ) if definitions is not None: definitions[name] = new_type return new_type
[ 51, 88 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class SchemaDefinitions(MutableMapping): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: self._definitions = dict(*args, **kwargs) class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._target_string = to else: assert issubclass(to, Schema) self._target = to class SchemaMetaclass(ABCMeta): def __new__( cls: type, name: str, bases: typing.Sequence[type], attrs: dict, definitions: SchemaDefinitions = None, ) -> type: fields: typing.Dict[str, Field] = {} for key, value in list(attrs.items()): if isinstance(value, Field): attrs.pop(key) fields[key] = value # If this class is subclassing other Schema classes, add their fields. for base in reversed(bases): base_fields = getattr(base, "fields", {}) for key, value in base_fields.items(): if isinstance(value, Field) and key not in fields: fields[key] = value # Add the definitions to any `Reference` fields that we're including. if definitions is not None: for field in fields.values(): set_definitions(field, definitions) #  Sort fields by their actual position in the source code, # using `Field._creation_counter` attrs["fields"] = dict( sorted(fields.items(), key=lambda item: item[1]._creation_counter) ) new_type = super(SchemaMetaclass, cls).__new__( # type: ignore cls, name, bases, attrs ) if definitions is not None: definitions[name] = new_type return new_type
true
2
854
typesystem
typesystem.schemas
Schema
__init__
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message)
[ 94, 130 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message)
true
2
855
typesystem
typesystem.schemas
Schema
__eq__
def __eq__(self, other: typing.Any) -> bool: if not isinstance(other, self.__class__): return False for key in self.fields.keys(): if getattr(self, key) != getattr(other, key): return False return True
[ 165, 172 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) def __eq__(self, other: typing.Any) -> bool: if not isinstance(other, self.__class__): return False for key in self.fields.keys(): if getattr(self, key) != getattr(other, key): return False return True
true
2
856
typesystem
typesystem.schemas
Schema
__getitem__
def __getitem__(self, key: typing.Any) -> typing.Any: try: field = self.fields[key] value = getattr(self, key) except (KeyError, AttributeError): raise KeyError(key) from None else: return field.serialize(value)
[ 174, 181 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) def __getitem__(self, key: typing.Any) -> typing.Any: try: field = self.fields[key] value = getattr(self, key) except (KeyError, AttributeError): raise KeyError(key) from None else: return field.serialize(value)
false
0
857
typesystem
typesystem.schemas
Schema
__iter__
def __iter__(self) -> typing.Iterator[str]: for key in self.fields: if hasattr(self, key): yield key
[ 183, 186 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) def __iter__(self) -> typing.Iterator[str]: for key in self.fields: if hasattr(self, key): yield key
true
2
858
typesystem
typesystem.schemas
Schema
__len__
def __len__(self) -> int: return len([key for key in self.fields if hasattr(self, key)])
[ 188, 189 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) def __len__(self) -> int: return len([key for key in self.fields if hasattr(self, key)])
false
0
859
typesystem
typesystem.schemas
Schema
__repr__
def __repr__(self) -> str: class_name = self.__class__.__name__ arguments = { key: getattr(self, key) for key in self.fields.keys() if hasattr(self, key) } argument_str = ", ".join( [f"{key}={value!r}" for key, value in arguments.items()] ) sparse_indicator = " [sparse]" if self.is_sparse else "" return f"{class_name}({argument_str}){sparse_indicator}"
[ 191, 200 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) def __repr__(self) -> str: class_name = self.__class__.__name__ arguments = { key: getattr(self, key) for key in self.fields.keys() if hasattr(self, key) } argument_str = ", ".join( [f"{key}={value!r}" for key, value in arguments.items()] ) sparse_indicator = " [sparse]" if self.is_sparse else "" return f"{class_name}({argument_str}){sparse_indicator}"
false
0
860
typesystem
typesystem.schemas
Reference
__init__
def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._target_string = to else: assert issubclass(to, Schema) self._target = to
[ 206, 219 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Schema(Mapping, metaclass=SchemaMetaclass): fields: typing.Dict[str, Field] = {} def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if args: assert len(args) == 1 assert not kwargs item = args[0] if isinstance(item, dict): for key in self.fields.keys(): if key in item: setattr(self, key, item[key]) else: for key in self.fields.keys(): if hasattr(item, key): setattr(self, key, getattr(item, key)) return for key, schema in self.fields.items(): if key in kwargs: value = kwargs.pop(key) value, error = schema.validate_or_error(value) if error: class_name = self.__class__.__name__ error_text = " ".join( [message.text for message in error.messages()] ) message = ( f"Invalid argument {key!r} for {class_name}(). {error_text}" ) raise TypeError(message) setattr(self, key, value) elif schema.has_default(): setattr(self, key, schema.get_default_value()) if kwargs: key = list(kwargs.keys())[0] class_name = self.__class__.__name__ message = f"{key!r} is an invalid keyword argument for {class_name}()." raise TypeError(message) class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._target_string = to else: assert issubclass(to, Schema) self._target = to
true
2
861
typesystem
typesystem.schemas
Reference
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") return self.target.validate(value, strict=strict)
[ 236, 241 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._target_string = to else: assert issubclass(to, Schema) self._target = to def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") return self.target.validate(value, strict=strict)
true
2
862
typesystem
typesystem.schemas
Reference
serialize
def serialize(self, obj: typing.Any) -> typing.Any: if obj is None: return None return dict(obj)
[ 243, 246 ]
false
[]
import typing from abc import ABCMeta from collections.abc import Mapping, MutableMapping from typesystem.base import ValidationError, ValidationResult from typesystem.fields import Array, Field, Object class Reference(Field): errors = {"null": "May not be null."} def __init__( self, to: typing.Union[str, typing.Type[Schema]], definitions: typing.Mapping = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.to = to self.definitions = definitions if isinstance(to, str): self._target_string = to else: assert issubclass(to, Schema) self._target = to def serialize(self, obj: typing.Any) -> typing.Any: if obj is None: return None return dict(obj)
true
2
863
typesystem
typesystem.tokenize.positional_validation
validate_with_positions
def validate_with_positions( *, token: Token, validator: typing.Union[Field, typing.Type[Schema]] ) -> typing.Any: try: return validator.validate(token.value) except ValidationError as error: messages = [] for message in error.messages(): if message.code == "required": field = message.index[-1] token = token.lookup(message.index[:-1]) text = f"The field {field!r} is required." else: token = token.lookup(message.index) text = message.text positional_message = Message( text=text, code=message.code, index=message.index, start_position=token.start, end_position=token.end, ) messages.append(positional_message) messages = sorted( messages, key=lambda m: m.start_position.char_index # type: ignore ) raise ValidationError(messages=messages)
[ 8, 35 ]
false
[]
import typing from typesystem.base import Message, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.tokens import Token def validate_with_positions( *, token: Token, validator: typing.Union[Field, typing.Type[Schema]] ) -> typing.Any: try: return validator.validate(token.value) except ValidationError as error: messages = [] for message in error.messages(): if message.code == "required": field = message.index[-1] token = token.lookup(message.index[:-1]) text = f"The field {field!r} is required." else: token = token.lookup(message.index) text = message.text positional_message = Message( text=text, code=message.code, index=message.index, start_position=token.start, end_position=token.end, ) messages.append(positional_message) messages = sorted( messages, key=lambda m: m.start_position.char_index # type: ignore ) raise ValidationError(messages=messages)
true
2
864
typesystem
typesystem.tokenize.tokenize_json
tokenize_json
def tokenize_json(content: typing.Union[str, bytes]) -> Token: if isinstance(content, bytes): content = content.decode("utf-8", "ignore") if not content.strip(): # Handle the empty string case explicitly for clear error messaging. position = Position(column_no=1, line_no=1, char_index=0) raise ParseError(text="No content.", code="no_content", position=position) decoder = _TokenizingDecoder(content=content) try: return decoder.decode(content) except JSONDecodeError as exc: # Handle cases that result in a JSON parse error. position = Position(column_no=exc.colno, line_no=exc.lineno, char_index=exc.pos) raise ParseError(text=exc.msg + ".", code="parse_error", position=position)
[ 164, 179 ]
false
[ "FLAGS", "WHITESPACE", "WHITESPACE_STR", "NUMBER_RE" ]
import re import typing from json.decoder import JSONDecodeError, JSONDecoder, scanstring from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions from typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL WHITESPACE = re.compile(r"[ \t\n\r]*", FLAGS) WHITESPACE_STR = " \t\n\r" NUMBER_RE = re.compile( r"(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?", (re.VERBOSE | re.MULTILINE | re.DOTALL), ) class _TokenizingDecoder(JSONDecoder): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: content = kwargs.pop("content") super().__init__(*args, **kwargs) self.scan_once = _make_scanner(self, content) def tokenize_json(content: typing.Union[str, bytes]) -> Token: if isinstance(content, bytes): content = content.decode("utf-8", "ignore") if not content.strip(): # Handle the empty string case explicitly for clear error messaging. position = Position(column_no=1, line_no=1, char_index=0) raise ParseError(text="No content.", code="no_content", position=position) decoder = _TokenizingDecoder(content=content) try: return decoder.decode(content) except JSONDecodeError as exc: # Handle cases that result in a JSON parse error. position = Position(column_no=exc.colno, line_no=exc.lineno, char_index=exc.pos) raise ParseError(text=exc.msg + ".", code="parse_error", position=position)
true
2
865
typesystem
typesystem.tokenize.tokenize_json
validate_json
def validate_json( content: typing.Union[str, bytes], validator: typing.Union[Field, typing.Type[Schema]], ) -> typing.Any: """ Parse and validate a JSON string, returning positionally marked error messages on parse or validation failures. content - A JSON string or bytestring. validator - A Field instance or Schema class to validate against. Returns a two-tuple of (value, error_messages) """ token = tokenize_json(content) return validate_with_positions(token=token, validator=validator)
[ 182, 196 ]
false
[ "FLAGS", "WHITESPACE", "WHITESPACE_STR", "NUMBER_RE" ]
import re import typing from json.decoder import JSONDecodeError, JSONDecoder, scanstring from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions from typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL WHITESPACE = re.compile(r"[ \t\n\r]*", FLAGS) WHITESPACE_STR = " \t\n\r" NUMBER_RE = re.compile( r"(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?", (re.VERBOSE | re.MULTILINE | re.DOTALL), ) def validate_json( content: typing.Union[str, bytes], validator: typing.Union[Field, typing.Type[Schema]], ) -> typing.Any: """ Parse and validate a JSON string, returning positionally marked error messages on parse or validation failures. content - A JSON string or bytestring. validator - A Field instance or Schema class to validate against. Returns a two-tuple of (value, error_messages) """ token = tokenize_json(content) return validate_with_positions(token=token, validator=validator)
false
0
866
typesystem
typesystem.tokenize.tokenize_yaml
tokenize_yaml
def tokenize_yaml(content: typing.Union[str, bytes]) -> Token: assert yaml is not None, "'pyyaml' must be installed." if isinstance(content, bytes): str_content = content.decode("utf-8", "ignore") else: str_content = content if not str_content.strip(): # Handle the empty string case explicitly for clear error messaging. position = Position(column_no=1, line_no=1, char_index=0) raise ParseError(text="No content.", code="no_content", position=position) class CustomSafeLoader(SafeLoader): pass def construct_mapping(loader: "yaml.Loader", node: "yaml.Node") -> DictToken: start = node.start_mark.index end = node.end_mark.index mapping = loader.construct_mapping(node) return DictToken(mapping, start, end - 1, content=str_content) def construct_sequence(loader: "yaml.Loader", node: "yaml.Node") -> ListToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_sequence(node) return ListToken(value, start, end - 1, content=str_content) def construct_scalar(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_scalar(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_int(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_int(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_float(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_float(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_bool(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_bool(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_null(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_null(node) return ScalarToken(value, start, end - 1, content=str_content) CustomSafeLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping ) CustomSafeLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_SEQUENCE_TAG, construct_sequence ) CustomSafeLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, construct_scalar ) CustomSafeLoader.add_constructor("tag:yaml.org,2002:int", construct_int) CustomSafeLoader.add_constructor("tag:yaml.org,2002:float", construct_float) CustomSafeLoader.add_constructor("tag:yaml.org,2002:bool", construct_bool) CustomSafeLoader.add_constructor("tag:yaml.org,2002:null", construct_null) try: return yaml.load(str_content, CustomSafeLoader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as exc: # type: ignore # Handle cases that result in a YAML parse error. text = exc.problem + "." position = _get_position(str_content, index=exc.problem_mark.index) raise ParseError(text=text, code="parse_error", position=position)
[ 24, 108 ]
false
[]
import typing from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions from typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token def tokenize_yaml(content: typing.Union[str, bytes]) -> Token: assert yaml is not None, "'pyyaml' must be installed." if isinstance(content, bytes): str_content = content.decode("utf-8", "ignore") else: str_content = content if not str_content.strip(): # Handle the empty string case explicitly for clear error messaging. position = Position(column_no=1, line_no=1, char_index=0) raise ParseError(text="No content.", code="no_content", position=position) class CustomSafeLoader(SafeLoader): pass def construct_mapping(loader: "yaml.Loader", node: "yaml.Node") -> DictToken: start = node.start_mark.index end = node.end_mark.index mapping = loader.construct_mapping(node) return DictToken(mapping, start, end - 1, content=str_content) def construct_sequence(loader: "yaml.Loader", node: "yaml.Node") -> ListToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_sequence(node) return ListToken(value, start, end - 1, content=str_content) def construct_scalar(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_scalar(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_int(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_int(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_float(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_float(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_bool(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_bool(node) return ScalarToken(value, start, end - 1, content=str_content) def construct_null(loader: "yaml.Loader", node: "yaml.Node") -> ScalarToken: start = node.start_mark.index end = node.end_mark.index value = loader.construct_yaml_null(node) return ScalarToken(value, start, end - 1, content=str_content) CustomSafeLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping ) CustomSafeLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_SEQUENCE_TAG, construct_sequence ) CustomSafeLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG, construct_scalar ) CustomSafeLoader.add_constructor("tag:yaml.org,2002:int", construct_int) CustomSafeLoader.add_constructor("tag:yaml.org,2002:float", construct_float) CustomSafeLoader.add_constructor("tag:yaml.org,2002:bool", construct_bool) CustomSafeLoader.add_constructor("tag:yaml.org,2002:null", construct_null) try: return yaml.load(str_content, CustomSafeLoader) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as exc: # type: ignore # Handle cases that result in a YAML parse error. text = exc.problem + "." position = _get_position(str_content, index=exc.problem_mark.index) raise ParseError(text=text, code="parse_error", position=position)
true
2
867
typesystem
typesystem.tokenize.tokenize_yaml
validate_yaml
def validate_yaml( content: typing.Union[str, bytes], validator: typing.Union[Field, typing.Type[Schema]], ) -> typing.Any: """ Parse and validate a YAML string, returning positionally marked error messages on parse or validation failures. content - A YAML string or bytestring. validator - A Field instance or Schema class to validate against. Returns a two-tuple of (value, error_messages) """ assert yaml is not None, "'pyyaml' must be installed." token = tokenize_yaml(content) return validate_with_positions(token=token, validator=validator)
[ 111, 127 ]
false
[]
import typing from typesystem.base import Message, ParseError, Position, ValidationError from typesystem.fields import Field from typesystem.schemas import Schema from typesystem.tokenize.positional_validation import validate_with_positions from typesystem.tokenize.tokens import DictToken, ListToken, ScalarToken, Token def validate_yaml( content: typing.Union[str, bytes], validator: typing.Union[Field, typing.Type[Schema]], ) -> typing.Any: """ Parse and validate a YAML string, returning positionally marked error messages on parse or validation failures. content - A YAML string or bytestring. validator - A Field instance or Schema class to validate against. Returns a two-tuple of (value, error_messages) """ assert yaml is not None, "'pyyaml' must be installed." token = tokenize_yaml(content) return validate_with_positions(token=token, validator=validator)
false
0
868
typesystem
typesystem.tokenize.tokens
Token
__init__
def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content
[ 6, 12 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content
false
0
869
typesystem
typesystem.tokenize.tokens
Token
lookup
def lookup(self, index: list) -> "Token": """ Given an index, lookup a child token within this structure. """ token = self for key in index: token = token._get_child_token(key) return token
[ 39, 46 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content def lookup(self, index: list) -> "Token": """ Given an index, lookup a child token within this structure. """ token = self for key in index: token = token._get_child_token(key) return token
true
2
870
typesystem
typesystem.tokenize.tokens
Token
lookup_key
def lookup_key(self, index: list) -> "Token": """ Given an index, lookup a token for a dictionary key within this structure. """ token = self.lookup(index[:-1]) return token._get_key_token(index[-1])
[ 48, 53 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content def lookup_key(self, index: list) -> "Token": """ Given an index, lookup a token for a dictionary key within this structure. """ token = self.lookup(index[:-1]) return token._get_key_token(index[-1])
false
0
871
typesystem
typesystem.tokenize.tokens
Token
__repr__
def __repr__(self) -> str: return "%s(%s)" % (self.__class__.__name__, repr(self.string))
[ 62, 63 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content def __repr__(self) -> str: return "%s(%s)" % (self.__class__.__name__, repr(self.string))
false
0
872
typesystem
typesystem.tokenize.tokens
Token
__eq__
def __eq__(self, other: typing.Any) -> bool: return isinstance(other, Token) and ( self._get_value() == other._get_value() and self._start_index == other._start_index and self._end_index == other._end_index )
[ 65, 66 ]
false
[]
import typing from typesystem.base import Position class Token: def __init__( self, value: typing.Any, start_index: int, end_index: int, content: str = "" ) -> None: self._value = value self._start_index = start_index self._end_index = end_index self._content = content def __eq__(self, other: typing.Any) -> bool: return isinstance(other, Token) and ( self._get_value() == other._get_value() and self._start_index == other._start_index and self._end_index == other._end_index )
false
0
873
typesystem
typesystem.tokenize.tokens
ScalarToken
__hash__
def __hash__(self) -> typing.Any: return hash(self._value)
[ 74, 75 ]
false
[]
import typing from typesystem.base import Position class ScalarToken(Token): def __hash__(self) -> typing.Any: return hash(self._value)
false
0
874
typesystem
typesystem.tokenize.tokens
DictToken
__init__
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: super().__init__(*args, **kwargs) self._child_keys = {k._value: k for k in self._value.keys()} self._child_tokens = {k._value: v for k, v in self._value.items()}
[ 82, 85 ]
false
[]
import typing from typesystem.base import Position class DictToken(Token): def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: super().__init__(*args, **kwargs) self._child_keys = {k._value: k for k in self._value.keys()} self._child_tokens = {k._value: v for k, v in self._value.items()}
false
0
875
youtube_dl
youtube_dl.aes
aes_ctr_decrypt
def aes_ctr_decrypt(data, key, counter): """ Decrypt with aes in counter mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block) returns the next counter block @returns {int[]} decrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES)) decrypted_data = [] for i in range(block_count): counter_block = counter.next_value() block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] block += [0] * (BLOCK_SIZE_BYTES - len(block)) cipher_counter_block = aes_encrypt(counter_block, expanded_key) decrypted_data += xor(block, cipher_counter_block) decrypted_data = decrypted_data[:len(data)] return decrypted_data
[ 10, 33 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x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14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def aes_ctr_decrypt(data, key, counter): """ Decrypt with aes in counter mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {instance} counter Instance whose next_value function (@returns {int[]} 16-Byte block) returns the next counter block @returns {int[]} decrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES)) decrypted_data = [] for i in range(block_count): counter_block = counter.next_value() block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] block += [0] * (BLOCK_SIZE_BYTES - len(block)) cipher_counter_block = aes_encrypt(counter_block, expanded_key) decrypted_data += xor(block, cipher_counter_block) decrypted_data = decrypted_data[:len(data)] return decrypted_data
true
2
876
youtube_dl
youtube_dl.aes
aes_cbc_decrypt
def aes_cbc_decrypt(data, key, iv): """ Decrypt with aes in CBC mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} decrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES)) decrypted_data = [] previous_cipher_block = iv for i in range(block_count): block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] block += [0] * (BLOCK_SIZE_BYTES - len(block)) decrypted_block = aes_decrypt(block, expanded_key) decrypted_data += xor(decrypted_block, previous_cipher_block) previous_cipher_block = block decrypted_data = decrypted_data[:len(data)] return decrypted_data
[ 36, 59 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E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, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def aes_cbc_decrypt(data, key, iv): """ Decrypt with aes in CBC mode @param {int[]} data cipher @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} decrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES)) decrypted_data = [] previous_cipher_block = iv for i in range(block_count): block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] block += [0] * (BLOCK_SIZE_BYTES - len(block)) decrypted_block = aes_decrypt(block, expanded_key) decrypted_data += xor(decrypted_block, previous_cipher_block) previous_cipher_block = block decrypted_data = decrypted_data[:len(data)] return decrypted_data
true
2
877
youtube_dl
youtube_dl.aes
aes_cbc_encrypt
def aes_cbc_encrypt(data, key, iv): """ Encrypt with aes in CBC mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} encrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES)) encrypted_data = [] previous_cipher_block = iv for i in range(block_count): block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] remaining_length = BLOCK_SIZE_BYTES - len(block) block += [remaining_length] * remaining_length mixed_block = xor(block, previous_cipher_block) encrypted_block = aes_encrypt(mixed_block, expanded_key) encrypted_data += encrypted_block previous_cipher_block = encrypted_block return encrypted_data
[ 62, 87 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, int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, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10, 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba, 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57, 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def aes_cbc_encrypt(data, key, iv): """ Encrypt with aes in CBC mode. Using PKCS#7 padding @param {int[]} data cleartext @param {int[]} key 16/24/32-Byte cipher key @param {int[]} iv 16-Byte IV @returns {int[]} encrypted data """ expanded_key = key_expansion(key) block_count = int(ceil(float(len(data)) / BLOCK_SIZE_BYTES)) encrypted_data = [] previous_cipher_block = iv for i in range(block_count): block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES] remaining_length = BLOCK_SIZE_BYTES - len(block) block += [remaining_length] * remaining_length mixed_block = xor(block, previous_cipher_block) encrypted_block = aes_encrypt(mixed_block, expanded_key) encrypted_data += encrypted_block previous_cipher_block = encrypted_block return encrypted_data
true
2
878
youtube_dl
youtube_dl.aes
key_expansion
def key_expansion(data): """ Generate key schedule @param {int[]} data 16/24/32-Byte cipher key @returns {int[]} 176/208/240-Byte expanded key """ data = data[:] # copy rcon_iteration = 1 key_size_bytes = len(data) expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SIZE_BYTES while len(data) < expanded_key_size_bytes: temp = data[-4:] temp = key_schedule_core(temp, rcon_iteration) rcon_iteration += 1 data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) for _ in range(3): temp = data[-4:] data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) if key_size_bytes == 32: temp = data[-4:] temp = sub_bytes(temp) data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) for _ in range(3 if key_size_bytes == 32 else 2 if key_size_bytes == 24 else 0): temp = data[-4:] data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) data = data[:expanded_key_size_bytes] return data
[ 90, 122 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0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 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba, 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57, 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def key_expansion(data): """ Generate key schedule @param {int[]} data 16/24/32-Byte cipher key @returns {int[]} 176/208/240-Byte expanded key """ data = data[:] # copy rcon_iteration = 1 key_size_bytes = len(data) expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SIZE_BYTES while len(data) < expanded_key_size_bytes: temp = data[-4:] temp = key_schedule_core(temp, rcon_iteration) rcon_iteration += 1 data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) for _ in range(3): temp = data[-4:] data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) if key_size_bytes == 32: temp = data[-4:] temp = sub_bytes(temp) data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) for _ in range(3 if key_size_bytes == 32 else 2 if key_size_bytes == 24 else 0): temp = data[-4:] data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes]) data = data[:expanded_key_size_bytes] return data
true
2
879
youtube_dl
youtube_dl.aes
aes_encrypt
def aes_encrypt(data, expanded_key): """ Encrypt one block with aes @param {int[]} data 16-Byte state @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte cipher """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 data = xor(data, expanded_key[:BLOCK_SIZE_BYTES]) for i in range(1, rounds + 1): data = sub_bytes(data) data = shift_rows(data) if i != rounds: data = mix_columns(data) data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]) return data
[ 125, 143 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 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, 0x73, 0xa7, 0x57, 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def aes_encrypt(data, expanded_key): """ Encrypt one block with aes @param {int[]} data 16-Byte state @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte cipher """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 data = xor(data, expanded_key[:BLOCK_SIZE_BYTES]) for i in range(1, rounds + 1): data = sub_bytes(data) data = shift_rows(data) if i != rounds: data = mix_columns(data) data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]) return data
true
2
880
youtube_dl
youtube_dl.aes
aes_decrypt
def aes_decrypt(data, expanded_key): """ Decrypt one block with aes @param {int[]} data 16-Byte cipher @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte state """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 for i in range(rounds, 0, -1): data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]) if i != rounds: data = mix_columns_inv(data) data = shift_rows_inv(data) data = sub_bytes_inv(data) data = xor(data, expanded_key[:BLOCK_SIZE_BYTES]) return data
[ 146, 164 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB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x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def aes_decrypt(data, expanded_key): """ Decrypt one block with aes @param {int[]} data 16-Byte cipher @param {int[]} expanded_key 176/208/240-Byte expanded key @returns {int[]} 16-Byte state """ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1 for i in range(rounds, 0, -1): data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]) if i != rounds: data = mix_columns_inv(data) data = shift_rows_inv(data) data = sub_bytes_inv(data) data = xor(data, expanded_key[:BLOCK_SIZE_BYTES]) return data
true
2
881
youtube_dl
youtube_dl.aes
aes_decrypt_text
def aes_decrypt_text(data, password, key_size_bytes): """ Decrypt text - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter - The cipher key is retrieved by encrypting the first 16 Byte of 'password' with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's) - Mode of operation is 'counter' @param {str} data Base64 encoded string @param {str,unicode} password Password (will be encoded with utf-8) @param {int} key_size_bytes Possible values: 16 for 128-Bit, 24 for 192-Bit or 32 for 256-Bit @returns {str} Decrypted data """ NONCE_LENGTH_BYTES = 8 data = bytes_to_intlist(compat_b64decode(data)) password = bytes_to_intlist(password.encode('utf-8')) key = password[:key_size_bytes] + [0] * (key_size_bytes - len(password)) key = aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES) nonce = data[:NONCE_LENGTH_BYTES] cipher = data[NONCE_LENGTH_BYTES:] class Counter(object): __value = nonce + [0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES) def next_value(self): temp = self.__value self.__value = inc(self.__value) return temp decrypted_data = aes_ctr_decrypt(cipher, key, Counter()) plaintext = intlist_to_bytes(decrypted_data) return plaintext
[ 167, 202 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6,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b, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def aes_decrypt_text(data, password, key_size_bytes): """ Decrypt text - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter - The cipher key is retrieved by encrypting the first 16 Byte of 'password' with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's) - Mode of operation is 'counter' @param {str} data Base64 encoded string @param {str,unicode} password Password (will be encoded with utf-8) @param {int} key_size_bytes Possible values: 16 for 128-Bit, 24 for 192-Bit or 32 for 256-Bit @returns {str} Decrypted data """ NONCE_LENGTH_BYTES = 8 data = bytes_to_intlist(compat_b64decode(data)) password = bytes_to_intlist(password.encode('utf-8')) key = password[:key_size_bytes] + [0] * (key_size_bytes - len(password)) key = aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES) nonce = data[:NONCE_LENGTH_BYTES] cipher = data[NONCE_LENGTH_BYTES:] class Counter(object): __value = nonce + [0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES) def next_value(self): temp = self.__value self.__value = inc(self.__value) return temp decrypted_data = aes_ctr_decrypt(cipher, key, Counter()) plaintext = intlist_to_bytes(decrypted_data) return plaintext
false
0
882
youtube_dl
youtube_dl.aes
key_schedule_core
def key_schedule_core(data, rcon_iteration): data = rotate(data) data = sub_bytes(data) data[0] = data[0] ^ RCON[rcon_iteration] return data
[ 292, 297 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0x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a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def key_schedule_core(data, rcon_iteration): data = rotate(data) data = sub_bytes(data) data[0] = data[0] ^ RCON[rcon_iteration] return data
false
0
883
youtube_dl
youtube_dl.aes
rijndael_mul
def rijndael_mul(a, b): if(a == 0 or b == 0): return 0 return RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[a] + RIJNDAEL_LOG_TABLE[b]) % 0xFF]
[ 304, 307 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36) SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3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x51, 0xa0, 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def rijndael_mul(a, b): if(a == 0 or b == 0): return 0 return RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[a] + RIJNDAEL_LOG_TABLE[b]) % 0xFF]
true
2
884
youtube_dl
youtube_dl.aes
inc
def inc(data): data = data[:] # copy for i in range(len(data) - 1, -1, -1): if data[i] == 255: data[i] = 0 else: data[i] = data[i] + 1 break return data
[ 349, 357 ]
false
[ "BLOCK_SIZE_BYTES", "RCON", "SBOX", "SBOX_INV", "MIX_COLUMN_MATRIX", "MIX_COLUMN_MATRIX_INV", "RIJNDAEL_EXP_TABLE", "RIJNDAEL_LOG_TABLE", "__all__" ]
from math import ceil from .compat import compat_b64decode from .utils import bytes_to_intlist, intlist_to_bytes BLOCK_SIZE_BYTES = 16 RCON = (0x8d, 0x01, 0x02, 0x04,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c3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba, 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57, 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8, 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0, 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7, 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d, 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1, 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab, 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5, 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07) __all__ = ['aes_encrypt', 'key_expansion', 'aes_ctr_decrypt', 'aes_cbc_decrypt', 'aes_decrypt_text'] def inc(data): data = data[:] # copy for i in range(len(data) - 1, -1, -1): if data[i] == 255: data[i] = 0 else: data[i] = data[i] + 1 break return data
true
2
885
youtube_dl
youtube_dl.downloader.common
FileDownloader
format_seconds
@staticmethod def format_seconds(seconds): (mins, secs) = divmod(seconds, 60) (hours, mins) = divmod(mins, 60) if hours > 99: return '--:--:--' if hours == 0: return '%02d:%02d' % (mins, secs) else: return '%02d:%02d:%02d' % (hours, mins, secs)
[ 68, 76 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def format_seconds(seconds): (mins, secs) = divmod(seconds, 60) (hours, mins) = divmod(mins, 60) if hours > 99: return '--:--:--' if hours == 0: return '%02d:%02d' % (mins, secs) else: return '%02d:%02d:%02d' % (hours, mins, secs)
true
2
886
youtube_dl
youtube_dl.downloader.common
FileDownloader
calc_percent
@staticmethod def calc_percent(byte_counter, data_len): if data_len is None: return None return float(byte_counter) / float(data_len) * 100.0
[ 79, 82 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def calc_percent(byte_counter, data_len): if data_len is None: return None return float(byte_counter) / float(data_len) * 100.0
true
2
887
youtube_dl
youtube_dl.downloader.common
FileDownloader
format_percent
@staticmethod def format_percent(percent): if percent is None: return '---.-%' return '%6s' % ('%3.1f%%' % percent)
[ 85, 88 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def format_percent(percent): if percent is None: return '---.-%' return '%6s' % ('%3.1f%%' % percent)
true
2
888
youtube_dl
youtube_dl.downloader.common
FileDownloader
calc_eta
@staticmethod def calc_eta(start, now, total, current): if total is None: return None if now is None: now = time.time() dif = now - start if current == 0 or dif < 0.001: # One millisecond return None rate = float(current) / dif return int((float(total) - float(current)) / rate)
[ 91, 100 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def calc_eta(start, now, total, current): if total is None: return None if now is None: now = time.time() dif = now - start if current == 0 or dif < 0.001: # One millisecond return None rate = float(current) / dif return int((float(total) - float(current)) / rate)
true
2
889
youtube_dl
youtube_dl.downloader.common
FileDownloader
calc_speed
@staticmethod def calc_speed(start, now, bytes): dif = now - start if bytes == 0 or dif < 0.001: # One millisecond return None return float(bytes) / dif
[ 109, 113 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def calc_speed(start, now, bytes): dif = now - start if bytes == 0 or dif < 0.001: # One millisecond return None return float(bytes) / dif
true
2
890
youtube_dl
youtube_dl.downloader.common
FileDownloader
format_retries
@staticmethod def format_retries(retries): return 'inf' if retries == float('inf') else '%.0f' % retries
[ 122, 123 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def format_retries(retries): return 'inf' if retries == float('inf') else '%.0f' % retries
false
0
891
youtube_dl
youtube_dl.downloader.common
FileDownloader
best_block_size
@staticmethod def best_block_size(elapsed_time, bytes): new_min = max(bytes / 2.0, 1.0) new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB if elapsed_time < 0.001: return int(new_max) rate = bytes / elapsed_time if rate > new_max: return int(new_max) if rate < new_min: return int(new_min) return int(rate)
[ 126, 136 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def best_block_size(elapsed_time, bytes): new_min = max(bytes / 2.0, 1.0) new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB if elapsed_time < 0.001: return int(new_max) rate = bytes / elapsed_time if rate > new_max: return int(new_max) if rate < new_min: return int(new_min) return int(rate)
true
2
892
youtube_dl
youtube_dl.downloader.common
FileDownloader
parse_bytes
@staticmethod def parse_bytes(bytestr): """Parse a string indicating a byte quantity into an integer.""" matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr) if matchobj is None: return None number = float(matchobj.group(1)) multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower()) return int(round(number * multiplier))
[ 139, 146 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) @staticmethod def parse_bytes(bytestr): """Parse a string indicating a byte quantity into an integer.""" matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr) if matchobj is None: return None number = float(matchobj.group(1)) multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower()) return int(round(number * multiplier))
true
2
893
youtube_dl
youtube_dl.downloader.common
FileDownloader
slow_down
def slow_down(self, start_time, now, byte_counter): """Sleep if the download speed is over the rate limit.""" rate_limit = self.params.get('ratelimit') if rate_limit is None or byte_counter == 0: return if now is None: now = time.time() elapsed = now - start_time if elapsed <= 0.0: return speed = float(byte_counter) / elapsed if speed > rate_limit: sleep_time = float(byte_counter) / rate_limit - elapsed if sleep_time > 0: time.sleep(sleep_time)
[ 166, 180 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def slow_down(self, start_time, now, byte_counter): """Sleep if the download speed is over the rate limit.""" rate_limit = self.params.get('ratelimit') if rate_limit is None or byte_counter == 0: return if now is None: now = time.time() elapsed = now - start_time if elapsed <= 0.0: return speed = float(byte_counter) / elapsed if speed > rate_limit: sleep_time = float(byte_counter) / rate_limit - elapsed if sleep_time > 0: time.sleep(sleep_time)
true
2
894
youtube_dl
youtube_dl.downloader.common
FileDownloader
temp_name
def temp_name(self, filename): """Returns a temporary filename for the given filename.""" if self.params.get('nopart', False) or filename == '-' or \ (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))): return filename return filename + '.part'
[ 182, 187 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def temp_name(self, filename): """Returns a temporary filename for the given filename.""" if self.params.get('nopart', False) or filename == '-' or \ (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))): return filename return filename + '.part'
true
2
895
youtube_dl
youtube_dl.downloader.common
FileDownloader
undo_temp_name
def undo_temp_name(self, filename): if filename.endswith('.part'): return filename[:-len('.part')] return filename
[ 189, 192 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def undo_temp_name(self, filename): if filename.endswith('.part'): return filename[:-len('.part')] return filename
true
2
896
youtube_dl
youtube_dl.downloader.common
FileDownloader
try_rename
def try_rename(self, old_filename, new_filename): try: if old_filename == new_filename: return os.rename(encodeFilename(old_filename), encodeFilename(new_filename)) except (IOError, OSError) as err: self.report_error('unable to rename file: %s' % error_to_compat_str(err))
[ 197, 203 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def try_rename(self, old_filename, new_filename): try: if old_filename == new_filename: return os.rename(encodeFilename(old_filename), encodeFilename(new_filename)) except (IOError, OSError) as err: self.report_error('unable to rename file: %s' % error_to_compat_str(err))
true
2
897
youtube_dl
youtube_dl.downloader.common
FileDownloader
try_utime
def try_utime(self, filename, last_modified_hdr): """Try to set the last-modified time of the given file.""" if last_modified_hdr is None: return if not os.path.isfile(encodeFilename(filename)): return timestr = last_modified_hdr if timestr is None: return filetime = timeconvert(timestr) if filetime is None: return filetime # Ignore obviously invalid dates if filetime == 0: return try: os.utime(filename, (time.time(), filetime)) except Exception: pass return filetime
[ 205, 224 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def try_utime(self, filename, last_modified_hdr): """Try to set the last-modified time of the given file.""" if last_modified_hdr is None: return if not os.path.isfile(encodeFilename(filename)): return timestr = last_modified_hdr if timestr is None: return filetime = timeconvert(timestr) if filetime is None: return filetime # Ignore obviously invalid dates if filetime == 0: return try: os.utime(filename, (time.time(), filetime)) except Exception: pass return filetime
true
2
898
youtube_dl
youtube_dl.downloader.common
FileDownloader
report_progress
def report_progress(self, s): if s['status'] == 'finished': if self.params.get('noprogress', False): self.to_screen('[download] Download completed') else: msg_template = '100%%' if s.get('total_bytes') is not None: s['_total_bytes_str'] = format_bytes(s['total_bytes']) msg_template += ' of %(_total_bytes_str)s' if s.get('elapsed') is not None: s['_elapsed_str'] = self.format_seconds(s['elapsed']) msg_template += ' in %(_elapsed_str)s' self._report_progress_status( msg_template % s, is_last_line=True) if self.params.get('noprogress'): return if s['status'] != 'downloading': return if s.get('eta') is not None: s['_eta_str'] = self.format_eta(s['eta']) else: s['_eta_str'] = 'Unknown ETA' if s.get('total_bytes') and s.get('downloaded_bytes') is not None: s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes']) elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None: s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate']) else: if s.get('downloaded_bytes') == 0: s['_percent_str'] = self.format_percent(0) else: s['_percent_str'] = 'Unknown %' if s.get('speed') is not None: s['_speed_str'] = self.format_speed(s['speed']) else: s['_speed_str'] = 'Unknown speed' if s.get('total_bytes') is not None: s['_total_bytes_str'] = format_bytes(s['total_bytes']) msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s' elif s.get('total_bytes_estimate') is not None: s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate']) msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s' else: if s.get('downloaded_bytes') is not None: s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes']) if s.get('elapsed'): s['_elapsed_str'] = self.format_seconds(s['elapsed']) msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)' else: msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s' else: msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s' self._report_progress_status(msg_template % s)
[ 247, 305 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def report_progress(self, s): if s['status'] == 'finished': if self.params.get('noprogress', False): self.to_screen('[download] Download completed') else: msg_template = '100%%' if s.get('total_bytes') is not None: s['_total_bytes_str'] = format_bytes(s['total_bytes']) msg_template += ' of %(_total_bytes_str)s' if s.get('elapsed') is not None: s['_elapsed_str'] = self.format_seconds(s['elapsed']) msg_template += ' in %(_elapsed_str)s' self._report_progress_status( msg_template % s, is_last_line=True) if self.params.get('noprogress'): return if s['status'] != 'downloading': return if s.get('eta') is not None: s['_eta_str'] = self.format_eta(s['eta']) else: s['_eta_str'] = 'Unknown ETA' if s.get('total_bytes') and s.get('downloaded_bytes') is not None: s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes']) elif s.get('total_bytes_estimate') and s.get('downloaded_bytes') is not None: s['_percent_str'] = self.format_percent(100 * s['downloaded_bytes'] / s['total_bytes_estimate']) else: if s.get('downloaded_bytes') == 0: s['_percent_str'] = self.format_percent(0) else: s['_percent_str'] = 'Unknown %' if s.get('speed') is not None: s['_speed_str'] = self.format_speed(s['speed']) else: s['_speed_str'] = 'Unknown speed' if s.get('total_bytes') is not None: s['_total_bytes_str'] = format_bytes(s['total_bytes']) msg_template = '%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)s' elif s.get('total_bytes_estimate') is not None: s['_total_bytes_estimate_str'] = format_bytes(s['total_bytes_estimate']) msg_template = '%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)s' else: if s.get('downloaded_bytes') is not None: s['_downloaded_bytes_str'] = format_bytes(s['downloaded_bytes']) if s.get('elapsed'): s['_elapsed_str'] = self.format_seconds(s['elapsed']) msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)' else: msg_template = '%(_downloaded_bytes_str)s at %(_speed_str)s' else: msg_template = '%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s' self._report_progress_status(msg_template % s)
true
2
899
youtube_dl
youtube_dl.downloader.common
FileDownloader
report_file_already_downloaded
def report_file_already_downloaded(self, file_name): """Report file has already been fully downloaded.""" try: self.to_screen('[download] %s has already been downloaded' % file_name) except UnicodeEncodeError: self.to_screen('[download] The file has already been downloaded')
[ 317, 322 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def report_file_already_downloaded(self, file_name): """Report file has already been fully downloaded.""" try: self.to_screen('[download] %s has already been downloaded' % file_name) except UnicodeEncodeError: self.to_screen('[download] The file has already been downloaded')
false
0
900
youtube_dl
youtube_dl.downloader.common
FileDownloader
download
def download(self, filename, info_dict): """Download to a filename using the info from info_dict Return True on success and False otherwise """ nooverwrites_and_exists = ( self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)) ) if not hasattr(filename, 'write'): continuedl_and_exists = ( self.params.get('continuedl', True) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False) ) # Check file already present if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists): self.report_file_already_downloaded(filename) self._hook_progress({ 'filename': filename, 'status': 'finished', 'total_bytes': os.path.getsize(encodeFilename(filename)), }) return True min_sleep_interval = self.params.get('sleep_interval') if min_sleep_interval: max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval) sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval) self.to_screen( '[download] Sleeping %s seconds...' % ( int(sleep_interval) if sleep_interval.is_integer() else '%.2f' % sleep_interval)) time.sleep(sleep_interval) return self.real_download(filename, info_dict)
[ 328, 365 ]
false
[]
import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): _TEST_FILE_SIZE = 10241 params = None def __init__(self, ydl, params): """Create a FileDownloader object with the given options.""" self.ydl = ydl self._progress_hooks = [] self.params = params self.add_progress_hook(self.report_progress) def download(self, filename, info_dict): """Download to a filename using the info from info_dict Return True on success and False otherwise """ nooverwrites_and_exists = ( self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)) ) if not hasattr(filename, 'write'): continuedl_and_exists = ( self.params.get('continuedl', True) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False) ) # Check file already present if filename != '-' and (nooverwrites_and_exists or continuedl_and_exists): self.report_file_already_downloaded(filename) self._hook_progress({ 'filename': filename, 'status': 'finished', 'total_bytes': os.path.getsize(encodeFilename(filename)), }) return True min_sleep_interval = self.params.get('sleep_interval') if min_sleep_interval: max_sleep_interval = self.params.get('max_sleep_interval', min_sleep_interval) sleep_interval = random.uniform(min_sleep_interval, max_sleep_interval) self.to_screen( '[download] Sleeping %s seconds...' % ( int(sleep_interval) if sleep_interval.is_integer() else '%.2f' % sleep_interval)) time.sleep(sleep_interval) return self.real_download(filename, info_dict)
true
2
901
youtube_dl
youtube_dl.downloader.dash
DashSegmentsFD
real_download
def real_download(self, filename, info_dict): fragment_base_url = info_dict.get('fragment_base_url') fragments = info_dict['fragments'][:1] if self.params.get( 'test', False) else info_dict['fragments'] ctx = { 'filename': filename, 'total_frags': len(fragments), } self._prepare_and_start_frag_download(ctx) fragment_retries = self.params.get('fragment_retries', 0) skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) frag_index = 0 for i, fragment in enumerate(fragments): frag_index += 1 if frag_index <= ctx['fragment_index']: continue # In DASH, the first segment contains necessary headers to # generate a valid MP4 file, so always abort for the first segment fatal = i == 0 or not skip_unavailable_fragments count = 0 while count <= fragment_retries: try: fragment_url = fragment.get('url') if not fragment_url: assert fragment_base_url fragment_url = urljoin(fragment_base_url, fragment['path']) success, frag_content = self._download_fragment(ctx, fragment_url, info_dict) if not success: return False self._append_fragment(ctx, frag_content) break except compat_urllib_error.HTTPError as err: # YouTube may often return 404 HTTP error for a fragment causing the # whole download to fail. However if the same fragment is immediately # retried with the same request data this usually succeeds (1-2 attempts # is usually enough) thus allowing to download the whole file successfully. # To be future-proof we will retry all fragments that fail with any # HTTP error. count += 1 if count <= fragment_retries: self.report_retry_fragment(err, frag_index, count, fragment_retries) except DownloadError: # Don't retry fragment if error occurred during HTTP downloading # itself since it has own retry settings if not fatal: self.report_skip_fragment(frag_index) break raise if count > fragment_retries: if not fatal: self.report_skip_fragment(frag_index) continue self.report_error('giving up after %s fragment retries' % fragment_retries) return False self._finish_frag_download(ctx) return True
[ 17, 79 ]
false
[]
from .fragment import FragmentFD from ..compat import compat_urllib_error from ..utils import ( DownloadError, urljoin, ) class DashSegmentsFD(FragmentFD): FD_NAME = 'dashsegments' def real_download(self, filename, info_dict): fragment_base_url = info_dict.get('fragment_base_url') fragments = info_dict['fragments'][:1] if self.params.get( 'test', False) else info_dict['fragments'] ctx = { 'filename': filename, 'total_frags': len(fragments), } self._prepare_and_start_frag_download(ctx) fragment_retries = self.params.get('fragment_retries', 0) skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) frag_index = 0 for i, fragment in enumerate(fragments): frag_index += 1 if frag_index <= ctx['fragment_index']: continue # In DASH, the first segment contains necessary headers to # generate a valid MP4 file, so always abort for the first segment fatal = i == 0 or not skip_unavailable_fragments count = 0 while count <= fragment_retries: try: fragment_url = fragment.get('url') if not fragment_url: assert fragment_base_url fragment_url = urljoin(fragment_base_url, fragment['path']) success, frag_content = self._download_fragment(ctx, fragment_url, info_dict) if not success: return False self._append_fragment(ctx, frag_content) break except compat_urllib_error.HTTPError as err: # YouTube may often return 404 HTTP error for a fragment causing the # whole download to fail. However if the same fragment is immediately # retried with the same request data this usually succeeds (1-2 attempts # is usually enough) thus allowing to download the whole file successfully. # To be future-proof we will retry all fragments that fail with any # HTTP error. count += 1 if count <= fragment_retries: self.report_retry_fragment(err, frag_index, count, fragment_retries) except DownloadError: # Don't retry fragment if error occurred during HTTP downloading # itself since it has own retry settings if not fatal: self.report_skip_fragment(frag_index) break raise if count > fragment_retries: if not fatal: self.report_skip_fragment(frag_index) continue self.report_error('giving up after %s fragment retries' % fragment_retries) return False self._finish_frag_download(ctx) return True
true
2
902
youtube_dl
youtube_dl.downloader.f4m
build_fragments_list
def build_fragments_list(boot_info): """ Return a list of (segment, fragment) for each fragment in the video """ res = [] segment_run_table = boot_info['segments'][0] fragment_run_entry_table = boot_info['fragments'][0]['fragments'] first_frag_number = fragment_run_entry_table[0]['first'] fragments_counter = itertools.count(first_frag_number) for segment, fragments_count in segment_run_table['segment_run']: # In some live HDS streams (for example Rai), `fragments_count` is # abnormal and causing out-of-memory errors. It's OK to change the # number of fragments for live streams as they are updated periodically if fragments_count == 4294967295 and boot_info['live']: fragments_count = 2 for _ in range(fragments_count): res.append((segment, next(fragments_counter))) if boot_info['live']: res = res[-2:] return res
[ 187, 206 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) def build_fragments_list(boot_info): """ Return a list of (segment, fragment) for each fragment in the video """ res = [] segment_run_table = boot_info['segments'][0] fragment_run_entry_table = boot_info['fragments'][0]['fragments'] first_frag_number = fragment_run_entry_table[0]['first'] fragments_counter = itertools.count(first_frag_number) for segment, fragments_count in segment_run_table['segment_run']: # In some live HDS streams (for example Rai), `fragments_count` is # abnormal and causing out-of-memory errors. It's OK to change the # number of fragments for live streams as they are updated periodically if fragments_count == 4294967295 and boot_info['live']: fragments_count = 2 for _ in range(fragments_count): res.append((segment, next(fragments_counter))) if boot_info['live']: res = res[-2:] return res
true
2
903
youtube_dl
youtube_dl.downloader.f4m
write_flv_header
def write_flv_header(stream): """Writes the FLV header to stream""" # FLV header stream.write(b'FLV\x01') stream.write(b'\x05') stream.write(b'\x00\x00\x00\x09') stream.write(b'\x00\x00\x00\x00')
[ 217, 223 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) def write_flv_header(stream): """Writes the FLV header to stream""" # FLV header stream.write(b'FLV\x01') stream.write(b'\x05') stream.write(b'\x00\x00\x00\x09') stream.write(b'\x00\x00\x00\x00')
false
0
904
youtube_dl
youtube_dl.downloader.f4m
write_metadata_tag
def write_metadata_tag(stream, metadata): """Writes optional metadata tag to stream""" SCRIPT_TAG = b'\x12' FLV_TAG_HEADER_LEN = 11 if metadata: stream.write(SCRIPT_TAG) write_unsigned_int_24(stream, len(metadata)) stream.write(b'\x00\x00\x00\x00\x00\x00\x00') stream.write(metadata) write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
[ 226, 236 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) def write_metadata_tag(stream, metadata): """Writes optional metadata tag to stream""" SCRIPT_TAG = b'\x12' FLV_TAG_HEADER_LEN = 11 if metadata: stream.write(SCRIPT_TAG) write_unsigned_int_24(stream, len(metadata)) stream.write(b'\x00\x00\x00\x00\x00\x00\x00') stream.write(metadata) write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
true
2
905
youtube_dl
youtube_dl.downloader.f4m
remove_encrypted_media
def remove_encrypted_media(media): return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and 'drmAdditionalHeaderSetId' not in e.attrib, media))
[ 239, 240 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) def remove_encrypted_media(media): return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and 'drmAdditionalHeaderSetId' not in e.attrib, media))
false
0
906
youtube_dl
youtube_dl.downloader.f4m
get_base_url
def get_base_url(manifest): base_url = xpath_text( manifest, [_add_ns('baseURL'), _add_ns('baseURL', 2)], 'base URL', default=None) if base_url: base_url = base_url.strip() return base_url
[ 249, 255 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) def get_base_url(manifest): base_url = xpath_text( manifest, [_add_ns('baseURL'), _add_ns('baseURL', 2)], 'base URL', default=None) if base_url: base_url = base_url.strip() return base_url
true
2
907
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_string
def read_string(self): res = b'' while True: char = self.read_bytes(1) if char == b'\x00': break res += char return res
[ 50, 57 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class FlvReader(io.BytesIO): def read_string(self): res = b'' while True: char = self.read_bytes(1) if char == b'\x00': break res += char return res
true
2
908
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_box_info
def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_data) """ real_size = size = self.read_unsigned_int() box_type = self.read_bytes(4) header_end = 8 if size == 1: real_size = self.read_unsigned_long_long() header_end = 16 return real_size, box_type, self.read_bytes(real_size - header_end)
[ 59, 69 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class FlvReader(io.BytesIO): def read_box_info(self): """ Read a box and return the info as a tuple: (box_size, box_type, box_data) """ real_size = size = self.read_unsigned_int() box_type = self.read_bytes(4) header_end = 8 if size == 1: real_size = self.read_unsigned_long_long() header_end = 16 return real_size, box_type, self.read_bytes(real_size - header_end)
true
2
909
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_asrt
def read_asrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) quality_entry_count = self.read_unsigned_char() # QualityEntryCount for i in range(quality_entry_count): self.read_string() segment_run_count = self.read_unsigned_int() segments = [] for i in range(segment_run_count): first_segment = self.read_unsigned_int() fragments_per_segment = self.read_unsigned_int() segments.append((first_segment, fragments_per_segment)) return { 'segment_run': segments, }
[ 71, 88 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class FlvReader(io.BytesIO): def read_asrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) quality_entry_count = self.read_unsigned_char() # QualityEntryCount for i in range(quality_entry_count): self.read_string() segment_run_count = self.read_unsigned_int() segments = [] for i in range(segment_run_count): first_segment = self.read_unsigned_int() fragments_per_segment = self.read_unsigned_int() segments.append((first_segment, fragments_per_segment)) return { 'segment_run': segments, }
true
2
910
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_afrt
def read_afrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) # time scale self.read_unsigned_int() quality_entry_count = self.read_unsigned_char() # QualitySegmentUrlModifiers for i in range(quality_entry_count): self.read_string() fragments_count = self.read_unsigned_int() fragments = [] for i in range(fragments_count): first = self.read_unsigned_int() first_ts = self.read_unsigned_long_long() duration = self.read_unsigned_int() if duration == 0: discontinuity_indicator = self.read_unsigned_char() else: discontinuity_indicator = None fragments.append({ 'first': first, 'ts': first_ts, 'duration': duration, 'discontinuity_indicator': discontinuity_indicator, }) return { 'fragments': fragments, }
[ 92, 122 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class FlvReader(io.BytesIO): def read_afrt(self): # version self.read_unsigned_char() # flags self.read_bytes(3) # time scale self.read_unsigned_int() quality_entry_count = self.read_unsigned_char() # QualitySegmentUrlModifiers for i in range(quality_entry_count): self.read_string() fragments_count = self.read_unsigned_int() fragments = [] for i in range(fragments_count): first = self.read_unsigned_int() first_ts = self.read_unsigned_long_long() duration = self.read_unsigned_int() if duration == 0: discontinuity_indicator = self.read_unsigned_char() else: discontinuity_indicator = None fragments.append({ 'first': first, 'ts': first_ts, 'duration': duration, 'discontinuity_indicator': discontinuity_indicator, }) return { 'fragments': fragments, }
true
2
911
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_abst
def read_abst(self): # version self.read_unsigned_char() # flags self.read_bytes(3) self.read_unsigned_int() # BootstrapinfoVersion # Profile,Live,Update,Reserved flags = self.read_unsigned_char() live = flags & 0x20 != 0 # time scale self.read_unsigned_int() # CurrentMediaTime self.read_unsigned_long_long() # SmpteTimeCodeOffset self.read_unsigned_long_long() self.read_string() # MovieIdentifier server_count = self.read_unsigned_char() # ServerEntryTable for i in range(server_count): self.read_string() quality_count = self.read_unsigned_char() # QualityEntryTable for i in range(quality_count): self.read_string() # DrmData self.read_string() # MetaData self.read_string() segments_count = self.read_unsigned_char() segments = [] for i in range(segments_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b'asrt' segment = FlvReader(box_data).read_asrt() segments.append(segment) fragments_run_count = self.read_unsigned_char() fragments = [] for i in range(fragments_run_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b'afrt' fragments.append(FlvReader(box_data).read_afrt()) return { 'segments': segments, 'fragments': fragments, 'live': live, }
[ 126, 171 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class FlvReader(io.BytesIO): def read_abst(self): # version self.read_unsigned_char() # flags self.read_bytes(3) self.read_unsigned_int() # BootstrapinfoVersion # Profile,Live,Update,Reserved flags = self.read_unsigned_char() live = flags & 0x20 != 0 # time scale self.read_unsigned_int() # CurrentMediaTime self.read_unsigned_long_long() # SmpteTimeCodeOffset self.read_unsigned_long_long() self.read_string() # MovieIdentifier server_count = self.read_unsigned_char() # ServerEntryTable for i in range(server_count): self.read_string() quality_count = self.read_unsigned_char() # QualityEntryTable for i in range(quality_count): self.read_string() # DrmData self.read_string() # MetaData self.read_string() segments_count = self.read_unsigned_char() segments = [] for i in range(segments_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b'asrt' segment = FlvReader(box_data).read_asrt() segments.append(segment) fragments_run_count = self.read_unsigned_char() fragments = [] for i in range(fragments_run_count): box_size, box_type, box_data = self.read_box_info() assert box_type == b'afrt' fragments.append(FlvReader(box_data).read_afrt()) return { 'segments': segments, 'fragments': fragments, 'live': live, }
true
2
912
youtube_dl
youtube_dl.downloader.f4m
FlvReader
read_bootstrap_info
def read_bootstrap_info(self): total_size, box_type, box_data = self.read_box_info() assert box_type == b'abst' return FlvReader(box_data).read_abst()
[ 177, 180 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class FlvReader(io.BytesIO): def read_bootstrap_info(self): total_size, box_type, box_data = self.read_box_info() assert box_type == b'abst' return FlvReader(box_data).read_abst()
false
0
913
youtube_dl
youtube_dl.downloader.f4m
F4mFD
real_download
def real_download(self, filename, info_dict): man_url = info_dict['url'] requested_bitrate = info_dict.get('tbr') self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() # Some manifests may be malformed, e.g. prosiebensat1 generated manifests # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244 # and https://github.com/ytdl-org/youtube-dl/issues/7823) manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip() doc = compat_etree_fromstring(manifest) formats = [(int(f.attrib.get('bitrate', -1)), f) for f in self._get_unencrypted_media(doc)] if requested_bitrate is None or len(formats) == 1: # get the best format formats = sorted(formats, key=lambda f: f[0]) rate, media = formats[-1] else: rate, media = list(filter( lambda f: int(f[0]) == requested_bitrate, formats))[0] # Prefer baseURL for relative URLs as per 11.2 of F4M 3.0 spec. man_base_url = get_base_url(doc) or man_url base_url = compat_urlparse.urljoin(man_base_url, media.attrib['url']) bootstrap_node = doc.find(_add_ns('bootstrapInfo')) boot_info, bootstrap_url = self._parse_bootstrap_node( bootstrap_node, man_base_url) live = boot_info['live'] metadata_node = media.find(_add_ns('metadata')) if metadata_node is not None: metadata = compat_b64decode(metadata_node.text) else: metadata = None fragments_list = build_fragments_list(boot_info) test = self.params.get('test', False) if test: # We only download the first fragment fragments_list = fragments_list[:1] total_frags = len(fragments_list) # For some akamai manifests we'll need to add a query to the fragment url akamai_pv = xpath_text(doc, _add_ns('pv-2.0')) ctx = { 'filename': filename, 'total_frags': total_frags, 'live': live, } self._prepare_frag_download(ctx) dest_stream = ctx['dest_stream'] if ctx['complete_frags_downloaded_bytes'] == 0: write_flv_header(dest_stream) if not live: write_metadata_tag(dest_stream, metadata) base_url_parsed = compat_urllib_parse_urlparse(base_url) self._start_frag_download(ctx) frag_index = 0 while fragments_list: seg_i, frag_i = fragments_list.pop(0) frag_index += 1 if frag_index <= ctx['fragment_index']: continue name = 'Seg%d-Frag%d' % (seg_i, frag_i) query = [] if base_url_parsed.query: query.append(base_url_parsed.query) if akamai_pv: query.append(akamai_pv.strip(';')) if info_dict.get('extra_param_to_segment_url'): query.append(info_dict['extra_param_to_segment_url']) url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query)) try: success, down_data = self._download_fragment(ctx, url_parsed.geturl(), info_dict) if not success: return False reader = FlvReader(down_data) while True: try: _, box_type, box_data = reader.read_box_info() except DataTruncatedError: if test: # In tests, segments may be truncated, and thus # FlvReader may not be able to parse the whole # chunk. If so, write the segment as is # See https://github.com/ytdl-org/youtube-dl/issues/9214 dest_stream.write(down_data) break raise if box_type == b'mdat': self._append_fragment(ctx, box_data) break except (compat_urllib_error.HTTPError, ) as err: if live and (err.code == 404 or err.code == 410): # We didn't keep up with the live window. Continue # with the next available fragment. msg = 'Fragment %d unavailable' % frag_i self.report_warning(msg) fragments_list = [] else: raise if not fragments_list and not test and live and bootstrap_url: fragments_list = self._update_live_fragments(bootstrap_url, frag_i) total_frags += len(fragments_list) if fragments_list and (fragments_list[0][1] > frag_i + 1): msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1)) self.report_warning(msg) self._finish_frag_download(ctx) return True
[ 318, 437 ]
false
[]
import io import itertools import time from .fragment import FragmentFD from ..compat import ( compat_b64decode, compat_etree_fromstring, compat_urlparse, compat_urllib_error, compat_urllib_parse_urlparse, compat_struct_pack, compat_struct_unpack, ) from ..utils import ( fix_xml_ampersands, xpath_text, ) class F4mFD(FragmentFD): FD_NAME = 'f4m' def real_download(self, filename, info_dict): man_url = info_dict['url'] requested_bitrate = info_dict.get('tbr') self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() # Some manifests may be malformed, e.g. prosiebensat1 generated manifests # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244 # and https://github.com/ytdl-org/youtube-dl/issues/7823) manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip() doc = compat_etree_fromstring(manifest) formats = [(int(f.attrib.get('bitrate', -1)), f) for f in self._get_unencrypted_media(doc)] if requested_bitrate is None or len(formats) == 1: # get the best format formats = sorted(formats, key=lambda f: f[0]) rate, media = formats[-1] else: rate, media = list(filter( lambda f: int(f[0]) == requested_bitrate, formats))[0] # Prefer baseURL for relative URLs as per 11.2 of F4M 3.0 spec. man_base_url = get_base_url(doc) or man_url base_url = compat_urlparse.urljoin(man_base_url, media.attrib['url']) bootstrap_node = doc.find(_add_ns('bootstrapInfo')) boot_info, bootstrap_url = self._parse_bootstrap_node( bootstrap_node, man_base_url) live = boot_info['live'] metadata_node = media.find(_add_ns('metadata')) if metadata_node is not None: metadata = compat_b64decode(metadata_node.text) else: metadata = None fragments_list = build_fragments_list(boot_info) test = self.params.get('test', False) if test: # We only download the first fragment fragments_list = fragments_list[:1] total_frags = len(fragments_list) # For some akamai manifests we'll need to add a query to the fragment url akamai_pv = xpath_text(doc, _add_ns('pv-2.0')) ctx = { 'filename': filename, 'total_frags': total_frags, 'live': live, } self._prepare_frag_download(ctx) dest_stream = ctx['dest_stream'] if ctx['complete_frags_downloaded_bytes'] == 0: write_flv_header(dest_stream) if not live: write_metadata_tag(dest_stream, metadata) base_url_parsed = compat_urllib_parse_urlparse(base_url) self._start_frag_download(ctx) frag_index = 0 while fragments_list: seg_i, frag_i = fragments_list.pop(0) frag_index += 1 if frag_index <= ctx['fragment_index']: continue name = 'Seg%d-Frag%d' % (seg_i, frag_i) query = [] if base_url_parsed.query: query.append(base_url_parsed.query) if akamai_pv: query.append(akamai_pv.strip(';')) if info_dict.get('extra_param_to_segment_url'): query.append(info_dict['extra_param_to_segment_url']) url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query)) try: success, down_data = self._download_fragment(ctx, url_parsed.geturl(), info_dict) if not success: return False reader = FlvReader(down_data) while True: try: _, box_type, box_data = reader.read_box_info() except DataTruncatedError: if test: # In tests, segments may be truncated, and thus # FlvReader may not be able to parse the whole # chunk. If so, write the segment as is # See https://github.com/ytdl-org/youtube-dl/issues/9214 dest_stream.write(down_data) break raise if box_type == b'mdat': self._append_fragment(ctx, box_data) break except (compat_urllib_error.HTTPError, ) as err: if live and (err.code == 404 or err.code == 410): # We didn't keep up with the live window. Continue # with the next available fragment. msg = 'Fragment %d unavailable' % frag_i self.report_warning(msg) fragments_list = [] else: raise if not fragments_list and not test and live and bootstrap_url: fragments_list = self._update_live_fragments(bootstrap_url, frag_i) total_frags += len(fragments_list) if fragments_list and (fragments_list[0][1] > frag_i + 1): msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1)) self.report_warning(msg) self._finish_frag_download(ctx) return True
true
2
914
youtube_dl
youtube_dl.downloader.hls
HlsFD
can_download
@staticmethod def can_download(manifest, info_dict): UNSUPPORTED_FEATURES = ( r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1] # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2] # Live streams heuristic does not always work (e.g. geo restricted to Germany # http://hls-geo.daserste.de/i/videoportal/Film/c_620000/622873/format,716451,716457,716450,716458,716459,.mp4.csmil/index_4_av.m3u8?null=0) # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3] # This heuristic also is not correct since segments may not be appended as well. # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite # no segments will definitely be appended to the end of the playlist. # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of # # event media playlists [4] r'#EXT-X-MAP:', # media initialization [5] # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4 # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2 # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2 # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5 # 5. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.5 ) check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES] is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest check_results.append(can_decrypt_frag or not is_aes128_enc) check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest)) check_results.append(not info_dict.get('is_live')) return all(check_results)
[ 30, 57 ]
false
[]
import re import binascii from .fragment import FragmentFD from .external import FFmpegFD from ..compat import ( compat_urllib_error, compat_urlparse, compat_struct_pack, ) from ..utils import ( parse_m3u8_attributes, update_url_query, ) class HlsFD(FragmentFD): FD_NAME = 'hlsnative' @staticmethod def can_download(manifest, info_dict): UNSUPPORTED_FEATURES = ( r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1] # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2] # Live streams heuristic does not always work (e.g. geo restricted to Germany # http://hls-geo.daserste.de/i/videoportal/Film/c_620000/622873/format,716451,716457,716450,716458,716459,.mp4.csmil/index_4_av.m3u8?null=0) # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3] # This heuristic also is not correct since segments may not be appended as well. # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite # no segments will definitely be appended to the end of the playlist. # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of # # event media playlists [4] r'#EXT-X-MAP:', # media initialization [5] # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4 # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2 # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2 # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5 # 5. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.5 ) check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES] is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest check_results.append(can_decrypt_frag or not is_aes128_enc) check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest)) check_results.append(not info_dict.get('is_live')) return all(check_results)
false
0
915
youtube_dl
youtube_dl.downloader.hls
HlsFD
real_download
def real_download(self, filename, info_dict): man_url = info_dict['url'] self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() s = urlh.read().decode('utf-8', 'ignore') if not self.can_download(s, info_dict): if info_dict.get('extra_param_to_segment_url') or info_dict.get('_decryption_key_url'): self.report_error('pycrypto not found. Please install it.') return False self.report_warning( 'hlsnative has detected features it does not support, ' 'extraction will be delegated to ffmpeg') fd = FFmpegFD(self.ydl, self.params) for ph in self._progress_hooks: fd.add_progress_hook(ph) return fd.real_download(filename, info_dict) def is_ad_fragment_start(s): return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad')) def is_ad_fragment_end(s): return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment')) media_frags = 0 ad_frags = 0 ad_frag_next = False for line in s.splitlines(): line = line.strip() if not line: continue if line.startswith('#'): if is_ad_fragment_start(line): ad_frag_next = True elif is_ad_fragment_end(line): ad_frag_next = False continue if ad_frag_next: ad_frags += 1 continue media_frags += 1 ctx = { 'filename': filename, 'total_frags': media_frags, 'ad_frags': ad_frags, } self._prepare_and_start_frag_download(ctx) fragment_retries = self.params.get('fragment_retries', 0) skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) test = self.params.get('test', False) extra_query = None extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url') if extra_param_to_segment_url: extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url) i = 0 media_sequence = 0 decrypt_info = {'METHOD': 'NONE'} byte_range = {} frag_index = 0 ad_frag_next = False for line in s.splitlines(): line = line.strip() if line: if not line.startswith('#'): if ad_frag_next: continue frag_index += 1 if frag_index <= ctx['fragment_index']: continue frag_url = ( line if re.match(r'^https?://', line) else compat_urlparse.urljoin(man_url, line)) if extra_query: frag_url = update_url_query(frag_url, extra_query) count = 0 headers = info_dict.get('http_headers', {}) if byte_range: headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1) while count <= fragment_retries: try: success, frag_content = self._download_fragment( ctx, frag_url, info_dict, headers) if not success: return False break except compat_urllib_error.HTTPError as err: # Unavailable (possibly temporary) fragments may be served. # First we try to retry then either skip or abort. # See https://github.com/ytdl-org/youtube-dl/issues/10165, # https://github.com/ytdl-org/youtube-dl/issues/10448). count += 1 if count <= fragment_retries: self.report_retry_fragment(err, frag_index, count, fragment_retries) if count > fragment_retries: if skip_unavailable_fragments: i += 1 media_sequence += 1 self.report_skip_fragment(frag_index) continue self.report_error( 'giving up after %s fragment retries' % fragment_retries) return False if decrypt_info['METHOD'] == 'AES-128': iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence) decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen( self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read() # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded, # not what it decrypts to. if not test: frag_content = AES.new( decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content) self._append_fragment(ctx, frag_content) # We only download the first fragment during the test if test: break i += 1 media_sequence += 1 elif line.startswith('#EXT-X-KEY'): decrypt_url = decrypt_info.get('URI') decrypt_info = parse_m3u8_attributes(line[11:]) if decrypt_info['METHOD'] == 'AES-128': if 'IV' in decrypt_info: decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32)) if not re.match(r'^https?://', decrypt_info['URI']): decrypt_info['URI'] = compat_urlparse.urljoin( man_url, decrypt_info['URI']) if extra_query: decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query) if decrypt_url != decrypt_info['URI']: decrypt_info['KEY'] = None elif line.startswith('#EXT-X-MEDIA-SEQUENCE'): media_sequence = int(line[22:]) elif line.startswith('#EXT-X-BYTERANGE'): splitted_byte_range = line[17:].split('@') sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end'] byte_range = { 'start': sub_range_start, 'end': sub_range_start + int(splitted_byte_range[0]), } elif is_ad_fragment_start(line): ad_frag_next = True elif is_ad_fragment_end(line): ad_frag_next = False self._finish_frag_download(ctx) return True
[ 59, 215 ]
false
[]
import re import binascii from .fragment import FragmentFD from .external import FFmpegFD from ..compat import ( compat_urllib_error, compat_urlparse, compat_struct_pack, ) from ..utils import ( parse_m3u8_attributes, update_url_query, ) class HlsFD(FragmentFD): FD_NAME = 'hlsnative' def real_download(self, filename, info_dict): man_url = info_dict['url'] self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME) urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url)) man_url = urlh.geturl() s = urlh.read().decode('utf-8', 'ignore') if not self.can_download(s, info_dict): if info_dict.get('extra_param_to_segment_url') or info_dict.get('_decryption_key_url'): self.report_error('pycrypto not found. Please install it.') return False self.report_warning( 'hlsnative has detected features it does not support, ' 'extraction will be delegated to ffmpeg') fd = FFmpegFD(self.ydl, self.params) for ph in self._progress_hooks: fd.add_progress_hook(ph) return fd.real_download(filename, info_dict) def is_ad_fragment_start(s): return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=ad' in s or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',ad')) def is_ad_fragment_end(s): return (s.startswith('#ANVATO-SEGMENT-INFO') and 'type=master' in s or s.startswith('#UPLYNK-SEGMENT') and s.endswith(',segment')) media_frags = 0 ad_frags = 0 ad_frag_next = False for line in s.splitlines(): line = line.strip() if not line: continue if line.startswith('#'): if is_ad_fragment_start(line): ad_frag_next = True elif is_ad_fragment_end(line): ad_frag_next = False continue if ad_frag_next: ad_frags += 1 continue media_frags += 1 ctx = { 'filename': filename, 'total_frags': media_frags, 'ad_frags': ad_frags, } self._prepare_and_start_frag_download(ctx) fragment_retries = self.params.get('fragment_retries', 0) skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) test = self.params.get('test', False) extra_query = None extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url') if extra_param_to_segment_url: extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url) i = 0 media_sequence = 0 decrypt_info = {'METHOD': 'NONE'} byte_range = {} frag_index = 0 ad_frag_next = False for line in s.splitlines(): line = line.strip() if line: if not line.startswith('#'): if ad_frag_next: continue frag_index += 1 if frag_index <= ctx['fragment_index']: continue frag_url = ( line if re.match(r'^https?://', line) else compat_urlparse.urljoin(man_url, line)) if extra_query: frag_url = update_url_query(frag_url, extra_query) count = 0 headers = info_dict.get('http_headers', {}) if byte_range: headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1) while count <= fragment_retries: try: success, frag_content = self._download_fragment( ctx, frag_url, info_dict, headers) if not success: return False break except compat_urllib_error.HTTPError as err: # Unavailable (possibly temporary) fragments may be served. # First we try to retry then either skip or abort. # See https://github.com/ytdl-org/youtube-dl/issues/10165, # https://github.com/ytdl-org/youtube-dl/issues/10448). count += 1 if count <= fragment_retries: self.report_retry_fragment(err, frag_index, count, fragment_retries) if count > fragment_retries: if skip_unavailable_fragments: i += 1 media_sequence += 1 self.report_skip_fragment(frag_index) continue self.report_error( 'giving up after %s fragment retries' % fragment_retries) return False if decrypt_info['METHOD'] == 'AES-128': iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence) decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen( self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read() # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded, # not what it decrypts to. if not test: frag_content = AES.new( decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content) self._append_fragment(ctx, frag_content) # We only download the first fragment during the test if test: break i += 1 media_sequence += 1 elif line.startswith('#EXT-X-KEY'): decrypt_url = decrypt_info.get('URI') decrypt_info = parse_m3u8_attributes(line[11:]) if decrypt_info['METHOD'] == 'AES-128': if 'IV' in decrypt_info: decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32)) if not re.match(r'^https?://', decrypt_info['URI']): decrypt_info['URI'] = compat_urlparse.urljoin( man_url, decrypt_info['URI']) if extra_query: decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query) if decrypt_url != decrypt_info['URI']: decrypt_info['KEY'] = None elif line.startswith('#EXT-X-MEDIA-SEQUENCE'): media_sequence = int(line[22:]) elif line.startswith('#EXT-X-BYTERANGE'): splitted_byte_range = line[17:].split('@') sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end'] byte_range = { 'start': sub_range_start, 'end': sub_range_start + int(splitted_byte_range[0]), } elif is_ad_fragment_start(line): ad_frag_next = True elif is_ad_fragment_end(line): ad_frag_next = False self._finish_frag_download(ctx) return True
true
2
916
youtube_dl
youtube_dl.downloader.http
HttpFD
real_download
def real_download(self, filename, info_dict): url = info_dict['url'] class DownloadContext(dict): __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ ctx = DownloadContext() ctx.filename = filename ctx.tmpfilename = self.temp_name(filename) ctx.stream = None # Do not include the Accept-Encoding header headers = {'Youtubedl-no-compression': 'True'} add_headers = info_dict.get('http_headers') if add_headers: headers.update(add_headers) is_test = self.params.get('test', False) chunk_size = self._TEST_FILE_SIZE if is_test else ( info_dict.get('downloader_options', {}).get('http_chunk_size') or self.params.get('http_chunk_size') or 0) ctx.open_mode = 'wb' ctx.resume_len = 0 ctx.data_len = None ctx.block_size = self.params.get('buffersize', 1024) ctx.start_time = time.time() ctx.chunk_size = None if self.params.get('continuedl', True): # Establish possible resume length if os.path.isfile(encodeFilename(ctx.tmpfilename)): ctx.resume_len = os.path.getsize( encodeFilename(ctx.tmpfilename)) ctx.is_resume = ctx.resume_len > 0 count = 0 retries = self.params.get('retries', 0) class SucceedDownload(Exception): pass class RetryDownload(Exception): def __init__(self, source_error): self.source_error = source_error class NextFragment(Exception): pass def set_range(req, start, end): range_header = 'bytes=%d-' % start if end: range_header += compat_str(end) req.add_header('Range', range_header) def establish_connection(): ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size) if not is_test and chunk_size else chunk_size) if ctx.resume_len > 0: range_start = ctx.resume_len if ctx.is_resume: self.report_resuming_byte(ctx.resume_len) ctx.open_mode = 'ab' elif ctx.chunk_size > 0: range_start = 0 else: range_start = None ctx.is_resume = False range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None if range_end and ctx.data_len is not None and range_end >= ctx.data_len: range_end = ctx.data_len - 1 has_range = range_start is not None ctx.has_range = has_range request = sanitized_Request(url, None, headers) if has_range: set_range(request, range_start, range_end) # Establish connection try: try: ctx.data = self.ydl.urlopen(request) except (compat_urllib_error.URLError, ) as err: # reason may not be available, e.g. for urllib2.HTTPError on python 2.6 reason = getattr(err, 'reason', None) if isinstance(reason, socket.timeout): raise RetryDownload(err) raise err # When trying to resume, Content-Range HTTP header of response has to be checked # to match the value of requested Range HTTP header. This is due to a webservers # that don't support resuming and serve a whole file with no Content-Range # set in response despite of requested Range (see # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799) if has_range: content_range = ctx.data.headers.get('Content-Range') if content_range: content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range) # Content-Range is present and matches requested Range, resume is possible if content_range_m: if range_start == int(content_range_m.group(1)): content_range_end = int_or_none(content_range_m.group(2)) content_len = int_or_none(content_range_m.group(3)) accept_content_len = ( # Non-chunked download not ctx.chunk_size # Chunked download and requested piece or # its part is promised to be served or content_range_end == range_end or content_len < range_end) if accept_content_len: ctx.data_len = content_len return # Content-Range is either not present or invalid. Assuming remote webserver is # trying to send the whole file, resume is not possible, so wiping the local file # and performing entire redownload self.report_unable_to_resume() ctx.resume_len = 0 ctx.open_mode = 'wb' ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None)) return except (compat_urllib_error.HTTPError, ) as err: if err.code == 416: # Unable to resume (requested range not satisfiable) try: # Open the connection again without the range header ctx.data = self.ydl.urlopen( sanitized_Request(url, None, headers)) content_length = ctx.data.info()['Content-Length'] except (compat_urllib_error.HTTPError, ) as err: if err.code < 500 or err.code >= 600: raise else: # Examine the reported length if (content_length is not None and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)): # The file had already been fully downloaded. # Explanation to the above condition: in issue #175 it was revealed that # YouTube sometimes adds or removes a few bytes from the end of the file, # changing the file size slightly and causing problems for some users. So # I decided to implement a suggested change and consider the file # completely downloaded if the file size differs less than 100 bytes from # the one in the hard drive. self.report_file_already_downloaded(ctx.filename) self.try_rename(ctx.tmpfilename, ctx.filename) self._hook_progress({ 'filename': ctx.filename, 'status': 'finished', 'downloaded_bytes': ctx.resume_len, 'total_bytes': ctx.resume_len, }) raise SucceedDownload() else: # The length does not match, we start the download over self.report_unable_to_resume() ctx.resume_len = 0 ctx.open_mode = 'wb' return elif err.code < 500 or err.code >= 600: # Unexpected HTTP error raise raise RetryDownload(err) except socket.error as err: if err.errno != errno.ECONNRESET: # Connection reset is no problem, just retry raise raise RetryDownload(err) def download(): data_len = ctx.data.info().get('Content-length', None) # Range HTTP header may be ignored/unsupported by a webserver # (e.g. extractor/scivee.py, extractor/bambuser.py). # However, for a test we still would like to download just a piece of a file. # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control # block size when downloading a file. if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE): data_len = self._TEST_FILE_SIZE if data_len is not None: data_len = int(data_len) + ctx.resume_len min_data_len = self.params.get('min_filesize') max_data_len = self.params.get('max_filesize') if min_data_len is not None and data_len < min_data_len: self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len)) return False if max_data_len is not None and data_len > max_data_len: self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len)) return False byte_counter = 0 + ctx.resume_len block_size = ctx.block_size start = time.time() # measure time over whole while-loop, so slow_down() and best_block_size() work together properly now = None # needed for slow_down() in the first loop run before = start # start measuring def retry(e): to_stdout = ctx.tmpfilename == '-' if ctx.stream is not None: if not to_stdout: ctx.stream.close() ctx.stream = None ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename)) raise RetryDownload(e) while True: try: # Download and write data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter)) # socket.timeout is a subclass of socket.error but may not have # errno set except socket.timeout as e: retry(e) except socket.error as e: # SSLError on python 2 (inherits socket.error) may have # no errno set but this error message if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out': retry(e) raise byte_counter += len(data_block) # exit loop when download is finished if len(data_block) == 0: break # Open destination file just in time if ctx.stream is None: try: ctx.stream, ctx.tmpfilename = sanitize_open( ctx.tmpfilename, ctx.open_mode) assert ctx.stream is not None ctx.filename = self.undo_temp_name(ctx.tmpfilename) self.report_destination(ctx.filename) except (OSError, IOError) as err: self.report_error('unable to open for writing: %s' % str(err)) return False if self.params.get('xattr_set_filesize', False) and data_len is not None: try: write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8')) except (XAttrUnavailableError, XAttrMetadataError) as err: self.report_error('unable to set filesize xattr: %s' % str(err)) try: ctx.stream.write(data_block) except (IOError, OSError) as err: self.to_stderr('\n') self.report_error('unable to write data: %s' % str(err)) return False # Apply rate limit self.slow_down(start, now, byte_counter - ctx.resume_len) # end measuring of one loop run now = time.time() after = now # Adjust block size if not self.params.get('noresizebuffer', False): block_size = self.best_block_size(after - before, len(data_block)) before = after # Progress message speed = self.calc_speed(start, now, byte_counter - ctx.resume_len) if ctx.data_len is None: eta = None else: eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len) self._hook_progress({ 'status': 'downloading', 'downloaded_bytes': byte_counter, 'total_bytes': ctx.data_len, 'tmpfilename': ctx.tmpfilename, 'filename': ctx.filename, 'eta': eta, 'speed': speed, 'elapsed': now - ctx.start_time, }) if data_len is not None and byte_counter == data_len: break if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len: ctx.resume_len = byte_counter # ctx.block_size = block_size raise NextFragment() if ctx.stream is None: self.to_stderr('\n') self.report_error('Did not get any data blocks') return False if ctx.tmpfilename != '-': ctx.stream.close() if data_len is not None and byte_counter != data_len: err = ContentTooShortError(byte_counter, int(data_len)) if count <= retries: retry(err) raise err self.try_rename(ctx.tmpfilename, ctx.filename) # Update file modification time if self.params.get('updatetime', True): info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None)) self._hook_progress({ 'downloaded_bytes': byte_counter, 'total_bytes': byte_counter, 'filename': ctx.filename, 'status': 'finished', 'elapsed': time.time() - ctx.start_time, }) return True while count <= retries: try: establish_connection() return download() except RetryDownload as e: count += 1 if count <= retries: self.report_retry(e.source_error, count, retries) continue except NextFragment: continue except SucceedDownload: return True self.report_error('giving up after %s retries' % retries) return False
[ 27, 363 ]
false
[]
import errno import os import socket import time import random import re from .common import FileDownloader from ..compat import ( compat_str, compat_urllib_error, ) from ..utils import ( ContentTooShortError, encodeFilename, int_or_none, sanitize_open, sanitized_Request, write_xattr, XAttrMetadataError, XAttrUnavailableError, ) class HttpFD(FileDownloader): def real_download(self, filename, info_dict): url = info_dict['url'] class DownloadContext(dict): __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ ctx = DownloadContext() ctx.filename = filename ctx.tmpfilename = self.temp_name(filename) ctx.stream = None # Do not include the Accept-Encoding header headers = {'Youtubedl-no-compression': 'True'} add_headers = info_dict.get('http_headers') if add_headers: headers.update(add_headers) is_test = self.params.get('test', False) chunk_size = self._TEST_FILE_SIZE if is_test else ( info_dict.get('downloader_options', {}).get('http_chunk_size') or self.params.get('http_chunk_size') or 0) ctx.open_mode = 'wb' ctx.resume_len = 0 ctx.data_len = None ctx.block_size = self.params.get('buffersize', 1024) ctx.start_time = time.time() ctx.chunk_size = None if self.params.get('continuedl', True): # Establish possible resume length if os.path.isfile(encodeFilename(ctx.tmpfilename)): ctx.resume_len = os.path.getsize( encodeFilename(ctx.tmpfilename)) ctx.is_resume = ctx.resume_len > 0 count = 0 retries = self.params.get('retries', 0) class SucceedDownload(Exception): pass class RetryDownload(Exception): def __init__(self, source_error): self.source_error = source_error class NextFragment(Exception): pass def set_range(req, start, end): range_header = 'bytes=%d-' % start if end: range_header += compat_str(end) req.add_header('Range', range_header) def establish_connection(): ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size) if not is_test and chunk_size else chunk_size) if ctx.resume_len > 0: range_start = ctx.resume_len if ctx.is_resume: self.report_resuming_byte(ctx.resume_len) ctx.open_mode = 'ab' elif ctx.chunk_size > 0: range_start = 0 else: range_start = None ctx.is_resume = False range_end = range_start + ctx.chunk_size - 1 if ctx.chunk_size else None if range_end and ctx.data_len is not None and range_end >= ctx.data_len: range_end = ctx.data_len - 1 has_range = range_start is not None ctx.has_range = has_range request = sanitized_Request(url, None, headers) if has_range: set_range(request, range_start, range_end) # Establish connection try: try: ctx.data = self.ydl.urlopen(request) except (compat_urllib_error.URLError, ) as err: # reason may not be available, e.g. for urllib2.HTTPError on python 2.6 reason = getattr(err, 'reason', None) if isinstance(reason, socket.timeout): raise RetryDownload(err) raise err # When trying to resume, Content-Range HTTP header of response has to be checked # to match the value of requested Range HTTP header. This is due to a webservers # that don't support resuming and serve a whole file with no Content-Range # set in response despite of requested Range (see # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799) if has_range: content_range = ctx.data.headers.get('Content-Range') if content_range: content_range_m = re.search(r'bytes (\d+)-(\d+)?(?:/(\d+))?', content_range) # Content-Range is present and matches requested Range, resume is possible if content_range_m: if range_start == int(content_range_m.group(1)): content_range_end = int_or_none(content_range_m.group(2)) content_len = int_or_none(content_range_m.group(3)) accept_content_len = ( # Non-chunked download not ctx.chunk_size # Chunked download and requested piece or # its part is promised to be served or content_range_end == range_end or content_len < range_end) if accept_content_len: ctx.data_len = content_len return # Content-Range is either not present or invalid. Assuming remote webserver is # trying to send the whole file, resume is not possible, so wiping the local file # and performing entire redownload self.report_unable_to_resume() ctx.resume_len = 0 ctx.open_mode = 'wb' ctx.data_len = int_or_none(ctx.data.info().get('Content-length', None)) return except (compat_urllib_error.HTTPError, ) as err: if err.code == 416: # Unable to resume (requested range not satisfiable) try: # Open the connection again without the range header ctx.data = self.ydl.urlopen( sanitized_Request(url, None, headers)) content_length = ctx.data.info()['Content-Length'] except (compat_urllib_error.HTTPError, ) as err: if err.code < 500 or err.code >= 600: raise else: # Examine the reported length if (content_length is not None and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)): # The file had already been fully downloaded. # Explanation to the above condition: in issue #175 it was revealed that # YouTube sometimes adds or removes a few bytes from the end of the file, # changing the file size slightly and causing problems for some users. So # I decided to implement a suggested change and consider the file # completely downloaded if the file size differs less than 100 bytes from # the one in the hard drive. self.report_file_already_downloaded(ctx.filename) self.try_rename(ctx.tmpfilename, ctx.filename) self._hook_progress({ 'filename': ctx.filename, 'status': 'finished', 'downloaded_bytes': ctx.resume_len, 'total_bytes': ctx.resume_len, }) raise SucceedDownload() else: # The length does not match, we start the download over self.report_unable_to_resume() ctx.resume_len = 0 ctx.open_mode = 'wb' return elif err.code < 500 or err.code >= 600: # Unexpected HTTP error raise raise RetryDownload(err) except socket.error as err: if err.errno != errno.ECONNRESET: # Connection reset is no problem, just retry raise raise RetryDownload(err) def download(): data_len = ctx.data.info().get('Content-length', None) # Range HTTP header may be ignored/unsupported by a webserver # (e.g. extractor/scivee.py, extractor/bambuser.py). # However, for a test we still would like to download just a piece of a file. # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control # block size when downloading a file. if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE): data_len = self._TEST_FILE_SIZE if data_len is not None: data_len = int(data_len) + ctx.resume_len min_data_len = self.params.get('min_filesize') max_data_len = self.params.get('max_filesize') if min_data_len is not None and data_len < min_data_len: self.to_screen('\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len)) return False if max_data_len is not None and data_len > max_data_len: self.to_screen('\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len)) return False byte_counter = 0 + ctx.resume_len block_size = ctx.block_size start = time.time() # measure time over whole while-loop, so slow_down() and best_block_size() work together properly now = None # needed for slow_down() in the first loop run before = start # start measuring def retry(e): to_stdout = ctx.tmpfilename == '-' if ctx.stream is not None: if not to_stdout: ctx.stream.close() ctx.stream = None ctx.resume_len = byte_counter if to_stdout else os.path.getsize(encodeFilename(ctx.tmpfilename)) raise RetryDownload(e) while True: try: # Download and write data_block = ctx.data.read(block_size if data_len is None else min(block_size, data_len - byte_counter)) # socket.timeout is a subclass of socket.error but may not have # errno set except socket.timeout as e: retry(e) except socket.error as e: # SSLError on python 2 (inherits socket.error) may have # no errno set but this error message if e.errno in (errno.ECONNRESET, errno.ETIMEDOUT) or getattr(e, 'message', None) == 'The read operation timed out': retry(e) raise byte_counter += len(data_block) # exit loop when download is finished if len(data_block) == 0: break # Open destination file just in time if ctx.stream is None: try: ctx.stream, ctx.tmpfilename = sanitize_open( ctx.tmpfilename, ctx.open_mode) assert ctx.stream is not None ctx.filename = self.undo_temp_name(ctx.tmpfilename) self.report_destination(ctx.filename) except (OSError, IOError) as err: self.report_error('unable to open for writing: %s' % str(err)) return False if self.params.get('xattr_set_filesize', False) and data_len is not None: try: write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode('utf-8')) except (XAttrUnavailableError, XAttrMetadataError) as err: self.report_error('unable to set filesize xattr: %s' % str(err)) try: ctx.stream.write(data_block) except (IOError, OSError) as err: self.to_stderr('\n') self.report_error('unable to write data: %s' % str(err)) return False # Apply rate limit self.slow_down(start, now, byte_counter - ctx.resume_len) # end measuring of one loop run now = time.time() after = now # Adjust block size if not self.params.get('noresizebuffer', False): block_size = self.best_block_size(after - before, len(data_block)) before = after # Progress message speed = self.calc_speed(start, now, byte_counter - ctx.resume_len) if ctx.data_len is None: eta = None else: eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len) self._hook_progress({ 'status': 'downloading', 'downloaded_bytes': byte_counter, 'total_bytes': ctx.data_len, 'tmpfilename': ctx.tmpfilename, 'filename': ctx.filename, 'eta': eta, 'speed': speed, 'elapsed': now - ctx.start_time, }) if data_len is not None and byte_counter == data_len: break if not is_test and ctx.chunk_size and ctx.data_len is not None and byte_counter < ctx.data_len: ctx.resume_len = byte_counter # ctx.block_size = block_size raise NextFragment() if ctx.stream is None: self.to_stderr('\n') self.report_error('Did not get any data blocks') return False if ctx.tmpfilename != '-': ctx.stream.close() if data_len is not None and byte_counter != data_len: err = ContentTooShortError(byte_counter, int(data_len)) if count <= retries: retry(err) raise err self.try_rename(ctx.tmpfilename, ctx.filename) # Update file modification time if self.params.get('updatetime', True): info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.info().get('last-modified', None)) self._hook_progress({ 'downloaded_bytes': byte_counter, 'total_bytes': byte_counter, 'filename': ctx.filename, 'status': 'finished', 'elapsed': time.time() - ctx.start_time, }) return True while count <= retries: try: establish_connection() return download() except RetryDownload as e: count += 1 if count <= retries: self.report_retry(e.source_error, count, retries) continue except NextFragment: continue except SucceedDownload: return True self.report_error('giving up after %s retries' % retries) return False
true
2
917
youtube_dl
youtube_dl.downloader.ism
write_piff_header
def write_piff_header(stream, params): track_id = params['track_id'] fourcc = params['fourcc'] duration = params['duration'] timescale = params.get('timescale', 10000000) language = params.get('language', 'und') height = params.get('height', 0) width = params.get('width', 0) is_audio = width == 0 and height == 0 creation_time = modification_time = int(time.time()) ftyp_payload = b'isml' # major brand ftyp_payload += u32.pack(1) # minor version ftyp_payload += b'piff' + b'iso2' # compatible brands stream.write(box(b'ftyp', ftyp_payload)) # File Type Box mvhd_payload = u64.pack(creation_time) mvhd_payload += u64.pack(modification_time) mvhd_payload += u32.pack(timescale) mvhd_payload += u64.pack(duration) mvhd_payload += s1616.pack(1) # rate mvhd_payload += s88.pack(1) # volume mvhd_payload += u16.pack(0) # reserved mvhd_payload += u32.pack(0) * 2 # reserved mvhd_payload += unity_matrix mvhd_payload += u32.pack(0) * 6 # pre defined mvhd_payload += u32.pack(0xffffffff) # next track id moov_payload = full_box(b'mvhd', 1, 0, mvhd_payload) # Movie Header Box tkhd_payload = u64.pack(creation_time) tkhd_payload += u64.pack(modification_time) tkhd_payload += u32.pack(track_id) # track id tkhd_payload += u32.pack(0) # reserved tkhd_payload += u64.pack(duration) tkhd_payload += u32.pack(0) * 2 # reserved tkhd_payload += s16.pack(0) # layer tkhd_payload += s16.pack(0) # alternate group tkhd_payload += s88.pack(1 if is_audio else 0) # volume tkhd_payload += u16.pack(0) # reserved tkhd_payload += unity_matrix tkhd_payload += u1616.pack(width) tkhd_payload += u1616.pack(height) trak_payload = full_box(b'tkhd', 1, TRACK_ENABLED | TRACK_IN_MOVIE | TRACK_IN_PREVIEW, tkhd_payload) # Track Header Box mdhd_payload = u64.pack(creation_time) mdhd_payload += u64.pack(modification_time) mdhd_payload += u32.pack(timescale) mdhd_payload += u64.pack(duration) mdhd_payload += u16.pack(((ord(language[0]) - 0x60) << 10) | ((ord(language[1]) - 0x60) << 5) | (ord(language[2]) - 0x60)) mdhd_payload += u16.pack(0) # pre defined mdia_payload = full_box(b'mdhd', 1, 0, mdhd_payload) # Media Header Box hdlr_payload = u32.pack(0) # pre defined hdlr_payload += b'soun' if is_audio else b'vide' # handler type hdlr_payload += u32.pack(0) * 3 # reserved hdlr_payload += (b'Sound' if is_audio else b'Video') + b'Handler\0' # name mdia_payload += full_box(b'hdlr', 0, 0, hdlr_payload) # Handler Reference Box if is_audio: smhd_payload = s88.pack(0) # balance smhd_payload += u16.pack(0) # reserved media_header_box = full_box(b'smhd', 0, 0, smhd_payload) # Sound Media Header else: vmhd_payload = u16.pack(0) # graphics mode vmhd_payload += u16.pack(0) * 3 # opcolor media_header_box = full_box(b'vmhd', 0, 1, vmhd_payload) # Video Media Header minf_payload = media_header_box dref_payload = u32.pack(1) # entry count dref_payload += full_box(b'url ', 0, SELF_CONTAINED, b'') # Data Entry URL Box dinf_payload = full_box(b'dref', 0, 0, dref_payload) # Data Reference Box minf_payload += box(b'dinf', dinf_payload) # Data Information Box stsd_payload = u32.pack(1) # entry count sample_entry_payload = u8.pack(0) * 6 # reserved sample_entry_payload += u16.pack(1) # data reference index if is_audio: sample_entry_payload += u32.pack(0) * 2 # reserved sample_entry_payload += u16.pack(params.get('channels', 2)) sample_entry_payload += u16.pack(params.get('bits_per_sample', 16)) sample_entry_payload += u16.pack(0) # pre defined sample_entry_payload += u16.pack(0) # reserved sample_entry_payload += u1616.pack(params['sampling_rate']) if fourcc == 'AACL': sample_entry_box = box(b'mp4a', sample_entry_payload) else: sample_entry_payload += u16.pack(0) # pre defined sample_entry_payload += u16.pack(0) # reserved sample_entry_payload += u32.pack(0) * 3 # pre defined sample_entry_payload += u16.pack(width) sample_entry_payload += u16.pack(height) sample_entry_payload += u1616.pack(0x48) # horiz resolution 72 dpi sample_entry_payload += u1616.pack(0x48) # vert resolution 72 dpi sample_entry_payload += u32.pack(0) # reserved sample_entry_payload += u16.pack(1) # frame count sample_entry_payload += u8.pack(0) * 32 # compressor name sample_entry_payload += u16.pack(0x18) # depth sample_entry_payload += s16.pack(-1) # pre defined codec_private_data = binascii.unhexlify(params['codec_private_data'].encode('utf-8')) if fourcc in ('H264', 'AVC1'): sps, pps = codec_private_data.split(u32.pack(1))[1:] avcc_payload = u8.pack(1) # configuration version avcc_payload += sps[1:4] # avc profile indication + profile compatibility + avc level indication avcc_payload += u8.pack(0xfc | (params.get('nal_unit_length_field', 4) - 1)) # complete representation (1) + reserved (11111) + length size minus one avcc_payload += u8.pack(1) # reserved (0) + number of sps (0000001) avcc_payload += u16.pack(len(sps)) avcc_payload += sps avcc_payload += u8.pack(1) # number of pps avcc_payload += u16.pack(len(pps)) avcc_payload += pps sample_entry_payload += box(b'avcC', avcc_payload) # AVC Decoder Configuration Record sample_entry_box = box(b'avc1', sample_entry_payload) # AVC Simple Entry stsd_payload += sample_entry_box stbl_payload = full_box(b'stsd', 0, 0, stsd_payload) # Sample Description Box stts_payload = u32.pack(0) # entry count stbl_payload += full_box(b'stts', 0, 0, stts_payload) # Decoding Time to Sample Box stsc_payload = u32.pack(0) # entry count stbl_payload += full_box(b'stsc', 0, 0, stsc_payload) # Sample To Chunk Box stco_payload = u32.pack(0) # entry count stbl_payload += full_box(b'stco', 0, 0, stco_payload) # Chunk Offset Box minf_payload += box(b'stbl', stbl_payload) # Sample Table Box mdia_payload += box(b'minf', minf_payload) # Media Information Box trak_payload += box(b'mdia', mdia_payload) # Media Box moov_payload += box(b'trak', trak_payload) # Track Box mehd_payload = u64.pack(duration) mvex_payload = full_box(b'mehd', 1, 0, mehd_payload) # Movie Extends Header Box trex_payload = u32.pack(track_id) # track id trex_payload += u32.pack(1) # default sample description index trex_payload += u32.pack(0) # default sample duration trex_payload += u32.pack(0) # default sample size trex_payload += u32.pack(0) # default sample flags mvex_payload += full_box(b'trex', 0, 0, trex_payload) # Track Extends Box moov_payload += box(b'mvex', mvex_payload) # Movie Extends Box stream.write(box(b'moov', moov_payload))
[ 42, 189 ]
false
[ "u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED" ]
import time import binascii import io from .fragment import FragmentFD from ..compat import ( compat_Struct, compat_urllib_error, ) u8 = compat_Struct('>B') u88 = compat_Struct('>Bx') u16 = compat_Struct('>H') u1616 = compat_Struct('>Hxx') u32 = compat_Struct('>I') u64 = compat_Struct('>Q') s88 = compat_Struct('>bx') s16 = compat_Struct('>h') s1616 = compat_Struct('>hxx') s32 = compat_Struct('>i') unity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000) TRACK_ENABLED = 0x1 TRACK_IN_MOVIE = 0x2 TRACK_IN_PREVIEW = 0x4 SELF_CONTAINED = 0x1 def write_piff_header(stream, params): track_id = params['track_id'] fourcc = params['fourcc'] duration = params['duration'] timescale = params.get('timescale', 10000000) language = params.get('language', 'und') height = params.get('height', 0) width = params.get('width', 0) is_audio = width == 0 and height == 0 creation_time = modification_time = int(time.time()) ftyp_payload = b'isml' # major brand ftyp_payload += u32.pack(1) # minor version ftyp_payload += b'piff' + b'iso2' # compatible brands stream.write(box(b'ftyp', ftyp_payload)) # File Type Box mvhd_payload = u64.pack(creation_time) mvhd_payload += u64.pack(modification_time) mvhd_payload += u32.pack(timescale) mvhd_payload += u64.pack(duration) mvhd_payload += s1616.pack(1) # rate mvhd_payload += s88.pack(1) # volume mvhd_payload += u16.pack(0) # reserved mvhd_payload += u32.pack(0) * 2 # reserved mvhd_payload += unity_matrix mvhd_payload += u32.pack(0) * 6 # pre defined mvhd_payload += u32.pack(0xffffffff) # next track id moov_payload = full_box(b'mvhd', 1, 0, mvhd_payload) # Movie Header Box tkhd_payload = u64.pack(creation_time) tkhd_payload += u64.pack(modification_time) tkhd_payload += u32.pack(track_id) # track id tkhd_payload += u32.pack(0) # reserved tkhd_payload += u64.pack(duration) tkhd_payload += u32.pack(0) * 2 # reserved tkhd_payload += s16.pack(0) # layer tkhd_payload += s16.pack(0) # alternate group tkhd_payload += s88.pack(1 if is_audio else 0) # volume tkhd_payload += u16.pack(0) # reserved tkhd_payload += unity_matrix tkhd_payload += u1616.pack(width) tkhd_payload += u1616.pack(height) trak_payload = full_box(b'tkhd', 1, TRACK_ENABLED | TRACK_IN_MOVIE | TRACK_IN_PREVIEW, tkhd_payload) # Track Header Box mdhd_payload = u64.pack(creation_time) mdhd_payload += u64.pack(modification_time) mdhd_payload += u32.pack(timescale) mdhd_payload += u64.pack(duration) mdhd_payload += u16.pack(((ord(language[0]) - 0x60) << 10) | ((ord(language[1]) - 0x60) << 5) | (ord(language[2]) - 0x60)) mdhd_payload += u16.pack(0) # pre defined mdia_payload = full_box(b'mdhd', 1, 0, mdhd_payload) # Media Header Box hdlr_payload = u32.pack(0) # pre defined hdlr_payload += b'soun' if is_audio else b'vide' # handler type hdlr_payload += u32.pack(0) * 3 # reserved hdlr_payload += (b'Sound' if is_audio else b'Video') + b'Handler\0' # name mdia_payload += full_box(b'hdlr', 0, 0, hdlr_payload) # Handler Reference Box if is_audio: smhd_payload = s88.pack(0) # balance smhd_payload += u16.pack(0) # reserved media_header_box = full_box(b'smhd', 0, 0, smhd_payload) # Sound Media Header else: vmhd_payload = u16.pack(0) # graphics mode vmhd_payload += u16.pack(0) * 3 # opcolor media_header_box = full_box(b'vmhd', 0, 1, vmhd_payload) # Video Media Header minf_payload = media_header_box dref_payload = u32.pack(1) # entry count dref_payload += full_box(b'url ', 0, SELF_CONTAINED, b'') # Data Entry URL Box dinf_payload = full_box(b'dref', 0, 0, dref_payload) # Data Reference Box minf_payload += box(b'dinf', dinf_payload) # Data Information Box stsd_payload = u32.pack(1) # entry count sample_entry_payload = u8.pack(0) * 6 # reserved sample_entry_payload += u16.pack(1) # data reference index if is_audio: sample_entry_payload += u32.pack(0) * 2 # reserved sample_entry_payload += u16.pack(params.get('channels', 2)) sample_entry_payload += u16.pack(params.get('bits_per_sample', 16)) sample_entry_payload += u16.pack(0) # pre defined sample_entry_payload += u16.pack(0) # reserved sample_entry_payload += u1616.pack(params['sampling_rate']) if fourcc == 'AACL': sample_entry_box = box(b'mp4a', sample_entry_payload) else: sample_entry_payload += u16.pack(0) # pre defined sample_entry_payload += u16.pack(0) # reserved sample_entry_payload += u32.pack(0) * 3 # pre defined sample_entry_payload += u16.pack(width) sample_entry_payload += u16.pack(height) sample_entry_payload += u1616.pack(0x48) # horiz resolution 72 dpi sample_entry_payload += u1616.pack(0x48) # vert resolution 72 dpi sample_entry_payload += u32.pack(0) # reserved sample_entry_payload += u16.pack(1) # frame count sample_entry_payload += u8.pack(0) * 32 # compressor name sample_entry_payload += u16.pack(0x18) # depth sample_entry_payload += s16.pack(-1) # pre defined codec_private_data = binascii.unhexlify(params['codec_private_data'].encode('utf-8')) if fourcc in ('H264', 'AVC1'): sps, pps = codec_private_data.split(u32.pack(1))[1:] avcc_payload = u8.pack(1) # configuration version avcc_payload += sps[1:4] # avc profile indication + profile compatibility + avc level indication avcc_payload += u8.pack(0xfc | (params.get('nal_unit_length_field', 4) - 1)) # complete representation (1) + reserved (11111) + length size minus one avcc_payload += u8.pack(1) # reserved (0) + number of sps (0000001) avcc_payload += u16.pack(len(sps)) avcc_payload += sps avcc_payload += u8.pack(1) # number of pps avcc_payload += u16.pack(len(pps)) avcc_payload += pps sample_entry_payload += box(b'avcC', avcc_payload) # AVC Decoder Configuration Record sample_entry_box = box(b'avc1', sample_entry_payload) # AVC Simple Entry stsd_payload += sample_entry_box stbl_payload = full_box(b'stsd', 0, 0, stsd_payload) # Sample Description Box stts_payload = u32.pack(0) # entry count stbl_payload += full_box(b'stts', 0, 0, stts_payload) # Decoding Time to Sample Box stsc_payload = u32.pack(0) # entry count stbl_payload += full_box(b'stsc', 0, 0, stsc_payload) # Sample To Chunk Box stco_payload = u32.pack(0) # entry count stbl_payload += full_box(b'stco', 0, 0, stco_payload) # Chunk Offset Box minf_payload += box(b'stbl', stbl_payload) # Sample Table Box mdia_payload += box(b'minf', minf_payload) # Media Information Box trak_payload += box(b'mdia', mdia_payload) # Media Box moov_payload += box(b'trak', trak_payload) # Track Box mehd_payload = u64.pack(duration) mvex_payload = full_box(b'mehd', 1, 0, mehd_payload) # Movie Extends Header Box trex_payload = u32.pack(track_id) # track id trex_payload += u32.pack(1) # default sample description index trex_payload += u32.pack(0) # default sample duration trex_payload += u32.pack(0) # default sample size trex_payload += u32.pack(0) # default sample flags mvex_payload += full_box(b'trex', 0, 0, trex_payload) # Track Extends Box moov_payload += box(b'mvex', mvex_payload) # Movie Extends Box stream.write(box(b'moov', moov_payload))
true
2
918
youtube_dl
youtube_dl.downloader.ism
extract_box_data
def extract_box_data(data, box_sequence): data_reader = io.BytesIO(data) while True: box_size = u32.unpack(data_reader.read(4))[0] box_type = data_reader.read(4) if box_type == box_sequence[0]: box_data = data_reader.read(box_size - 8) if len(box_sequence) == 1: return box_data return extract_box_data(box_data, box_sequence[1:]) data_reader.seek(box_size - 8, 1)
[ 192, 202 ]
false
[ "u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED" ]
import time import binascii import io from .fragment import FragmentFD from ..compat import ( compat_Struct, compat_urllib_error, ) u8 = compat_Struct('>B') u88 = compat_Struct('>Bx') u16 = compat_Struct('>H') u1616 = compat_Struct('>Hxx') u32 = compat_Struct('>I') u64 = compat_Struct('>Q') s88 = compat_Struct('>bx') s16 = compat_Struct('>h') s1616 = compat_Struct('>hxx') s32 = compat_Struct('>i') unity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000) TRACK_ENABLED = 0x1 TRACK_IN_MOVIE = 0x2 TRACK_IN_PREVIEW = 0x4 SELF_CONTAINED = 0x1 def extract_box_data(data, box_sequence): data_reader = io.BytesIO(data) while True: box_size = u32.unpack(data_reader.read(4))[0] box_type = data_reader.read(4) if box_type == box_sequence[0]: box_data = data_reader.read(box_size - 8) if len(box_sequence) == 1: return box_data return extract_box_data(box_data, box_sequence[1:]) data_reader.seek(box_size - 8, 1)
true
2
919
youtube_dl
youtube_dl.downloader.ism
IsmFD
real_download
def real_download(self, filename, info_dict): segments = info_dict['fragments'][:1] if self.params.get( 'test', False) else info_dict['fragments'] ctx = { 'filename': filename, 'total_frags': len(segments), } self._prepare_and_start_frag_download(ctx) fragment_retries = self.params.get('fragment_retries', 0) skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) track_written = False frag_index = 0 for i, segment in enumerate(segments): frag_index += 1 if frag_index <= ctx['fragment_index']: continue count = 0 while count <= fragment_retries: try: success, frag_content = self._download_fragment(ctx, segment['url'], info_dict) if not success: return False if not track_written: tfhd_data = extract_box_data(frag_content, [b'moof', b'traf', b'tfhd']) info_dict['_download_params']['track_id'] = u32.unpack(tfhd_data[4:8])[0] write_piff_header(ctx['dest_stream'], info_dict['_download_params']) track_written = True self._append_fragment(ctx, frag_content) break except compat_urllib_error.HTTPError as err: count += 1 if count <= fragment_retries: self.report_retry_fragment(err, frag_index, count, fragment_retries) if count > fragment_retries: if skip_unavailable_fragments: self.report_skip_fragment(frag_index) continue self.report_error('giving up after %s fragment retries' % fragment_retries) return False self._finish_frag_download(ctx) return True
[ 212, 258 ]
false
[ "u8", "u88", "u16", "u1616", "u32", "u64", "s88", "s16", "s1616", "s32", "unity_matrix", "TRACK_ENABLED", "TRACK_IN_MOVIE", "TRACK_IN_PREVIEW", "SELF_CONTAINED" ]
import time import binascii import io from .fragment import FragmentFD from ..compat import ( compat_Struct, compat_urllib_error, ) u8 = compat_Struct('>B') u88 = compat_Struct('>Bx') u16 = compat_Struct('>H') u1616 = compat_Struct('>Hxx') u32 = compat_Struct('>I') u64 = compat_Struct('>Q') s88 = compat_Struct('>bx') s16 = compat_Struct('>h') s1616 = compat_Struct('>hxx') s32 = compat_Struct('>i') unity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000) TRACK_ENABLED = 0x1 TRACK_IN_MOVIE = 0x2 TRACK_IN_PREVIEW = 0x4 SELF_CONTAINED = 0x1 class IsmFD(FragmentFD): FD_NAME = 'ism' def real_download(self, filename, info_dict): segments = info_dict['fragments'][:1] if self.params.get( 'test', False) else info_dict['fragments'] ctx = { 'filename': filename, 'total_frags': len(segments), } self._prepare_and_start_frag_download(ctx) fragment_retries = self.params.get('fragment_retries', 0) skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) track_written = False frag_index = 0 for i, segment in enumerate(segments): frag_index += 1 if frag_index <= ctx['fragment_index']: continue count = 0 while count <= fragment_retries: try: success, frag_content = self._download_fragment(ctx, segment['url'], info_dict) if not success: return False if not track_written: tfhd_data = extract_box_data(frag_content, [b'moof', b'traf', b'tfhd']) info_dict['_download_params']['track_id'] = u32.unpack(tfhd_data[4:8])[0] write_piff_header(ctx['dest_stream'], info_dict['_download_params']) track_written = True self._append_fragment(ctx, frag_content) break except compat_urllib_error.HTTPError as err: count += 1 if count <= fragment_retries: self.report_retry_fragment(err, frag_index, count, fragment_retries) if count > fragment_retries: if skip_unavailable_fragments: self.report_skip_fragment(frag_index) continue self.report_error('giving up after %s fragment retries' % fragment_retries) return False self._finish_frag_download(ctx) return True
true
2
920
youtube_dl
youtube_dl.jsinterp
JSInterpreter
interpret_statement
def interpret_statement(self, stmt, local_vars, allow_recursion=100): if allow_recursion < 0: raise ExtractorError('Recursion limit reached') should_abort = False stmt = stmt.lstrip() stmt_m = re.match(r'var\s', stmt) if stmt_m: expr = stmt[len(stmt_m.group(0)):] else: return_m = re.match(r'return(?:\s+|$)', stmt) if return_m: expr = stmt[len(return_m.group(0)):] should_abort = True else: # Try interpreting it as an expression expr = stmt v = self.interpret_expression(expr, local_vars, allow_recursion) return v, should_abort
[ 37, 56 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def interpret_statement(self, stmt, local_vars, allow_recursion=100): if allow_recursion < 0: raise ExtractorError('Recursion limit reached') should_abort = False stmt = stmt.lstrip() stmt_m = re.match(r'var\s', stmt) if stmt_m: expr = stmt[len(stmt_m.group(0)):] else: return_m = re.match(r'return(?:\s+|$)', stmt) if return_m: expr = stmt[len(return_m.group(0)):] should_abort = True else: # Try interpreting it as an expression expr = stmt v = self.interpret_expression(expr, local_vars, allow_recursion) return v, should_abort
true
2
921
youtube_dl
youtube_dl.jsinterp
JSInterpreter
interpret_expression
def interpret_expression(self, expr, local_vars, allow_recursion): expr = expr.strip() if expr == '': # Empty expression return None if expr.startswith('('): parens_count = 0 for m in re.finditer(r'[()]', expr): if m.group(0) == '(': parens_count += 1 else: parens_count -= 1 if parens_count == 0: sub_expr = expr[1:m.start()] sub_result = self.interpret_expression( sub_expr, local_vars, allow_recursion) remaining_expr = expr[m.end():].strip() if not remaining_expr: return sub_result else: expr = json.dumps(sub_result) + remaining_expr break else: raise ExtractorError('Premature end of parens in %r' % expr) for op, opfunc in _ASSIGN_OPERATORS: m = re.match(r'''(?x) (?P<out>%s)(?:\[(?P<index>[^\]]+?)\])? \s*%s (?P<expr>.*)$''' % (_NAME_RE, re.escape(op)), expr) if not m: continue right_val = self.interpret_expression( m.group('expr'), local_vars, allow_recursion - 1) if m.groupdict().get('index'): lvar = local_vars[m.group('out')] idx = self.interpret_expression( m.group('index'), local_vars, allow_recursion) assert isinstance(idx, int) cur = lvar[idx] val = opfunc(cur, right_val) lvar[idx] = val return val else: cur = local_vars.get(m.group('out')) val = opfunc(cur, right_val) local_vars[m.group('out')] = val return val if expr.isdigit(): return int(expr) var_m = re.match( r'(?!if|return|true|false)(?P<name>%s)$' % _NAME_RE, expr) if var_m: return local_vars[var_m.group('name')] try: return json.loads(expr) except ValueError: pass m = re.match( r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr) if m: val = local_vars[m.group('in')] idx = self.interpret_expression( m.group('idx'), local_vars, allow_recursion - 1) return val[idx] m = re.match( r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*(?:\(+(?P<args>[^()]*)\))?$' % _NAME_RE, expr) if m: variable = m.group('var') member = remove_quotes(m.group('member') or m.group('member2')) arg_str = m.group('args') if variable in local_vars: obj = local_vars[variable] else: if variable not in self._objects: self._objects[variable] = self.extract_object(variable) obj = self._objects[variable] if arg_str is None: # Member access if member == 'length': return len(obj) return obj[member] assert expr.endswith(')') # Function call if arg_str == '': argvals = tuple() else: argvals = tuple([ self.interpret_expression(v, local_vars, allow_recursion) for v in arg_str.split(',')]) if member == 'split': assert argvals == ('',) return list(obj) if member == 'join': assert len(argvals) == 1 return argvals[0].join(obj) if member == 'reverse': assert len(argvals) == 0 obj.reverse() return obj if member == 'slice': assert len(argvals) == 1 return obj[argvals[0]:] if member == 'splice': assert isinstance(obj, list) index, howMany = argvals res = [] for i in range(index, min(index + howMany, len(obj))): res.append(obj.pop(index)) return res return obj[member](argvals) for op, opfunc in _OPERATORS: m = re.match(r'(?P<x>.+?)%s(?P<y>.+)' % re.escape(op), expr) if not m: continue x, abort = self.interpret_statement( m.group('x'), local_vars, allow_recursion - 1) if abort: raise ExtractorError( 'Premature left-side return of %s in %r' % (op, expr)) y, abort = self.interpret_statement( m.group('y'), local_vars, allow_recursion - 1) if abort: raise ExtractorError( 'Premature right-side return of %s in %r' % (op, expr)) return opfunc(x, y) m = re.match( r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v in m.group('args').split(',')]) if len(m.group('args')) > 0 else tuple() if fname not in self._functions: self._functions[fname] = self.extract_function(fname) return self._functions[fname](argvals) raise ExtractorError('Unsupported JS expression %r' % expr)
[ 58, 210 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def interpret_expression(self, expr, local_vars, allow_recursion): expr = expr.strip() if expr == '': # Empty expression return None if expr.startswith('('): parens_count = 0 for m in re.finditer(r'[()]', expr): if m.group(0) == '(': parens_count += 1 else: parens_count -= 1 if parens_count == 0: sub_expr = expr[1:m.start()] sub_result = self.interpret_expression( sub_expr, local_vars, allow_recursion) remaining_expr = expr[m.end():].strip() if not remaining_expr: return sub_result else: expr = json.dumps(sub_result) + remaining_expr break else: raise ExtractorError('Premature end of parens in %r' % expr) for op, opfunc in _ASSIGN_OPERATORS: m = re.match(r'''(?x) (?P<out>%s)(?:\[(?P<index>[^\]]+?)\])? \s*%s (?P<expr>.*)$''' % (_NAME_RE, re.escape(op)), expr) if not m: continue right_val = self.interpret_expression( m.group('expr'), local_vars, allow_recursion - 1) if m.groupdict().get('index'): lvar = local_vars[m.group('out')] idx = self.interpret_expression( m.group('index'), local_vars, allow_recursion) assert isinstance(idx, int) cur = lvar[idx] val = opfunc(cur, right_val) lvar[idx] = val return val else: cur = local_vars.get(m.group('out')) val = opfunc(cur, right_val) local_vars[m.group('out')] = val return val if expr.isdigit(): return int(expr) var_m = re.match( r'(?!if|return|true|false)(?P<name>%s)$' % _NAME_RE, expr) if var_m: return local_vars[var_m.group('name')] try: return json.loads(expr) except ValueError: pass m = re.match( r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr) if m: val = local_vars[m.group('in')] idx = self.interpret_expression( m.group('idx'), local_vars, allow_recursion - 1) return val[idx] m = re.match( r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*(?:\(+(?P<args>[^()]*)\))?$' % _NAME_RE, expr) if m: variable = m.group('var') member = remove_quotes(m.group('member') or m.group('member2')) arg_str = m.group('args') if variable in local_vars: obj = local_vars[variable] else: if variable not in self._objects: self._objects[variable] = self.extract_object(variable) obj = self._objects[variable] if arg_str is None: # Member access if member == 'length': return len(obj) return obj[member] assert expr.endswith(')') # Function call if arg_str == '': argvals = tuple() else: argvals = tuple([ self.interpret_expression(v, local_vars, allow_recursion) for v in arg_str.split(',')]) if member == 'split': assert argvals == ('',) return list(obj) if member == 'join': assert len(argvals) == 1 return argvals[0].join(obj) if member == 'reverse': assert len(argvals) == 0 obj.reverse() return obj if member == 'slice': assert len(argvals) == 1 return obj[argvals[0]:] if member == 'splice': assert isinstance(obj, list) index, howMany = argvals res = [] for i in range(index, min(index + howMany, len(obj))): res.append(obj.pop(index)) return res return obj[member](argvals) for op, opfunc in _OPERATORS: m = re.match(r'(?P<x>.+?)%s(?P<y>.+)' % re.escape(op), expr) if not m: continue x, abort = self.interpret_statement( m.group('x'), local_vars, allow_recursion - 1) if abort: raise ExtractorError( 'Premature left-side return of %s in %r' % (op, expr)) y, abort = self.interpret_statement( m.group('y'), local_vars, allow_recursion - 1) if abort: raise ExtractorError( 'Premature right-side return of %s in %r' % (op, expr)) return opfunc(x, y) m = re.match( r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr) if m: fname = m.group('func') argvals = tuple([ int(v) if v.isdigit() else local_vars[v] for v in m.group('args').split(',')]) if len(m.group('args')) > 0 else tuple() if fname not in self._functions: self._functions[fname] = self.extract_function(fname) return self._functions[fname](argvals) raise ExtractorError('Unsupported JS expression %r' % expr)
true
2
922
youtube_dl
youtube_dl.jsinterp
JSInterpreter
extract_object
def extract_object(self, objname): _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')''' obj = {} obj_m = re.search( r'''(?x) (?<!this\.)%s\s*=\s*{\s* (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*) }\s*; ''' % (re.escape(objname), _FUNC_NAME_RE), self.code) fields = obj_m.group('fields') # Currently, it only supports function definitions fields_m = re.finditer( r'''(?x) (?P<key>%s)\s*:\s*function\s*\((?P<args>[a-z,]+)\){(?P<code>[^}]+)} ''' % _FUNC_NAME_RE, fields) for f in fields_m: argnames = f.group('args').split(',') obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code')) return obj
[ 212, 233 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def extract_object(self, objname): _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')''' obj = {} obj_m = re.search( r'''(?x) (?<!this\.)%s\s*=\s*{\s* (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*) }\s*; ''' % (re.escape(objname), _FUNC_NAME_RE), self.code) fields = obj_m.group('fields') # Currently, it only supports function definitions fields_m = re.finditer( r'''(?x) (?P<key>%s)\s*:\s*function\s*\((?P<args>[a-z,]+)\){(?P<code>[^}]+)} ''' % _FUNC_NAME_RE, fields) for f in fields_m: argnames = f.group('args').split(',') obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code')) return obj
true
2
923
youtube_dl
youtube_dl.jsinterp
JSInterpreter
extract_function
def extract_function(self, funcname): func_m = re.search( r'''(?x) (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s* \((?P<args>[^)]*)\)\s* \{(?P<code>[^}]+)\}''' % ( re.escape(funcname), re.escape(funcname), re.escape(funcname)), self.code) if func_m is None: raise ExtractorError('Could not find JS function %r' % funcname) argnames = func_m.group('args').split(',') return self.build_function(argnames, func_m.group('code'))
[ 235, 247 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def extract_function(self, funcname): func_m = re.search( r'''(?x) (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s* \((?P<args>[^)]*)\)\s* \{(?P<code>[^}]+)\}''' % ( re.escape(funcname), re.escape(funcname), re.escape(funcname)), self.code) if func_m is None: raise ExtractorError('Could not find JS function %r' % funcname) argnames = func_m.group('args').split(',') return self.build_function(argnames, func_m.group('code'))
true
2
924
youtube_dl
youtube_dl.jsinterp
JSInterpreter
call_function
def call_function(self, funcname, *args): f = self.extract_function(funcname) return f(args)
[ 249, 251 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def call_function(self, funcname, *args): f = self.extract_function(funcname) return f(args)
false
0
925
youtube_dl
youtube_dl.jsinterp
JSInterpreter
build_function
def build_function(self, argnames, code): def resf(args): local_vars = dict(zip(argnames, args)) for stmt in code.split(';'): res, abort = self.interpret_statement(stmt, local_vars) if abort: break return res return resf
[ 253, 261 ]
false
[ "_OPERATORS", "_ASSIGN_OPERATORS", "_NAME_RE" ]
import json import operator import re from .utils import ( ExtractorError, remove_quotes, ) _OPERATORS = [ ('|', operator.or_), ('^', operator.xor), ('&', operator.and_), ('>>', operator.rshift), ('<<', operator.lshift), ('-', operator.sub), ('+', operator.add), ('%', operator.mod), ('/', operator.truediv), ('*', operator.mul), ] _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' class JSInterpreter(object): def __init__(self, code, objects=None): if objects is None: objects = {} self.code = code self._functions = {} self._objects = objects def build_function(self, argnames, code): def resf(args): local_vars = dict(zip(argnames, args)) for stmt in code.split(';'): res, abort = self.interpret_statement(stmt, local_vars) if abort: break return res return resf
true
2
926
youtube_dl
youtube_dl.options
parseOpts
def parseOpts(overrideArguments=None): def _readOptions(filename_bytes, default=[]): try: optionf = open(filename_bytes) except IOError: return default # silently skip if file is not present try: # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56 contents = optionf.read() if sys.version_info < (3,): contents = contents.decode(preferredencoding()) res = compat_shlex_split(contents, comments=True) finally: optionf.close() return res def _readUserConf(): xdg_config_home = compat_getenv('XDG_CONFIG_HOME') if xdg_config_home: userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config') if not os.path.isfile(userConfFile): userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf') else: userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config') if not os.path.isfile(userConfFile): userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf') userConf = _readOptions(userConfFile, None) if userConf is None: appdata_dir = compat_getenv('appdata') if appdata_dir: userConf = _readOptions( os.path.join(appdata_dir, 'youtube-dl', 'config'), default=None) if userConf is None: userConf = _readOptions( os.path.join(appdata_dir, 'youtube-dl', 'config.txt'), default=None) if userConf is None: userConf = _readOptions( os.path.join(compat_expanduser('~'), 'youtube-dl.conf'), default=None) if userConf is None: userConf = _readOptions( os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'), default=None) if userConf is None: userConf = [] return userConf def _format_option_string(option): ''' ('-o', '--option') -> -o, --format METAVAR''' opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, ', ') if option.takes_value(): opts.append(' %s' % option.metavar) return ''.join(opts) def _comma_separated_values_options_callback(option, opt_str, value, parser): setattr(parser.values, option.dest, value.split(',')) # No need to wrap help messages if we're on a wide console columns = compat_get_terminal_size().columns max_width = columns if columns else 80 max_help_position = 80 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position) fmt.format_option_strings = _format_option_string kw = { 'version': __version__, 'formatter': fmt, 'usage': '%prog [OPTIONS] URL [URL...]', 'conflict_handler': 'resolve', } parser = optparse.OptionParser(**compat_kwargs(kw)) general = optparse.OptionGroup(parser, 'General Options') general.add_option( '-h', '--help', action='help', help='Print this help text and exit') general.add_option( '--version', action='version', help='Print program version and exit') general.add_option( '-U', '--update', action='store_true', dest='update_self', help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)') general.add_option( '-i', '--ignore-errors', action='store_true', dest='ignoreerrors', default=False, help='Continue on download errors, for example to skip unavailable videos in a playlist') general.add_option( '--abort-on-error', action='store_false', dest='ignoreerrors', help='Abort downloading of further videos (in the playlist or the command line) if an error occurs') general.add_option( '--dump-user-agent', action='store_true', dest='dump_user_agent', default=False, help='Display the current browser identification') general.add_option( '--list-extractors', action='store_true', dest='list_extractors', default=False, help='List all supported extractors') general.add_option( '--extractor-descriptions', action='store_true', dest='list_extractor_descriptions', default=False, help='Output descriptions of all supported extractors') general.add_option( '--force-generic-extractor', action='store_true', dest='force_generic_extractor', default=False, help='Force extraction to use the generic extractor') general.add_option( '--default-search', dest='default_search', metavar='PREFIX', help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.') general.add_option( '--ignore-config', action='store_true', help='Do not read configuration files. ' 'When given in the global configuration file /etc/youtube-dl.conf: ' 'Do not read the user configuration in ~/.config/youtube-dl/config ' '(%APPDATA%/youtube-dl/config.txt on Windows)') general.add_option( '--config-location', dest='config_location', metavar='PATH', help='Location of the configuration file; either the path to the config or its containing directory.') general.add_option( '--flat-playlist', action='store_const', dest='extract_flat', const='in_playlist', default=False, help='Do not extract the videos of a playlist, only list them.') general.add_option( '--mark-watched', action='store_true', dest='mark_watched', default=False, help='Mark videos watched (YouTube only)') general.add_option( '--no-mark-watched', action='store_false', dest='mark_watched', default=False, help='Do not mark videos watched (YouTube only)') general.add_option( '--no-color', '--no-colors', action='store_true', dest='no_color', default=False, help='Do not emit color codes in output') network = optparse.OptionGroup(parser, 'Network Options') network.add_option( '--proxy', dest='proxy', default=None, metavar='URL', help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable ' 'SOCKS proxy, specify a proper scheme. For example ' 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") ' 'for direct connection') network.add_option( '--socket-timeout', dest='socket_timeout', type=float, default=None, metavar='SECONDS', help='Time to wait before giving up, in seconds') network.add_option( '--source-address', metavar='IP', dest='source_address', default=None, help='Client-side IP address to bind to', ) network.add_option( '-4', '--force-ipv4', action='store_const', const='0.0.0.0', dest='source_address', help='Make all connections via IPv4', ) network.add_option( '-6', '--force-ipv6', action='store_const', const='::', dest='source_address', help='Make all connections via IPv6', ) geo = optparse.OptionGroup(parser, 'Geo Restriction') geo.add_option( '--geo-verification-proxy', dest='geo_verification_proxy', default=None, metavar='URL', help='Use this proxy to verify the IP address for some geo-restricted sites. ' 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.') geo.add_option( '--cn-verification-proxy', dest='cn_verification_proxy', default=None, metavar='URL', help=optparse.SUPPRESS_HELP) geo.add_option( '--geo-bypass', action='store_true', dest='geo_bypass', default=True, help='Bypass geographic restriction via faking X-Forwarded-For HTTP header') geo.add_option( '--no-geo-bypass', action='store_false', dest='geo_bypass', default=True, help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header') geo.add_option( '--geo-bypass-country', metavar='CODE', dest='geo_bypass_country', default=None, help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code') geo.add_option( '--geo-bypass-ip-block', metavar='IP_BLOCK', dest='geo_bypass_ip_block', default=None, help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation') selection = optparse.OptionGroup(parser, 'Video Selection') selection.add_option( '--playlist-start', dest='playliststart', metavar='NUMBER', default=1, type=int, help='Playlist video to start at (default is %default)') selection.add_option( '--playlist-end', dest='playlistend', metavar='NUMBER', default=None, type=int, help='Playlist video to end at (default is last)') selection.add_option( '--playlist-items', dest='playlist_items', metavar='ITEM_SPEC', default=None, help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.') selection.add_option( '--match-title', dest='matchtitle', metavar='REGEX', help='Download only matching titles (regex or caseless sub-string)') selection.add_option( '--reject-title', dest='rejecttitle', metavar='REGEX', help='Skip download for matching titles (regex or caseless sub-string)') selection.add_option( '--max-downloads', dest='max_downloads', metavar='NUMBER', type=int, default=None, help='Abort after downloading NUMBER files') selection.add_option( '--min-filesize', metavar='SIZE', dest='min_filesize', default=None, help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)') selection.add_option( '--max-filesize', metavar='SIZE', dest='max_filesize', default=None, help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)') selection.add_option( '--date', metavar='DATE', dest='date', default=None, help='Download only videos uploaded in this date') selection.add_option( '--datebefore', metavar='DATE', dest='datebefore', default=None, help='Download only videos uploaded on or before this date (i.e. inclusive)') selection.add_option( '--dateafter', metavar='DATE', dest='dateafter', default=None, help='Download only videos uploaded on or after this date (i.e. inclusive)') selection.add_option( '--min-views', metavar='COUNT', dest='min_views', default=None, type=int, help='Do not download any videos with less than COUNT views') selection.add_option( '--max-views', metavar='COUNT', dest='max_views', default=None, type=int, help='Do not download any videos with more than COUNT views') selection.add_option( '--match-filter', metavar='FILTER', dest='match_filter', default=None, help=( 'Generic video filter. ' 'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to ' 'match if the key is present, ' '!key to check if the key is not present, ' 'key > NUMBER (like "comment_count > 12", also works with ' '>=, <, <=, !=, =) to compare against a number, ' 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) ' 'to match against a string literal ' 'and & to require multiple matches. ' 'Values which are not known are excluded unless you ' 'put a question mark (?) after the operator. ' 'For example, to only match videos that have been liked more than ' '100 times and disliked less than 50 times (or the dislike ' 'functionality is not available at the given service), but who ' 'also have a description, use --match-filter ' '"like_count > 100 & dislike_count <? 50 & description" .' )) selection.add_option( '--no-playlist', action='store_true', dest='noplaylist', default=False, help='Download only the video, if the URL refers to a video and a playlist.') selection.add_option( '--yes-playlist', action='store_false', dest='noplaylist', default=False, help='Download the playlist, if the URL refers to a video and a playlist.') selection.add_option( '--age-limit', metavar='YEARS', dest='age_limit', default=None, type=int, help='Download only videos suitable for the given age') selection.add_option( '--download-archive', metavar='FILE', dest='download_archive', help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.') selection.add_option( '--include-ads', dest='include_ads', action='store_true', help='Download advertisements as well (experimental)') authentication = optparse.OptionGroup(parser, 'Authentication Options') authentication.add_option( '-u', '--username', dest='username', metavar='USERNAME', help='Login with this account ID') authentication.add_option( '-p', '--password', dest='password', metavar='PASSWORD', help='Account password. If this option is left out, youtube-dl will ask interactively.') authentication.add_option( '-2', '--twofactor', dest='twofactor', metavar='TWOFACTOR', help='Two-factor authentication code') authentication.add_option( '-n', '--netrc', action='store_true', dest='usenetrc', default=False, help='Use .netrc authentication data') authentication.add_option( '--video-password', dest='videopassword', metavar='PASSWORD', help='Video password (vimeo, youku)') adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options') adobe_pass.add_option( '--ap-mso', dest='ap_mso', metavar='MSO', help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs') adobe_pass.add_option( '--ap-username', dest='ap_username', metavar='USERNAME', help='Multiple-system operator account login') adobe_pass.add_option( '--ap-password', dest='ap_password', metavar='PASSWORD', help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.') adobe_pass.add_option( '--ap-list-mso', action='store_true', dest='ap_list_mso', default=False, help='List all supported multiple-system operators') video_format = optparse.OptionGroup(parser, 'Video Format Options') video_format.add_option( '-f', '--format', action='store', dest='format', metavar='FORMAT', default=None, help='Video format code, see the "FORMAT SELECTION" for all the info') video_format.add_option( '--all-formats', action='store_const', dest='format', const='all', help='Download all available video formats') video_format.add_option( '--prefer-free-formats', action='store_true', dest='prefer_free_formats', default=False, help='Prefer free video formats unless a specific one is requested') video_format.add_option( '-F', '--list-formats', action='store_true', dest='listformats', help='List all available formats of requested videos') video_format.add_option( '--youtube-include-dash-manifest', action='store_true', dest='youtube_include_dash_manifest', default=True, help=optparse.SUPPRESS_HELP) video_format.add_option( '--youtube-skip-dash-manifest', action='store_false', dest='youtube_include_dash_manifest', help='Do not download the DASH manifests and related data on YouTube videos') video_format.add_option( '--merge-output-format', action='store', dest='merge_output_format', metavar='FORMAT', default=None, help=( 'If a merge is required (e.g. bestvideo+bestaudio), ' 'output to given container format. One of mkv, mp4, ogg, webm, flv. ' 'Ignored if no merge is required')) subtitles = optparse.OptionGroup(parser, 'Subtitle Options') subtitles.add_option( '--write-sub', '--write-srt', action='store_true', dest='writesubtitles', default=False, help='Write subtitle file') subtitles.add_option( '--write-auto-sub', '--write-automatic-sub', action='store_true', dest='writeautomaticsub', default=False, help='Write automatically generated subtitle file (YouTube only)') subtitles.add_option( '--all-subs', action='store_true', dest='allsubtitles', default=False, help='Download all the available subtitles of the video') subtitles.add_option( '--list-subs', action='store_true', dest='listsubtitles', default=False, help='List all available subtitles for the video') subtitles.add_option( '--sub-format', action='store', dest='subtitlesformat', metavar='FORMAT', default='best', help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"') subtitles.add_option( '--sub-lang', '--sub-langs', '--srt-lang', action='callback', dest='subtitleslangs', metavar='LANGS', type='str', default=[], callback=_comma_separated_values_options_callback, help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags') downloader = optparse.OptionGroup(parser, 'Download Options') downloader.add_option( '-r', '--limit-rate', '--rate-limit', dest='ratelimit', metavar='RATE', help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)') downloader.add_option( '-R', '--retries', dest='retries', metavar='RETRIES', default=10, help='Number of retries (default is %default), or "infinite".') downloader.add_option( '--fragment-retries', dest='fragment_retries', metavar='RETRIES', default=10, help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)') downloader.add_option( '--skip-unavailable-fragments', action='store_true', dest='skip_unavailable_fragments', default=True, help='Skip unavailable fragments (DASH, hlsnative and ISM)') downloader.add_option( '--abort-on-unavailable-fragment', action='store_false', dest='skip_unavailable_fragments', help='Abort downloading when some fragment is not available') downloader.add_option( '--keep-fragments', action='store_true', dest='keep_fragments', default=False, help='Keep downloaded fragments on disk after downloading is finished; fragments are erased by default') downloader.add_option( '--buffer-size', dest='buffersize', metavar='SIZE', default='1024', help='Size of download buffer (e.g. 1024 or 16K) (default is %default)') downloader.add_option( '--no-resize-buffer', action='store_true', dest='noresizebuffer', default=False, help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.') downloader.add_option( '--http-chunk-size', dest='http_chunk_size', metavar='SIZE', default=None, help='Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). ' 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)') downloader.add_option( '--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP) downloader.add_option( '--playlist-reverse', action='store_true', help='Download playlist videos in reverse order') downloader.add_option( '--playlist-random', action='store_true', help='Download playlist videos in random order') downloader.add_option( '--xattr-set-filesize', dest='xattr_set_filesize', action='store_true', help='Set file xattribute ytdl.filesize with expected file size') downloader.add_option( '--hls-prefer-native', dest='hls_prefer_native', action='store_true', default=None, help='Use the native HLS downloader instead of ffmpeg') downloader.add_option( '--hls-prefer-ffmpeg', dest='hls_prefer_native', action='store_false', default=None, help='Use ffmpeg instead of the native HLS downloader') downloader.add_option( '--hls-use-mpegts', dest='hls_use_mpegts', action='store_true', help='Use the mpegts container for HLS videos, allowing to play the ' 'video while downloading (some players may not be able to play it)') downloader.add_option( '--external-downloader', dest='external_downloader', metavar='COMMAND', help='Use the specified external downloader. ' 'Currently supports %s' % ','.join(list_external_downloaders())) downloader.add_option( '--external-downloader-args', dest='external_downloader_args', metavar='ARGS', help='Give these arguments to the external downloader') workarounds = optparse.OptionGroup(parser, 'Workarounds') workarounds.add_option( '--encoding', dest='encoding', metavar='ENCODING', help='Force the specified encoding (experimental)') workarounds.add_option( '--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation') workarounds.add_option( '--prefer-insecure', '--prefer-unsecure', action='store_true', dest='prefer_insecure', help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)') workarounds.add_option( '--user-agent', metavar='UA', dest='user_agent', help='Specify a custom user agent') workarounds.add_option( '--referer', metavar='URL', dest='referer', default=None, help='Specify a custom referer, use if the video access is restricted to one domain', ) workarounds.add_option( '--add-header', metavar='FIELD:VALUE', dest='headers', action='append', help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times', ) workarounds.add_option( '--bidi-workaround', dest='bidi_workaround', action='store_true', help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH') workarounds.add_option( '--sleep-interval', '--min-sleep-interval', metavar='SECONDS', dest='sleep_interval', type=float, help=( 'Number of seconds to sleep before each download when used alone ' 'or a lower bound of a range for randomized sleep before each download ' '(minimum possible number of seconds to sleep) when used along with ' '--max-sleep-interval.')) workarounds.add_option( '--max-sleep-interval', metavar='SECONDS', dest='max_sleep_interval', type=float, help=( 'Upper bound of a range for randomized sleep before each download ' '(maximum possible number of seconds to sleep). Must only be used ' 'along with --min-sleep-interval.')) verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options') verbosity.add_option( '-q', '--quiet', action='store_true', dest='quiet', default=False, help='Activate quiet mode') verbosity.add_option( '--no-warnings', dest='no_warnings', action='store_true', default=False, help='Ignore warnings') verbosity.add_option( '-s', '--simulate', action='store_true', dest='simulate', default=False, help='Do not download the video and do not write anything to disk') verbosity.add_option( '--skip-download', action='store_true', dest='skip_download', default=False, help='Do not download the video') verbosity.add_option( '-g', '--get-url', action='store_true', dest='geturl', default=False, help='Simulate, quiet but print URL') verbosity.add_option( '-e', '--get-title', action='store_true', dest='gettitle', default=False, help='Simulate, quiet but print title') verbosity.add_option( '--get-id', action='store_true', dest='getid', default=False, help='Simulate, quiet but print id') verbosity.add_option( '--get-thumbnail', action='store_true', dest='getthumbnail', default=False, help='Simulate, quiet but print thumbnail URL') verbosity.add_option( '--get-description', action='store_true', dest='getdescription', default=False, help='Simulate, quiet but print video description') verbosity.add_option( '--get-duration', action='store_true', dest='getduration', default=False, help='Simulate, quiet but print video length') verbosity.add_option( '--get-filename', action='store_true', dest='getfilename', default=False, help='Simulate, quiet but print output filename') verbosity.add_option( '--get-format', action='store_true', dest='getformat', default=False, help='Simulate, quiet but print output format') verbosity.add_option( '-j', '--dump-json', action='store_true', dest='dumpjson', default=False, help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.') verbosity.add_option( '-J', '--dump-single-json', action='store_true', dest='dump_single_json', default=False, help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.') verbosity.add_option( '--print-json', action='store_true', dest='print_json', default=False, help='Be quiet and print the video information as JSON (video is still being downloaded).', ) verbosity.add_option( '--newline', action='store_true', dest='progress_with_newline', default=False, help='Output progress bar as new lines') verbosity.add_option( '--no-progress', action='store_true', dest='noprogress', default=False, help='Do not print progress bar') verbosity.add_option( '--console-title', action='store_true', dest='consoletitle', default=False, help='Display progress in console titlebar') verbosity.add_option( '-v', '--verbose', action='store_true', dest='verbose', default=False, help='Print various debugging information') verbosity.add_option( '--dump-pages', '--dump-intermediate-pages', action='store_true', dest='dump_intermediate_pages', default=False, help='Print downloaded pages encoded using base64 to debug problems (very verbose)') verbosity.add_option( '--write-pages', action='store_true', dest='write_pages', default=False, help='Write downloaded intermediary pages to files in the current directory to debug problems') verbosity.add_option( '--youtube-print-sig-code', action='store_true', dest='youtube_print_sig_code', default=False, help=optparse.SUPPRESS_HELP) verbosity.add_option( '--print-traffic', '--dump-headers', dest='debug_printtraffic', action='store_true', default=False, help='Display sent and read HTTP traffic') verbosity.add_option( '-C', '--call-home', dest='call_home', action='store_true', default=False, help='Contact the youtube-dl server for debugging') verbosity.add_option( '--no-call-home', dest='call_home', action='store_false', default=False, help='Do NOT contact the youtube-dl server for debugging') filesystem = optparse.OptionGroup(parser, 'Filesystem Options') filesystem.add_option( '-a', '--batch-file', dest='batchfile', metavar='FILE', help="File containing URLs to download ('-' for stdin), one URL per line. " "Lines starting with '#', ';' or ']' are considered as comments and ignored.") filesystem.add_option( '--id', default=False, action='store_true', dest='useid', help='Use only video ID in file name') filesystem.add_option( '-o', '--output', dest='outtmpl', metavar='TEMPLATE', help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info')) filesystem.add_option( '--output-na-placeholder', dest='outtmpl_na_placeholder', metavar='PLACEHOLDER', default='NA', help=('Placeholder value for unavailable meta fields in output filename template (default is "%default")')) filesystem.add_option( '--autonumber-size', dest='autonumber_size', metavar='NUMBER', type=int, help=optparse.SUPPRESS_HELP) filesystem.add_option( '--autonumber-start', dest='autonumber_start', metavar='NUMBER', default=1, type=int, help='Specify the start value for %(autonumber)s (default is %default)') filesystem.add_option( '--restrict-filenames', action='store_true', dest='restrictfilenames', default=False, help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames') filesystem.add_option( '-A', '--auto-number', action='store_true', dest='autonumber', default=False, help=optparse.SUPPRESS_HELP) filesystem.add_option( '-t', '--title', action='store_true', dest='usetitle', default=False, help=optparse.SUPPRESS_HELP) filesystem.add_option( '-l', '--literal', default=False, action='store_true', dest='usetitle', help=optparse.SUPPRESS_HELP) filesystem.add_option( '-w', '--no-overwrites', action='store_true', dest='nooverwrites', default=False, help='Do not overwrite files') filesystem.add_option( '-c', '--continue', action='store_true', dest='continue_dl', default=True, help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.') filesystem.add_option( '--no-continue', action='store_false', dest='continue_dl', help='Do not resume partially downloaded files (restart from beginning)') filesystem.add_option( '--no-part', action='store_true', dest='nopart', default=False, help='Do not use .part files - write directly into output file') filesystem.add_option( '--no-mtime', action='store_false', dest='updatetime', default=True, help='Do not use the Last-modified header to set the file modification time') filesystem.add_option( '--write-description', action='store_true', dest='writedescription', default=False, help='Write video description to a .description file') filesystem.add_option( '--write-info-json', action='store_true', dest='writeinfojson', default=False, help='Write video metadata to a .info.json file') filesystem.add_option( '--write-annotations', action='store_true', dest='writeannotations', default=False, help='Write video annotations to a .annotations.xml file') filesystem.add_option( '--load-info-json', '--load-info', dest='load_info_filename', metavar='FILE', help='JSON file containing the video information (created with the "--write-info-json" option)') filesystem.add_option( '--cookies', dest='cookiefile', metavar='FILE', help='File to read cookies from and dump cookie jar in') filesystem.add_option( '--cache-dir', dest='cachedir', default=None, metavar='DIR', help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change.') filesystem.add_option( '--no-cache-dir', action='store_const', const=False, dest='cachedir', help='Disable filesystem caching') filesystem.add_option( '--rm-cache-dir', action='store_true', dest='rm_cachedir', help='Delete all filesystem cache files') thumbnail = optparse.OptionGroup(parser, 'Thumbnail Options') thumbnail.add_option( '--write-thumbnail', action='store_true', dest='writethumbnail', default=False, help='Write thumbnail image to disk') thumbnail.add_option( '--write-all-thumbnails', action='store_true', dest='write_all_thumbnails', default=False, help='Write all thumbnail image formats to disk') thumbnail.add_option( '--list-thumbnails', action='store_true', dest='list_thumbnails', default=False, help='Simulate and list all available thumbnail formats') postproc = optparse.OptionGroup(parser, 'Post-processing Options') postproc.add_option( '-x', '--extract-audio', action='store_true', dest='extractaudio', default=False, help='Convert video files to audio-only files (requires ffmpeg/avconv and ffprobe/avprobe)') postproc.add_option( '--audio-format', metavar='FORMAT', dest='audioformat', default='best', help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x') postproc.add_option( '--audio-quality', metavar='QUALITY', dest='audioquality', default='5', help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)') postproc.add_option( '--recode-video', metavar='FORMAT', dest='recodevideo', default=None, help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)') postproc.add_option( '--postprocessor-args', dest='postprocessor_args', metavar='ARGS', help='Give these arguments to the postprocessor') postproc.add_option( '-k', '--keep-video', action='store_true', dest='keepvideo', default=False, help='Keep the video file on disk after the post-processing; the video is erased by default') postproc.add_option( '--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False, help='Do not overwrite post-processed files; the post-processed files are overwritten by default') postproc.add_option( '--embed-subs', action='store_true', dest='embedsubtitles', default=False, help='Embed subtitles in the video (only for mp4, webm and mkv videos)') postproc.add_option( '--embed-thumbnail', action='store_true', dest='embedthumbnail', default=False, help='Embed thumbnail in the audio as cover art') postproc.add_option( '--add-metadata', action='store_true', dest='addmetadata', default=False, help='Write metadata to the video file') postproc.add_option( '--metadata-from-title', metavar='FORMAT', dest='metafromtitle', help='Parse additional metadata like song title / artist from the video title. ' 'The format syntax is the same as --output. Regular expression with ' 'named capture groups may also be used. ' 'The parsed parameters replace existing values. ' 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like ' '"Coldplay - Paradise". ' 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"') postproc.add_option( '--xattrs', action='store_true', dest='xattrs', default=False, help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)') postproc.add_option( '--fixup', metavar='POLICY', dest='fixup', default='detect_or_warn', help='Automatically correct known faults of the file. ' 'One of never (do nothing), warn (only emit a warning), ' 'detect_or_warn (the default; fix file if we can, warn otherwise)') postproc.add_option( '--prefer-avconv', action='store_false', dest='prefer_ffmpeg', help='Prefer avconv over ffmpeg for running the postprocessors') postproc.add_option( '--prefer-ffmpeg', action='store_true', dest='prefer_ffmpeg', help='Prefer ffmpeg over avconv for running the postprocessors (default)') postproc.add_option( '--ffmpeg-location', '--avconv-location', metavar='PATH', dest='ffmpeg_location', help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.') postproc.add_option( '--exec', metavar='CMD', dest='exec_cmd', help='Execute a command on the file after downloading and post-processing, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'') postproc.add_option( '--convert-subs', '--convert-subtitles', metavar='FORMAT', dest='convertsubtitles', default=None, help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)') parser.add_option_group(general) parser.add_option_group(network) parser.add_option_group(geo) parser.add_option_group(selection) parser.add_option_group(downloader) parser.add_option_group(filesystem) parser.add_option_group(thumbnail) parser.add_option_group(verbosity) parser.add_option_group(workarounds) parser.add_option_group(video_format) parser.add_option_group(subtitles) parser.add_option_group(authentication) parser.add_option_group(adobe_pass) parser.add_option_group(postproc) if overrideArguments is not None: opts, args = parser.parse_args(overrideArguments) if opts.verbose: write_string('[debug] Override config: ' + repr(overrideArguments) + '\n') else: def compat_conf(conf): if sys.version_info < (3,): return [a.decode(preferredencoding(), 'replace') for a in conf] return conf command_line_conf = compat_conf(sys.argv[1:]) opts, args = parser.parse_args(command_line_conf) system_conf = user_conf = custom_conf = [] if '--config-location' in command_line_conf: location = compat_expanduser(opts.config_location) if os.path.isdir(location): location = os.path.join(location, 'youtube-dl.conf') if not os.path.exists(location): parser.error('config-location %s does not exist.' % location) custom_conf = _readOptions(location) elif '--ignore-config' in command_line_conf: pass else: system_conf = _readOptions('/etc/youtube-dl.conf') if '--ignore-config' not in system_conf: user_conf = _readUserConf() argv = system_conf + user_conf + custom_conf + command_line_conf opts, args = parser.parse_args(argv) if opts.verbose: for conf_label, conf in ( ('System config', system_conf), ('User config', user_conf), ('Custom config', custom_conf), ('Command-line args', command_line_conf)): write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf)))) return parser, opts, args
[ 40, 919 ]
false
[]
import os.path import optparse import re import sys from .downloader.external import list_external_downloaders from .compat import ( compat_expanduser, compat_get_terminal_size, compat_getenv, compat_kwargs, compat_shlex_split, ) from .utils import ( preferredencoding, write_string, ) from .version import __version__ def parseOpts(overrideArguments=None): def _readOptions(filename_bytes, default=[]): try: optionf = open(filename_bytes) except IOError: return default # silently skip if file is not present try: # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56 contents = optionf.read() if sys.version_info < (3,): contents = contents.decode(preferredencoding()) res = compat_shlex_split(contents, comments=True) finally: optionf.close() return res def _readUserConf(): xdg_config_home = compat_getenv('XDG_CONFIG_HOME') if xdg_config_home: userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config') if not os.path.isfile(userConfFile): userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf') else: userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config') if not os.path.isfile(userConfFile): userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf') userConf = _readOptions(userConfFile, None) if userConf is None: appdata_dir = compat_getenv('appdata') if appdata_dir: userConf = _readOptions( os.path.join(appdata_dir, 'youtube-dl', 'config'), default=None) if userConf is None: userConf = _readOptions( os.path.join(appdata_dir, 'youtube-dl', 'config.txt'), default=None) if userConf is None: userConf = _readOptions( os.path.join(compat_expanduser('~'), 'youtube-dl.conf'), default=None) if userConf is None: userConf = _readOptions( os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'), default=None) if userConf is None: userConf = [] return userConf def _format_option_string(option): ''' ('-o', '--option') -> -o, --format METAVAR''' opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, ', ') if option.takes_value(): opts.append(' %s' % option.metavar) return ''.join(opts) def _comma_separated_values_options_callback(option, opt_str, value, parser): setattr(parser.values, option.dest, value.split(',')) # No need to wrap help messages if we're on a wide console columns = compat_get_terminal_size().columns max_width = columns if columns else 80 max_help_position = 80 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position) fmt.format_option_strings = _format_option_string kw = { 'version': __version__, 'formatter': fmt, 'usage': '%prog [OPTIONS] URL [URL...]', 'conflict_handler': 'resolve', } parser = optparse.OptionParser(**compat_kwargs(kw)) general = optparse.OptionGroup(parser, 'General Options') general.add_option( '-h', '--help', action='help', help='Print this help text and exit') general.add_option( '--version', action='version', help='Print program version and exit') general.add_option( '-U', '--update', action='store_true', dest='update_self', help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)') general.add_option( '-i', '--ignore-errors', action='store_true', dest='ignoreerrors', default=False, help='Continue on download errors, for example to skip unavailable videos in a playlist') general.add_option( '--abort-on-error', action='store_false', dest='ignoreerrors', help='Abort downloading of further videos (in the playlist or the command line) if an error occurs') general.add_option( '--dump-user-agent', action='store_true', dest='dump_user_agent', default=False, help='Display the current browser identification') general.add_option( '--list-extractors', action='store_true', dest='list_extractors', default=False, help='List all supported extractors') general.add_option( '--extractor-descriptions', action='store_true', dest='list_extractor_descriptions', default=False, help='Output descriptions of all supported extractors') general.add_option( '--force-generic-extractor', action='store_true', dest='force_generic_extractor', default=False, help='Force extraction to use the generic extractor') general.add_option( '--default-search', dest='default_search', metavar='PREFIX', help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.') general.add_option( '--ignore-config', action='store_true', help='Do not read configuration files. ' 'When given in the global configuration file /etc/youtube-dl.conf: ' 'Do not read the user configuration in ~/.config/youtube-dl/config ' '(%APPDATA%/youtube-dl/config.txt on Windows)') general.add_option( '--config-location', dest='config_location', metavar='PATH', help='Location of the configuration file; either the path to the config or its containing directory.') general.add_option( '--flat-playlist', action='store_const', dest='extract_flat', const='in_playlist', default=False, help='Do not extract the videos of a playlist, only list them.') general.add_option( '--mark-watched', action='store_true', dest='mark_watched', default=False, help='Mark videos watched (YouTube only)') general.add_option( '--no-mark-watched', action='store_false', dest='mark_watched', default=False, help='Do not mark videos watched (YouTube only)') general.add_option( '--no-color', '--no-colors', action='store_true', dest='no_color', default=False, help='Do not emit color codes in output') network = optparse.OptionGroup(parser, 'Network Options') network.add_option( '--proxy', dest='proxy', default=None, metavar='URL', help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable ' 'SOCKS proxy, specify a proper scheme. For example ' 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") ' 'for direct connection') network.add_option( '--socket-timeout', dest='socket_timeout', type=float, default=None, metavar='SECONDS', help='Time to wait before giving up, in seconds') network.add_option( '--source-address', metavar='IP', dest='source_address', default=None, help='Client-side IP address to bind to', ) network.add_option( '-4', '--force-ipv4', action='store_const', const='0.0.0.0', dest='source_address', help='Make all connections via IPv4', ) network.add_option( '-6', '--force-ipv6', action='store_const', const='::', dest='source_address', help='Make all connections via IPv6', ) geo = optparse.OptionGroup(parser, 'Geo Restriction') geo.add_option( '--geo-verification-proxy', dest='geo_verification_proxy', default=None, metavar='URL', help='Use this proxy to verify the IP address for some geo-restricted sites. ' 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.') geo.add_option( '--cn-verification-proxy', dest='cn_verification_proxy', default=None, metavar='URL', help=optparse.SUPPRESS_HELP) geo.add_option( '--geo-bypass', action='store_true', dest='geo_bypass', default=True, help='Bypass geographic restriction via faking X-Forwarded-For HTTP header') geo.add_option( '--no-geo-bypass', action='store_false', dest='geo_bypass', default=True, help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header') geo.add_option( '--geo-bypass-country', metavar='CODE', dest='geo_bypass_country', default=None, help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code') geo.add_option( '--geo-bypass-ip-block', metavar='IP_BLOCK', dest='geo_bypass_ip_block', default=None, help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation') selection = optparse.OptionGroup(parser, 'Video Selection') selection.add_option( '--playlist-start', dest='playliststart', metavar='NUMBER', default=1, type=int, help='Playlist video to start at (default is %default)') selection.add_option( '--playlist-end', dest='playlistend', metavar='NUMBER', default=None, type=int, help='Playlist video to end at (default is last)') selection.add_option( '--playlist-items', dest='playlist_items', metavar='ITEM_SPEC', default=None, help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.') selection.add_option( '--match-title', dest='matchtitle', metavar='REGEX', help='Download only matching titles (regex or caseless sub-string)') selection.add_option( '--reject-title', dest='rejecttitle', metavar='REGEX', help='Skip download for matching titles (regex or caseless sub-string)') selection.add_option( '--max-downloads', dest='max_downloads', metavar='NUMBER', type=int, default=None, help='Abort after downloading NUMBER files') selection.add_option( '--min-filesize', metavar='SIZE', dest='min_filesize', default=None, help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)') selection.add_option( '--max-filesize', metavar='SIZE', dest='max_filesize', default=None, help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)') selection.add_option( '--date', metavar='DATE', dest='date', default=None, help='Download only videos uploaded in this date') selection.add_option( '--datebefore', metavar='DATE', dest='datebefore', default=None, help='Download only videos uploaded on or before this date (i.e. inclusive)') selection.add_option( '--dateafter', metavar='DATE', dest='dateafter', default=None, help='Download only videos uploaded on or after this date (i.e. inclusive)') selection.add_option( '--min-views', metavar='COUNT', dest='min_views', default=None, type=int, help='Do not download any videos with less than COUNT views') selection.add_option( '--max-views', metavar='COUNT', dest='max_views', default=None, type=int, help='Do not download any videos with more than COUNT views') selection.add_option( '--match-filter', metavar='FILTER', dest='match_filter', default=None, help=( 'Generic video filter. ' 'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to ' 'match if the key is present, ' '!key to check if the key is not present, ' 'key > NUMBER (like "comment_count > 12", also works with ' '>=, <, <=, !=, =) to compare against a number, ' 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) ' 'to match against a string literal ' 'and & to require multiple matches. ' 'Values which are not known are excluded unless you ' 'put a question mark (?) after the operator. ' 'For example, to only match videos that have been liked more than ' '100 times and disliked less than 50 times (or the dislike ' 'functionality is not available at the given service), but who ' 'also have a description, use --match-filter ' '"like_count > 100 & dislike_count <? 50 & description" .' )) selection.add_option( '--no-playlist', action='store_true', dest='noplaylist', default=False, help='Download only the video, if the URL refers to a video and a playlist.') selection.add_option( '--yes-playlist', action='store_false', dest='noplaylist', default=False, help='Download the playlist, if the URL refers to a video and a playlist.') selection.add_option( '--age-limit', metavar='YEARS', dest='age_limit', default=None, type=int, help='Download only videos suitable for the given age') selection.add_option( '--download-archive', metavar='FILE', dest='download_archive', help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.') selection.add_option( '--include-ads', dest='include_ads', action='store_true', help='Download advertisements as well (experimental)') authentication = optparse.OptionGroup(parser, 'Authentication Options') authentication.add_option( '-u', '--username', dest='username', metavar='USERNAME', help='Login with this account ID') authentication.add_option( '-p', '--password', dest='password', metavar='PASSWORD', help='Account password. If this option is left out, youtube-dl will ask interactively.') authentication.add_option( '-2', '--twofactor', dest='twofactor', metavar='TWOFACTOR', help='Two-factor authentication code') authentication.add_option( '-n', '--netrc', action='store_true', dest='usenetrc', default=False, help='Use .netrc authentication data') authentication.add_option( '--video-password', dest='videopassword', metavar='PASSWORD', help='Video password (vimeo, youku)') adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options') adobe_pass.add_option( '--ap-mso', dest='ap_mso', metavar='MSO', help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs') adobe_pass.add_option( '--ap-username', dest='ap_username', metavar='USERNAME', help='Multiple-system operator account login') adobe_pass.add_option( '--ap-password', dest='ap_password', metavar='PASSWORD', help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.') adobe_pass.add_option( '--ap-list-mso', action='store_true', dest='ap_list_mso', default=False, help='List all supported multiple-system operators') video_format = optparse.OptionGroup(parser, 'Video Format Options') video_format.add_option( '-f', '--format', action='store', dest='format', metavar='FORMAT', default=None, help='Video format code, see the "FORMAT SELECTION" for all the info') video_format.add_option( '--all-formats', action='store_const', dest='format', const='all', help='Download all available video formats') video_format.add_option( '--prefer-free-formats', action='store_true', dest='prefer_free_formats', default=False, help='Prefer free video formats unless a specific one is requested') video_format.add_option( '-F', '--list-formats', action='store_true', dest='listformats', help='List all available formats of requested videos') video_format.add_option( '--youtube-include-dash-manifest', action='store_true', dest='youtube_include_dash_manifest', default=True, help=optparse.SUPPRESS_HELP) video_format.add_option( '--youtube-skip-dash-manifest', action='store_false', dest='youtube_include_dash_manifest', help='Do not download the DASH manifests and related data on YouTube videos') video_format.add_option( '--merge-output-format', action='store', dest='merge_output_format', metavar='FORMAT', default=None, help=( 'If a merge is required (e.g. bestvideo+bestaudio), ' 'output to given container format. One of mkv, mp4, ogg, webm, flv. ' 'Ignored if no merge is required')) subtitles = optparse.OptionGroup(parser, 'Subtitle Options') subtitles.add_option( '--write-sub', '--write-srt', action='store_true', dest='writesubtitles', default=False, help='Write subtitle file') subtitles.add_option( '--write-auto-sub', '--write-automatic-sub', action='store_true', dest='writeautomaticsub', default=False, help='Write automatically generated subtitle file (YouTube only)') subtitles.add_option( '--all-subs', action='store_true', dest='allsubtitles', default=False, help='Download all the available subtitles of the video') subtitles.add_option( '--list-subs', action='store_true', dest='listsubtitles', default=False, help='List all available subtitles for the video') subtitles.add_option( '--sub-format', action='store', dest='subtitlesformat', metavar='FORMAT', default='best', help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"') subtitles.add_option( '--sub-lang', '--sub-langs', '--srt-lang', action='callback', dest='subtitleslangs', metavar='LANGS', type='str', default=[], callback=_comma_separated_values_options_callback, help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags') downloader = optparse.OptionGroup(parser, 'Download Options') downloader.add_option( '-r', '--limit-rate', '--rate-limit', dest='ratelimit', metavar='RATE', help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)') downloader.add_option( '-R', '--retries', dest='retries', metavar='RETRIES', default=10, help='Number of retries (default is %default), or "infinite".') downloader.add_option( '--fragment-retries', dest='fragment_retries', metavar='RETRIES', default=10, help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)') downloader.add_option( '--skip-unavailable-fragments', action='store_true', dest='skip_unavailable_fragments', default=True, help='Skip unavailable fragments (DASH, hlsnative and ISM)') downloader.add_option( '--abort-on-unavailable-fragment', action='store_false', dest='skip_unavailable_fragments', help='Abort downloading when some fragment is not available') downloader.add_option( '--keep-fragments', action='store_true', dest='keep_fragments', default=False, help='Keep downloaded fragments on disk after downloading is finished; fragments are erased by default') downloader.add_option( '--buffer-size', dest='buffersize', metavar='SIZE', default='1024', help='Size of download buffer (e.g. 1024 or 16K) (default is %default)') downloader.add_option( '--no-resize-buffer', action='store_true', dest='noresizebuffer', default=False, help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.') downloader.add_option( '--http-chunk-size', dest='http_chunk_size', metavar='SIZE', default=None, help='Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). ' 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)') downloader.add_option( '--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP) downloader.add_option( '--playlist-reverse', action='store_true', help='Download playlist videos in reverse order') downloader.add_option( '--playlist-random', action='store_true', help='Download playlist videos in random order') downloader.add_option( '--xattr-set-filesize', dest='xattr_set_filesize', action='store_true', help='Set file xattribute ytdl.filesize with expected file size') downloader.add_option( '--hls-prefer-native', dest='hls_prefer_native', action='store_true', default=None, help='Use the native HLS downloader instead of ffmpeg') downloader.add_option( '--hls-prefer-ffmpeg', dest='hls_prefer_native', action='store_false', default=None, help='Use ffmpeg instead of the native HLS downloader') downloader.add_option( '--hls-use-mpegts', dest='hls_use_mpegts', action='store_true', help='Use the mpegts container for HLS videos, allowing to play the ' 'video while downloading (some players may not be able to play it)') downloader.add_option( '--external-downloader', dest='external_downloader', metavar='COMMAND', help='Use the specified external downloader. ' 'Currently supports %s' % ','.join(list_external_downloaders())) downloader.add_option( '--external-downloader-args', dest='external_downloader_args', metavar='ARGS', help='Give these arguments to the external downloader') workarounds = optparse.OptionGroup(parser, 'Workarounds') workarounds.add_option( '--encoding', dest='encoding', metavar='ENCODING', help='Force the specified encoding (experimental)') workarounds.add_option( '--no-check-certificate', action='store_true', dest='no_check_certificate', default=False, help='Suppress HTTPS certificate validation') workarounds.add_option( '--prefer-insecure', '--prefer-unsecure', action='store_true', dest='prefer_insecure', help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)') workarounds.add_option( '--user-agent', metavar='UA', dest='user_agent', help='Specify a custom user agent') workarounds.add_option( '--referer', metavar='URL', dest='referer', default=None, help='Specify a custom referer, use if the video access is restricted to one domain', ) workarounds.add_option( '--add-header', metavar='FIELD:VALUE', dest='headers', action='append', help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times', ) workarounds.add_option( '--bidi-workaround', dest='bidi_workaround', action='store_true', help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH') workarounds.add_option( '--sleep-interval', '--min-sleep-interval', metavar='SECONDS', dest='sleep_interval', type=float, help=( 'Number of seconds to sleep before each download when used alone ' 'or a lower bound of a range for randomized sleep before each download ' '(minimum possible number of seconds to sleep) when used along with ' '--max-sleep-interval.')) workarounds.add_option( '--max-sleep-interval', metavar='SECONDS', dest='max_sleep_interval', type=float, help=( 'Upper bound of a range for randomized sleep before each download ' '(maximum possible number of seconds to sleep). Must only be used ' 'along with --min-sleep-interval.')) verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options') verbosity.add_option( '-q', '--quiet', action='store_true', dest='quiet', default=False, help='Activate quiet mode') verbosity.add_option( '--no-warnings', dest='no_warnings', action='store_true', default=False, help='Ignore warnings') verbosity.add_option( '-s', '--simulate', action='store_true', dest='simulate', default=False, help='Do not download the video and do not write anything to disk') verbosity.add_option( '--skip-download', action='store_true', dest='skip_download', default=False, help='Do not download the video') verbosity.add_option( '-g', '--get-url', action='store_true', dest='geturl', default=False, help='Simulate, quiet but print URL') verbosity.add_option( '-e', '--get-title', action='store_true', dest='gettitle', default=False, help='Simulate, quiet but print title') verbosity.add_option( '--get-id', action='store_true', dest='getid', default=False, help='Simulate, quiet but print id') verbosity.add_option( '--get-thumbnail', action='store_true', dest='getthumbnail', default=False, help='Simulate, quiet but print thumbnail URL') verbosity.add_option( '--get-description', action='store_true', dest='getdescription', default=False, help='Simulate, quiet but print video description') verbosity.add_option( '--get-duration', action='store_true', dest='getduration', default=False, help='Simulate, quiet but print video length') verbosity.add_option( '--get-filename', action='store_true', dest='getfilename', default=False, help='Simulate, quiet but print output filename') verbosity.add_option( '--get-format', action='store_true', dest='getformat', default=False, help='Simulate, quiet but print output format') verbosity.add_option( '-j', '--dump-json', action='store_true', dest='dumpjson', default=False, help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.') verbosity.add_option( '-J', '--dump-single-json', action='store_true', dest='dump_single_json', default=False, help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.') verbosity.add_option( '--print-json', action='store_true', dest='print_json', default=False, help='Be quiet and print the video information as JSON (video is still being downloaded).', ) verbosity.add_option( '--newline', action='store_true', dest='progress_with_newline', default=False, help='Output progress bar as new lines') verbosity.add_option( '--no-progress', action='store_true', dest='noprogress', default=False, help='Do not print progress bar') verbosity.add_option( '--console-title', action='store_true', dest='consoletitle', default=False, help='Display progress in console titlebar') verbosity.add_option( '-v', '--verbose', action='store_true', dest='verbose', default=False, help='Print various debugging information') verbosity.add_option( '--dump-pages', '--dump-intermediate-pages', action='store_true', dest='dump_intermediate_pages', default=False, help='Print downloaded pages encoded using base64 to debug problems (very verbose)') verbosity.add_option( '--write-pages', action='store_true', dest='write_pages', default=False, help='Write downloaded intermediary pages to files in the current directory to debug problems') verbosity.add_option( '--youtube-print-sig-code', action='store_true', dest='youtube_print_sig_code', default=False, help=optparse.SUPPRESS_HELP) verbosity.add_option( '--print-traffic', '--dump-headers', dest='debug_printtraffic', action='store_true', default=False, help='Display sent and read HTTP traffic') verbosity.add_option( '-C', '--call-home', dest='call_home', action='store_true', default=False, help='Contact the youtube-dl server for debugging') verbosity.add_option( '--no-call-home', dest='call_home', action='store_false', default=False, help='Do NOT contact the youtube-dl server for debugging') filesystem = optparse.OptionGroup(parser, 'Filesystem Options') filesystem.add_option( '-a', '--batch-file', dest='batchfile', metavar='FILE', help="File containing URLs to download ('-' for stdin), one URL per line. " "Lines starting with '#', ';' or ']' are considered as comments and ignored.") filesystem.add_option( '--id', default=False, action='store_true', dest='useid', help='Use only video ID in file name') filesystem.add_option( '-o', '--output', dest='outtmpl', metavar='TEMPLATE', help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info')) filesystem.add_option( '--output-na-placeholder', dest='outtmpl_na_placeholder', metavar='PLACEHOLDER', default='NA', help=('Placeholder value for unavailable meta fields in output filename template (default is "%default")')) filesystem.add_option( '--autonumber-size', dest='autonumber_size', metavar='NUMBER', type=int, help=optparse.SUPPRESS_HELP) filesystem.add_option( '--autonumber-start', dest='autonumber_start', metavar='NUMBER', default=1, type=int, help='Specify the start value for %(autonumber)s (default is %default)') filesystem.add_option( '--restrict-filenames', action='store_true', dest='restrictfilenames', default=False, help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames') filesystem.add_option( '-A', '--auto-number', action='store_true', dest='autonumber', default=False, help=optparse.SUPPRESS_HELP) filesystem.add_option( '-t', '--title', action='store_true', dest='usetitle', default=False, help=optparse.SUPPRESS_HELP) filesystem.add_option( '-l', '--literal', default=False, action='store_true', dest='usetitle', help=optparse.SUPPRESS_HELP) filesystem.add_option( '-w', '--no-overwrites', action='store_true', dest='nooverwrites', default=False, help='Do not overwrite files') filesystem.add_option( '-c', '--continue', action='store_true', dest='continue_dl', default=True, help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.') filesystem.add_option( '--no-continue', action='store_false', dest='continue_dl', help='Do not resume partially downloaded files (restart from beginning)') filesystem.add_option( '--no-part', action='store_true', dest='nopart', default=False, help='Do not use .part files - write directly into output file') filesystem.add_option( '--no-mtime', action='store_false', dest='updatetime', default=True, help='Do not use the Last-modified header to set the file modification time') filesystem.add_option( '--write-description', action='store_true', dest='writedescription', default=False, help='Write video description to a .description file') filesystem.add_option( '--write-info-json', action='store_true', dest='writeinfojson', default=False, help='Write video metadata to a .info.json file') filesystem.add_option( '--write-annotations', action='store_true', dest='writeannotations', default=False, help='Write video annotations to a .annotations.xml file') filesystem.add_option( '--load-info-json', '--load-info', dest='load_info_filename', metavar='FILE', help='JSON file containing the video information (created with the "--write-info-json" option)') filesystem.add_option( '--cookies', dest='cookiefile', metavar='FILE', help='File to read cookies from and dump cookie jar in') filesystem.add_option( '--cache-dir', dest='cachedir', default=None, metavar='DIR', help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change.') filesystem.add_option( '--no-cache-dir', action='store_const', const=False, dest='cachedir', help='Disable filesystem caching') filesystem.add_option( '--rm-cache-dir', action='store_true', dest='rm_cachedir', help='Delete all filesystem cache files') thumbnail = optparse.OptionGroup(parser, 'Thumbnail Options') thumbnail.add_option( '--write-thumbnail', action='store_true', dest='writethumbnail', default=False, help='Write thumbnail image to disk') thumbnail.add_option( '--write-all-thumbnails', action='store_true', dest='write_all_thumbnails', default=False, help='Write all thumbnail image formats to disk') thumbnail.add_option( '--list-thumbnails', action='store_true', dest='list_thumbnails', default=False, help='Simulate and list all available thumbnail formats') postproc = optparse.OptionGroup(parser, 'Post-processing Options') postproc.add_option( '-x', '--extract-audio', action='store_true', dest='extractaudio', default=False, help='Convert video files to audio-only files (requires ffmpeg/avconv and ffprobe/avprobe)') postproc.add_option( '--audio-format', metavar='FORMAT', dest='audioformat', default='best', help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x') postproc.add_option( '--audio-quality', metavar='QUALITY', dest='audioquality', default='5', help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)') postproc.add_option( '--recode-video', metavar='FORMAT', dest='recodevideo', default=None, help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)') postproc.add_option( '--postprocessor-args', dest='postprocessor_args', metavar='ARGS', help='Give these arguments to the postprocessor') postproc.add_option( '-k', '--keep-video', action='store_true', dest='keepvideo', default=False, help='Keep the video file on disk after the post-processing; the video is erased by default') postproc.add_option( '--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False, help='Do not overwrite post-processed files; the post-processed files are overwritten by default') postproc.add_option( '--embed-subs', action='store_true', dest='embedsubtitles', default=False, help='Embed subtitles in the video (only for mp4, webm and mkv videos)') postproc.add_option( '--embed-thumbnail', action='store_true', dest='embedthumbnail', default=False, help='Embed thumbnail in the audio as cover art') postproc.add_option( '--add-metadata', action='store_true', dest='addmetadata', default=False, help='Write metadata to the video file') postproc.add_option( '--metadata-from-title', metavar='FORMAT', dest='metafromtitle', help='Parse additional metadata like song title / artist from the video title. ' 'The format syntax is the same as --output. Regular expression with ' 'named capture groups may also be used. ' 'The parsed parameters replace existing values. ' 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like ' '"Coldplay - Paradise". ' 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"') postproc.add_option( '--xattrs', action='store_true', dest='xattrs', default=False, help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)') postproc.add_option( '--fixup', metavar='POLICY', dest='fixup', default='detect_or_warn', help='Automatically correct known faults of the file. ' 'One of never (do nothing), warn (only emit a warning), ' 'detect_or_warn (the default; fix file if we can, warn otherwise)') postproc.add_option( '--prefer-avconv', action='store_false', dest='prefer_ffmpeg', help='Prefer avconv over ffmpeg for running the postprocessors') postproc.add_option( '--prefer-ffmpeg', action='store_true', dest='prefer_ffmpeg', help='Prefer ffmpeg over avconv for running the postprocessors (default)') postproc.add_option( '--ffmpeg-location', '--avconv-location', metavar='PATH', dest='ffmpeg_location', help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.') postproc.add_option( '--exec', metavar='CMD', dest='exec_cmd', help='Execute a command on the file after downloading and post-processing, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'') postproc.add_option( '--convert-subs', '--convert-subtitles', metavar='FORMAT', dest='convertsubtitles', default=None, help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)') parser.add_option_group(general) parser.add_option_group(network) parser.add_option_group(geo) parser.add_option_group(selection) parser.add_option_group(downloader) parser.add_option_group(filesystem) parser.add_option_group(thumbnail) parser.add_option_group(verbosity) parser.add_option_group(workarounds) parser.add_option_group(video_format) parser.add_option_group(subtitles) parser.add_option_group(authentication) parser.add_option_group(adobe_pass) parser.add_option_group(postproc) if overrideArguments is not None: opts, args = parser.parse_args(overrideArguments) if opts.verbose: write_string('[debug] Override config: ' + repr(overrideArguments) + '\n') else: def compat_conf(conf): if sys.version_info < (3,): return [a.decode(preferredencoding(), 'replace') for a in conf] return conf command_line_conf = compat_conf(sys.argv[1:]) opts, args = parser.parse_args(command_line_conf) system_conf = user_conf = custom_conf = [] if '--config-location' in command_line_conf: location = compat_expanduser(opts.config_location) if os.path.isdir(location): location = os.path.join(location, 'youtube-dl.conf') if not os.path.exists(location): parser.error('config-location %s does not exist.' % location) custom_conf = _readOptions(location) elif '--ignore-config' in command_line_conf: pass else: system_conf = _readOptions('/etc/youtube-dl.conf') if '--ignore-config' not in system_conf: user_conf = _readUserConf() argv = system_conf + user_conf + custom_conf + command_line_conf opts, args = parser.parse_args(argv) if opts.verbose: for conf_label, conf in ( ('System config', system_conf), ('User config', user_conf), ('Custom config', custom_conf), ('Command-line args', command_line_conf)): write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf)))) return parser, opts, args
true
2
927
youtube_dl
youtube_dl.postprocessor.common
PostProcessor
try_utime
def try_utime(self, path, atime, mtime, errnote='Cannot update utime of file'): try: os.utime(encodeFilename(path), (atime, mtime)) except Exception: self._downloader.report_warning(errnote)
[ 57, 61 ]
false
[]
import os from ..utils import ( PostProcessingError, cli_configuration_args, encodeFilename, ) class PostProcessor(object): _downloader = None def __init__(self, downloader=None): self._downloader = downloader def try_utime(self, path, atime, mtime, errnote='Cannot update utime of file'): try: os.utime(encodeFilename(path), (atime, mtime)) except Exception: self._downloader.report_warning(errnote)
false
0
928
youtube_dl
youtube_dl.postprocessor.metadatafromtitle
MetadataFromTitlePP
__init__
def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) if re.search(r'%\(\w+\)s', titleformat) else titleformat)
[ 8, 11 ]
false
[]
import re from .common import PostProcessor class MetadataFromTitlePP(PostProcessor): def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) if re.search(r'%\(\w+\)s', titleformat) else titleformat)
false
0
929
youtube_dl
youtube_dl.postprocessor.metadatafromtitle
MetadataFromTitlePP
format_to_regex
def format_to_regex(self, fmt): r""" Converts a string like '%(title)s - %(artist)s' to a regex like '(?P<title>.+)\ \-\ (?P<artist>.+)' """ lastpos = 0 regex = '' # replace %(..)s with regex group and escape other string parts for match in re.finditer(r'%\((\w+)\)s', fmt): regex += re.escape(fmt[lastpos:match.start()]) regex += r'(?P<' + match.group(1) + '>.+)' lastpos = match.end() if lastpos < len(fmt): regex += re.escape(fmt[lastpos:]) return regex
[ 15, 31 ]
false
[]
import re from .common import PostProcessor class MetadataFromTitlePP(PostProcessor): def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) if re.search(r'%\(\w+\)s', titleformat) else titleformat) def format_to_regex(self, fmt): r""" Converts a string like '%(title)s - %(artist)s' to a regex like '(?P<title>.+)\ \-\ (?P<artist>.+)' """ lastpos = 0 regex = '' # replace %(..)s with regex group and escape other string parts for match in re.finditer(r'%\((\w+)\)s', fmt): regex += re.escape(fmt[lastpos:match.start()]) regex += r'(?P<' + match.group(1) + '>.+)' lastpos = match.end() if lastpos < len(fmt): regex += re.escape(fmt[lastpos:]) return regex
true
2
930
youtube_dl
youtube_dl.postprocessor.metadatafromtitle
MetadataFromTitlePP
run
def run(self, info): title = info['title'] match = re.match(self._titleregex, title) if match is None: self._downloader.to_screen( '[fromtitle] Could not interpret title of video as "%s"' % self._titleformat) return [], info for attribute, value in match.groupdict().items(): info[attribute] = value self._downloader.to_screen( '[fromtitle] parsed %s: %s' % (attribute, value if value is not None else 'NA')) return [], info
[ 33, 47 ]
false
[]
import re from .common import PostProcessor class MetadataFromTitlePP(PostProcessor): def __init__(self, downloader, titleformat): super(MetadataFromTitlePP, self).__init__(downloader) self._titleformat = titleformat self._titleregex = (self.format_to_regex(titleformat) if re.search(r'%\(\w+\)s', titleformat) else titleformat) def run(self, info): title = info['title'] match = re.match(self._titleregex, title) if match is None: self._downloader.to_screen( '[fromtitle] Could not interpret title of video as "%s"' % self._titleformat) return [], info for attribute, value in match.groupdict().items(): info[attribute] = value self._downloader.to_screen( '[fromtitle] parsed %s: %s' % (attribute, value if value is not None else 'NA')) return [], info
true
2
931
youtube_dl
youtube_dl.postprocessor.xattrpp
XAttrMetadataPP
run
def run(self, info): """ Set extended attributes on downloaded file (if xattr support is found). """ # Write the metadata to the file's xattrs self._downloader.to_screen('[metadata] Writing metadata to file\'s xattrs') filename = info['filepath'] try: xattr_mapping = { 'user.xdg.referrer.url': 'webpage_url', # 'user.xdg.comment': 'description', 'user.dublincore.title': 'title', 'user.dublincore.date': 'upload_date', 'user.dublincore.description': 'description', 'user.dublincore.contributor': 'uploader', 'user.dublincore.format': 'format', } num_written = 0 for xattrname, infoname in xattr_mapping.items(): value = info.get(infoname) if value: if infoname == 'upload_date': value = hyphenate_date(value) byte_value = value.encode('utf-8') write_xattr(filename, xattrname, byte_value) num_written += 1 return [], info except XAttrUnavailableError as e: self._downloader.report_error(str(e)) return [], info except XAttrMetadataError as e: if e.reason == 'NO_SPACE': self._downloader.report_warning( 'There\'s no disk space left, disk quota exceeded or filesystem xattr limit exceeded. ' + (('Some ' if num_written else '') + 'extended attributes are not written.').capitalize()) elif e.reason == 'VALUE_TOO_LONG': self._downloader.report_warning( 'Unable to write extended attributes due to too long values.') else: msg = 'This filesystem doesn\'t support extended attributes. ' if compat_os_name == 'nt': msg += 'You need to use NTFS.' else: msg += '(You may have to enable them in your /etc/fstab)' self._downloader.report_error(msg) return [], info
[ 25, 78 ]
false
[]
from .common import PostProcessor from ..compat import compat_os_name from ..utils import ( hyphenate_date, write_xattr, XAttrMetadataError, XAttrUnavailableError, ) class XAttrMetadataPP(PostProcessor): # # More info about extended attributes for media: # http://freedesktop.org/wiki/CommonExtendedAttributes/ # http://www.freedesktop.org/wiki/PhreedomDraft/ # http://dublincore.org/documents/usageguide/elements.shtml # # TODO: # * capture youtube keywords and put them in 'user.dublincore.subject' (comma-separated) # * figure out which xattrs can be used for 'duration', 'thumbnail', 'resolution' # def run(self, info): """ Set extended attributes on downloaded file (if xattr support is found). """ # Write the metadata to the file's xattrs self._downloader.to_screen('[metadata] Writing metadata to file\'s xattrs') filename = info['filepath'] try: xattr_mapping = { 'user.xdg.referrer.url': 'webpage_url', # 'user.xdg.comment': 'description', 'user.dublincore.title': 'title', 'user.dublincore.date': 'upload_date', 'user.dublincore.description': 'description', 'user.dublincore.contributor': 'uploader', 'user.dublincore.format': 'format', } num_written = 0 for xattrname, infoname in xattr_mapping.items(): value = info.get(infoname) if value: if infoname == 'upload_date': value = hyphenate_date(value) byte_value = value.encode('utf-8') write_xattr(filename, xattrname, byte_value) num_written += 1 return [], info except XAttrUnavailableError as e: self._downloader.report_error(str(e)) return [], info except XAttrMetadataError as e: if e.reason == 'NO_SPACE': self._downloader.report_warning( 'There\'s no disk space left, disk quota exceeded or filesystem xattr limit exceeded. ' + (('Some ' if num_written else '') + 'extended attributes are not written.').capitalize()) elif e.reason == 'VALUE_TOO_LONG': self._downloader.report_warning( 'Unable to write extended attributes due to too long values.') else: msg = 'This filesystem doesn\'t support extended attributes. ' if compat_os_name == 'nt': msg += 'You need to use NTFS.' else: msg += '(You may have to enable them in your /etc/fstab)' self._downloader.report_error(msg) return [], info
true
2
932
youtube_dl
youtube_dl.socks
ProxyError
__init__
def __init__(self, code=None, msg=None): if code is not None and msg is None: msg = self.CODES.get(code) or 'unknown error' super(ProxyError, self).__init__(code, msg)
[ 60, 63 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AUTH_VERSION = 0x01 SOCKS5_USER_AUTH_SUCCESS = 0x00 Proxy = collections.namedtuple('Proxy', ( 'type', 'host', 'port', 'username', 'password', 'remote_dns')) class ProxyError(socket.error): ERR_SUCCESS = 0x00 def __init__(self, code=None, msg=None): if code is not None and msg is None: msg = self.CODES.get(code) or 'unknown error' super(ProxyError, self).__init__(code, msg)
true
2
933
youtube_dl
youtube_dl.socks
InvalidVersionError
__init__
def __init__(self, expected_version, got_version): msg = ('Invalid response version from server. Expected {0:02x} got ' '{1:02x}'.format(expected_version, got_version)) super(InvalidVersionError, self).__init__(0, msg)
[ 67, 70 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AUTH_VERSION = 0x01 SOCKS5_USER_AUTH_SUCCESS = 0x00 Proxy = collections.namedtuple('Proxy', ( 'type', 'host', 'port', 'username', 'password', 'remote_dns')) class InvalidVersionError(ProxyError): def __init__(self, expected_version, got_version): msg = ('Invalid response version from server. Expected {0:02x} got ' '{1:02x}'.format(expected_version, got_version)) super(InvalidVersionError, self).__init__(0, msg)
false
0
934
youtube_dl
youtube_dl.socks
sockssocket
setproxy
def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None): assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5) self._proxy = Proxy(proxytype, addr, port, username, password, rdns)
[ 115, 118 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AUTH_VERSION = 0x01 SOCKS5_USER_AUTH_SUCCESS = 0x00 Proxy = collections.namedtuple('Proxy', ( 'type', 'host', 'port', 'username', 'password', 'remote_dns')) class sockssocket(socket.socket): def __init__(self, *args, **kwargs): self._proxy = None super(sockssocket, self).__init__(*args, **kwargs) def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None): assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5) self._proxy = Proxy(proxytype, addr, port, username, password, rdns)
false
0
935
youtube_dl
youtube_dl.socks
sockssocket
recvall
def recvall(self, cnt): data = b'' while len(data) < cnt: cur = self.recv(cnt - len(data)) if not cur: raise EOFError('{0} bytes missing'.format(cnt - len(data))) data += cur return data
[ 120, 127 ]
false
[ "__author__", "SOCKS4_VERSION", "SOCKS4_REPLY_VERSION", "SOCKS4_DEFAULT_DSTIP", "SOCKS5_VERSION", "SOCKS5_USER_AUTH_VERSION", "SOCKS5_USER_AUTH_SUCCESS", "Proxy" ]
import collections import socket from .compat import ( compat_ord, compat_struct_pack, compat_struct_unpack, ) __author__ = 'Timo Schmid <coding@timoschmid.de>' SOCKS4_VERSION = 4 SOCKS4_REPLY_VERSION = 0x00 SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF) SOCKS5_VERSION = 5 SOCKS5_USER_AUTH_VERSION = 0x01 SOCKS5_USER_AUTH_SUCCESS = 0x00 Proxy = collections.namedtuple('Proxy', ( 'type', 'host', 'port', 'username', 'password', 'remote_dns')) class sockssocket(socket.socket): def __init__(self, *args, **kwargs): self._proxy = None super(sockssocket, self).__init__(*args, **kwargs) def recvall(self, cnt): data = b'' while len(data) < cnt: cur = self.recv(cnt - len(data)) if not cur: raise EOFError('{0} bytes missing'.format(cnt - len(data))) data += cur return data
true
2
936
youtube_dl
youtube_dl.swfinterp
_ScopeDict
__repr__
def __repr__(self): return '%s__Scope(%s)' % ( self.avm_class.name, super(_ScopeDict, self).__repr__())
[ 59, 60 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Timer') TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'}) _builtin_classes = { StringClass.name: StringClass, ByteArrayClass.name: ByteArrayClass, TimerClass.name: TimerClass, TimerEventClass.name: TimerEventClass, } undefined = _Undefined() class _ScopeDict(dict): def __init__(self, avm_class): super(_ScopeDict, self).__init__() self.avm_class = avm_class def __repr__(self): return '%s__Scope(%s)' % ( self.avm_class.name, super(_ScopeDict, self).__repr__())
false
0
937
youtube_dl
youtube_dl.swfinterp
_AVMClass
register_methods
def register_methods(self, methods): self.method_names.update(methods.items()) self.method_idxs.update(dict( (idx, name) for name, idx in methods.items()))
[ 84, 86 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Timer') TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'}) _builtin_classes = { StringClass.name: StringClass, ByteArrayClass.name: ByteArrayClass, TimerClass.name: TimerClass, TimerEventClass.name: TimerEventClass, } undefined = _Undefined() class _AVMClass(object): def __init__(self, name_idx, name, static_properties=None): self.name_idx = name_idx self.name = name self.method_names = {} self.method_idxs = {} self.methods = {} self.method_pyfunctions = {} self.static_properties = static_properties if static_properties else {} self.variables = _ScopeDict(self) self.constants = {} def register_methods(self, methods): self.method_names.update(methods.items()) self.method_idxs.update(dict( (idx, name) for name, idx in methods.items()))
false
0
938
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
__init__
def __init__(self, file_contents): self._patched_functions = { (TimerClass, 'addEventListener'): lambda params: undefined, } code_tag = next(tag for tag_code, tag in _extract_tags(file_contents) if tag_code == 82) p = code_tag.index(b'\0', 4) + 1 code_reader = io.BytesIO(code_tag[p:]) # Parse ABC (AVM2 ByteCode) # Define a couple convenience methods u30 = lambda *args: _u30(*args, reader=code_reader) s32 = lambda *args: _s32(*args, reader=code_reader) u32 = lambda *args: _u32(*args, reader=code_reader) read_bytes = lambda *args: _read_bytes(*args, reader=code_reader) read_byte = lambda *args: _read_byte(*args, reader=code_reader) # minor_version + major_version read_bytes(2 + 2) # Constant pool int_count = u30() self.constant_ints = [0] for _c in range(1, int_count): self.constant_ints.append(s32()) self.constant_uints = [0] uint_count = u30() for _c in range(1, uint_count): self.constant_uints.append(u32()) double_count = u30() read_bytes(max(0, (double_count - 1)) * 8) string_count = u30() self.constant_strings = [''] for _c in range(1, string_count): s = _read_string(code_reader) self.constant_strings.append(s) namespace_count = u30() for _c in range(1, namespace_count): read_bytes(1) # kind u30() # name ns_set_count = u30() for _c in range(1, ns_set_count): count = u30() for _c2 in range(count): u30() multiname_count = u30() MULTINAME_SIZES = { 0x07: 2, # QName 0x0d: 2, # QNameA 0x0f: 1, # RTQName 0x10: 1, # RTQNameA 0x11: 0, # RTQNameL 0x12: 0, # RTQNameLA 0x09: 2, # Multiname 0x0e: 2, # MultinameA 0x1b: 1, # MultinameL 0x1c: 1, # MultinameLA } self.multinames = [''] for _c in range(1, multiname_count): kind = u30() assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind if kind == 0x07: u30() # namespace_idx name_idx = u30() self.multinames.append(self.constant_strings[name_idx]) elif kind == 0x09: name_idx = u30() u30() self.multinames.append(self.constant_strings[name_idx]) else: self.multinames.append(_Multiname(kind)) for _c2 in range(MULTINAME_SIZES[kind]): u30() # Methods method_count = u30() MethodInfo = collections.namedtuple( 'MethodInfo', ['NEED_ARGUMENTS', 'NEED_REST']) method_infos = [] for method_id in range(method_count): param_count = u30() u30() # return type for _ in range(param_count): u30() # param type u30() # name index (always 0 for youtube) flags = read_byte() if flags & 0x08 != 0: # Options present option_count = u30() for c in range(option_count): u30() # val read_bytes(1) # kind if flags & 0x80 != 0: # Param names present for _ in range(param_count): u30() # param name mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0) method_infos.append(mi) # Metadata metadata_count = u30() for _c in range(metadata_count): u30() # name item_count = u30() for _c2 in range(item_count): u30() # key u30() # value def parse_traits_info(): trait_name_idx = u30() kind_full = read_byte() kind = kind_full & 0x0f attrs = kind_full >> 4 methods = {} constants = None if kind == 0x00: # Slot u30() # Slot id u30() # type_name_idx vindex = u30() if vindex != 0: read_byte() # vkind elif kind == 0x06: # Const u30() # Slot id u30() # type_name_idx vindex = u30() vkind = 'any' if vindex != 0: vkind = read_byte() if vkind == 0x03: # Constant_Int value = self.constant_ints[vindex] elif vkind == 0x04: # Constant_UInt value = self.constant_uints[vindex] else: return {}, None # Ignore silently for now constants = {self.multinames[trait_name_idx]: value} elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter u30() # disp_id method_idx = u30() methods[self.multinames[trait_name_idx]] = method_idx elif kind == 0x04: # Class u30() # slot_id u30() # classi elif kind == 0x05: # Function u30() # slot_id function_idx = u30() methods[function_idx] = self.multinames[trait_name_idx] else: raise ExtractorError('Unsupported trait kind %d' % kind) if attrs & 0x4 != 0: # Metadata present metadata_count = u30() for _c3 in range(metadata_count): u30() # metadata index return methods, constants # Classes class_count = u30() classes = [] for class_id in range(class_count): name_idx = u30() cname = self.multinames[name_idx] avm_class = _AVMClass(name_idx, cname) classes.append(avm_class) u30() # super_name idx flags = read_byte() if flags & 0x08 != 0: # Protected namespace is present u30() # protected_ns_idx intrf_count = u30() for _c2 in range(intrf_count): u30() u30() # iinit trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) assert len(classes) == class_count self._classes_by_name = dict((c.name, c) for c in classes) for avm_class in classes: avm_class.cinit_idx = u30() trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) # Scripts script_count = u30() for _c in range(script_count): u30() # init trait_count = u30() for _c2 in range(trait_count): parse_traits_info() # Method bodies method_body_count = u30() Method = collections.namedtuple('Method', ['code', 'local_count']) self._all_methods = [] for _c in range(method_body_count): method_idx = u30() u30() # max_stack local_count = u30() u30() # init_scope_depth u30() # max_scope_depth code_length = u30() code = read_bytes(code_length) m = Method(code, local_count) self._all_methods.append(m) for avm_class in classes: if method_idx in avm_class.method_idxs: avm_class.methods[avm_class.method_idxs[method_idx]] = m exception_count = u30() for _c2 in range(exception_count): u30() # from u30() # to u30() # target u30() # exc_type u30() # var_name trait_count = u30() for _c2 in range(trait_count): parse_traits_info() assert p + code_reader.tell() == len(code_tag)
[ 185, 418 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Timer') TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'}) _builtin_classes = { StringClass.name: StringClass, ByteArrayClass.name: ByteArrayClass, TimerClass.name: TimerClass, TimerEventClass.name: TimerEventClass, } undefined = _Undefined() class _AVMClass(object): def __init__(self, name_idx, name, static_properties=None): self.name_idx = name_idx self.name = name self.method_names = {} self.method_idxs = {} self.methods = {} self.method_pyfunctions = {} self.static_properties = static_properties if static_properties else {} self.variables = _ScopeDict(self) self.constants = {} class _Multiname(object): def __init__(self, kind): self.kind = kind class SWFInterpreter(object): def __init__(self, file_contents): self._patched_functions = { (TimerClass, 'addEventListener'): lambda params: undefined, } code_tag = next(tag for tag_code, tag in _extract_tags(file_contents) if tag_code == 82) p = code_tag.index(b'\0', 4) + 1 code_reader = io.BytesIO(code_tag[p:]) # Parse ABC (AVM2 ByteCode) # Define a couple convenience methods u30 = lambda *args: _u30(*args, reader=code_reader) s32 = lambda *args: _s32(*args, reader=code_reader) u32 = lambda *args: _u32(*args, reader=code_reader) read_bytes = lambda *args: _read_bytes(*args, reader=code_reader) read_byte = lambda *args: _read_byte(*args, reader=code_reader) # minor_version + major_version read_bytes(2 + 2) # Constant pool int_count = u30() self.constant_ints = [0] for _c in range(1, int_count): self.constant_ints.append(s32()) self.constant_uints = [0] uint_count = u30() for _c in range(1, uint_count): self.constant_uints.append(u32()) double_count = u30() read_bytes(max(0, (double_count - 1)) * 8) string_count = u30() self.constant_strings = [''] for _c in range(1, string_count): s = _read_string(code_reader) self.constant_strings.append(s) namespace_count = u30() for _c in range(1, namespace_count): read_bytes(1) # kind u30() # name ns_set_count = u30() for _c in range(1, ns_set_count): count = u30() for _c2 in range(count): u30() multiname_count = u30() MULTINAME_SIZES = { 0x07: 2, # QName 0x0d: 2, # QNameA 0x0f: 1, # RTQName 0x10: 1, # RTQNameA 0x11: 0, # RTQNameL 0x12: 0, # RTQNameLA 0x09: 2, # Multiname 0x0e: 2, # MultinameA 0x1b: 1, # MultinameL 0x1c: 1, # MultinameLA } self.multinames = [''] for _c in range(1, multiname_count): kind = u30() assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind if kind == 0x07: u30() # namespace_idx name_idx = u30() self.multinames.append(self.constant_strings[name_idx]) elif kind == 0x09: name_idx = u30() u30() self.multinames.append(self.constant_strings[name_idx]) else: self.multinames.append(_Multiname(kind)) for _c2 in range(MULTINAME_SIZES[kind]): u30() # Methods method_count = u30() MethodInfo = collections.namedtuple( 'MethodInfo', ['NEED_ARGUMENTS', 'NEED_REST']) method_infos = [] for method_id in range(method_count): param_count = u30() u30() # return type for _ in range(param_count): u30() # param type u30() # name index (always 0 for youtube) flags = read_byte() if flags & 0x08 != 0: # Options present option_count = u30() for c in range(option_count): u30() # val read_bytes(1) # kind if flags & 0x80 != 0: # Param names present for _ in range(param_count): u30() # param name mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0) method_infos.append(mi) # Metadata metadata_count = u30() for _c in range(metadata_count): u30() # name item_count = u30() for _c2 in range(item_count): u30() # key u30() # value def parse_traits_info(): trait_name_idx = u30() kind_full = read_byte() kind = kind_full & 0x0f attrs = kind_full >> 4 methods = {} constants = None if kind == 0x00: # Slot u30() # Slot id u30() # type_name_idx vindex = u30() if vindex != 0: read_byte() # vkind elif kind == 0x06: # Const u30() # Slot id u30() # type_name_idx vindex = u30() vkind = 'any' if vindex != 0: vkind = read_byte() if vkind == 0x03: # Constant_Int value = self.constant_ints[vindex] elif vkind == 0x04: # Constant_UInt value = self.constant_uints[vindex] else: return {}, None # Ignore silently for now constants = {self.multinames[trait_name_idx]: value} elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter u30() # disp_id method_idx = u30() methods[self.multinames[trait_name_idx]] = method_idx elif kind == 0x04: # Class u30() # slot_id u30() # classi elif kind == 0x05: # Function u30() # slot_id function_idx = u30() methods[function_idx] = self.multinames[trait_name_idx] else: raise ExtractorError('Unsupported trait kind %d' % kind) if attrs & 0x4 != 0: # Metadata present metadata_count = u30() for _c3 in range(metadata_count): u30() # metadata index return methods, constants # Classes class_count = u30() classes = [] for class_id in range(class_count): name_idx = u30() cname = self.multinames[name_idx] avm_class = _AVMClass(name_idx, cname) classes.append(avm_class) u30() # super_name idx flags = read_byte() if flags & 0x08 != 0: # Protected namespace is present u30() # protected_ns_idx intrf_count = u30() for _c2 in range(intrf_count): u30() u30() # iinit trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) assert len(classes) == class_count self._classes_by_name = dict((c.name, c) for c in classes) for avm_class in classes: avm_class.cinit_idx = u30() trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) # Scripts script_count = u30() for _c in range(script_count): u30() # init trait_count = u30() for _c2 in range(trait_count): parse_traits_info() # Method bodies method_body_count = u30() Method = collections.namedtuple('Method', ['code', 'local_count']) self._all_methods = [] for _c in range(method_body_count): method_idx = u30() u30() # max_stack local_count = u30() u30() # init_scope_depth u30() # max_scope_depth code_length = u30() code = read_bytes(code_length) m = Method(code, local_count) self._all_methods.append(m) for avm_class in classes: if method_idx in avm_class.method_idxs: avm_class.methods[avm_class.method_idxs[method_idx]] = m exception_count = u30() for _c2 in range(exception_count): u30() # from u30() # to u30() # target u30() # exc_type u30() # var_name trait_count = u30() for _c2 in range(trait_count): parse_traits_info() assert p + code_reader.tell() == len(code_tag)
true
2
939
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
patch_function
def patch_function(self, avm_class, func_name, f): self._patched_functions[(avm_class, func_name)] = f
[ 420, 421 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Timer') TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'}) _builtin_classes = { StringClass.name: StringClass, ByteArrayClass.name: ByteArrayClass, TimerClass.name: TimerClass, TimerEventClass.name: TimerEventClass, } undefined = _Undefined() class SWFInterpreter(object): def __init__(self, file_contents): self._patched_functions = { (TimerClass, 'addEventListener'): lambda params: undefined, } code_tag = next(tag for tag_code, tag in _extract_tags(file_contents) if tag_code == 82) p = code_tag.index(b'\0', 4) + 1 code_reader = io.BytesIO(code_tag[p:]) # Parse ABC (AVM2 ByteCode) # Define a couple convenience methods u30 = lambda *args: _u30(*args, reader=code_reader) s32 = lambda *args: _s32(*args, reader=code_reader) u32 = lambda *args: _u32(*args, reader=code_reader) read_bytes = lambda *args: _read_bytes(*args, reader=code_reader) read_byte = lambda *args: _read_byte(*args, reader=code_reader) # minor_version + major_version read_bytes(2 + 2) # Constant pool int_count = u30() self.constant_ints = [0] for _c in range(1, int_count): self.constant_ints.append(s32()) self.constant_uints = [0] uint_count = u30() for _c in range(1, uint_count): self.constant_uints.append(u32()) double_count = u30() read_bytes(max(0, (double_count - 1)) * 8) string_count = u30() self.constant_strings = [''] for _c in range(1, string_count): s = _read_string(code_reader) self.constant_strings.append(s) namespace_count = u30() for _c in range(1, namespace_count): read_bytes(1) # kind u30() # name ns_set_count = u30() for _c in range(1, ns_set_count): count = u30() for _c2 in range(count): u30() multiname_count = u30() MULTINAME_SIZES = { 0x07: 2, # QName 0x0d: 2, # QNameA 0x0f: 1, # RTQName 0x10: 1, # RTQNameA 0x11: 0, # RTQNameL 0x12: 0, # RTQNameLA 0x09: 2, # Multiname 0x0e: 2, # MultinameA 0x1b: 1, # MultinameL 0x1c: 1, # MultinameLA } self.multinames = [''] for _c in range(1, multiname_count): kind = u30() assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind if kind == 0x07: u30() # namespace_idx name_idx = u30() self.multinames.append(self.constant_strings[name_idx]) elif kind == 0x09: name_idx = u30() u30() self.multinames.append(self.constant_strings[name_idx]) else: self.multinames.append(_Multiname(kind)) for _c2 in range(MULTINAME_SIZES[kind]): u30() # Methods method_count = u30() MethodInfo = collections.namedtuple( 'MethodInfo', ['NEED_ARGUMENTS', 'NEED_REST']) method_infos = [] for method_id in range(method_count): param_count = u30() u30() # return type for _ in range(param_count): u30() # param type u30() # name index (always 0 for youtube) flags = read_byte() if flags & 0x08 != 0: # Options present option_count = u30() for c in range(option_count): u30() # val read_bytes(1) # kind if flags & 0x80 != 0: # Param names present for _ in range(param_count): u30() # param name mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0) method_infos.append(mi) # Metadata metadata_count = u30() for _c in range(metadata_count): u30() # name item_count = u30() for _c2 in range(item_count): u30() # key u30() # value def parse_traits_info(): trait_name_idx = u30() kind_full = read_byte() kind = kind_full & 0x0f attrs = kind_full >> 4 methods = {} constants = None if kind == 0x00: # Slot u30() # Slot id u30() # type_name_idx vindex = u30() if vindex != 0: read_byte() # vkind elif kind == 0x06: # Const u30() # Slot id u30() # type_name_idx vindex = u30() vkind = 'any' if vindex != 0: vkind = read_byte() if vkind == 0x03: # Constant_Int value = self.constant_ints[vindex] elif vkind == 0x04: # Constant_UInt value = self.constant_uints[vindex] else: return {}, None # Ignore silently for now constants = {self.multinames[trait_name_idx]: value} elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter u30() # disp_id method_idx = u30() methods[self.multinames[trait_name_idx]] = method_idx elif kind == 0x04: # Class u30() # slot_id u30() # classi elif kind == 0x05: # Function u30() # slot_id function_idx = u30() methods[function_idx] = self.multinames[trait_name_idx] else: raise ExtractorError('Unsupported trait kind %d' % kind) if attrs & 0x4 != 0: # Metadata present metadata_count = u30() for _c3 in range(metadata_count): u30() # metadata index return methods, constants # Classes class_count = u30() classes = [] for class_id in range(class_count): name_idx = u30() cname = self.multinames[name_idx] avm_class = _AVMClass(name_idx, cname) classes.append(avm_class) u30() # super_name idx flags = read_byte() if flags & 0x08 != 0: # Protected namespace is present u30() # protected_ns_idx intrf_count = u30() for _c2 in range(intrf_count): u30() u30() # iinit trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) assert len(classes) == class_count self._classes_by_name = dict((c.name, c) for c in classes) for avm_class in classes: avm_class.cinit_idx = u30() trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) # Scripts script_count = u30() for _c in range(script_count): u30() # init trait_count = u30() for _c2 in range(trait_count): parse_traits_info() # Method bodies method_body_count = u30() Method = collections.namedtuple('Method', ['code', 'local_count']) self._all_methods = [] for _c in range(method_body_count): method_idx = u30() u30() # max_stack local_count = u30() u30() # init_scope_depth u30() # max_scope_depth code_length = u30() code = read_bytes(code_length) m = Method(code, local_count) self._all_methods.append(m) for avm_class in classes: if method_idx in avm_class.method_idxs: avm_class.methods[avm_class.method_idxs[method_idx]] = m exception_count = u30() for _c2 in range(exception_count): u30() # from u30() # to u30() # target u30() # exc_type u30() # var_name trait_count = u30() for _c2 in range(trait_count): parse_traits_info() assert p + code_reader.tell() == len(code_tag) def patch_function(self, avm_class, func_name, f): self._patched_functions[(avm_class, func_name)] = f
false
0
940
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
extract_class
def extract_class(self, class_name, call_cinit=True): try: res = self._classes_by_name[class_name] except KeyError: raise ExtractorError('Class %r not found' % class_name) if call_cinit and hasattr(res, 'cinit_idx'): res.register_methods({'$cinit': res.cinit_idx}) res.methods['$cinit'] = self._all_methods[res.cinit_idx] cinit = self.extract_function(res, '$cinit') cinit([]) return res
[ 423, 435 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Timer') TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'}) _builtin_classes = { StringClass.name: StringClass, ByteArrayClass.name: ByteArrayClass, TimerClass.name: TimerClass, TimerEventClass.name: TimerEventClass, } undefined = _Undefined() class SWFInterpreter(object): def __init__(self, file_contents): self._patched_functions = { (TimerClass, 'addEventListener'): lambda params: undefined, } code_tag = next(tag for tag_code, tag in _extract_tags(file_contents) if tag_code == 82) p = code_tag.index(b'\0', 4) + 1 code_reader = io.BytesIO(code_tag[p:]) # Parse ABC (AVM2 ByteCode) # Define a couple convenience methods u30 = lambda *args: _u30(*args, reader=code_reader) s32 = lambda *args: _s32(*args, reader=code_reader) u32 = lambda *args: _u32(*args, reader=code_reader) read_bytes = lambda *args: _read_bytes(*args, reader=code_reader) read_byte = lambda *args: _read_byte(*args, reader=code_reader) # minor_version + major_version read_bytes(2 + 2) # Constant pool int_count = u30() self.constant_ints = [0] for _c in range(1, int_count): self.constant_ints.append(s32()) self.constant_uints = [0] uint_count = u30() for _c in range(1, uint_count): self.constant_uints.append(u32()) double_count = u30() read_bytes(max(0, (double_count - 1)) * 8) string_count = u30() self.constant_strings = [''] for _c in range(1, string_count): s = _read_string(code_reader) self.constant_strings.append(s) namespace_count = u30() for _c in range(1, namespace_count): read_bytes(1) # kind u30() # name ns_set_count = u30() for _c in range(1, ns_set_count): count = u30() for _c2 in range(count): u30() multiname_count = u30() MULTINAME_SIZES = { 0x07: 2, # QName 0x0d: 2, # QNameA 0x0f: 1, # RTQName 0x10: 1, # RTQNameA 0x11: 0, # RTQNameL 0x12: 0, # RTQNameLA 0x09: 2, # Multiname 0x0e: 2, # MultinameA 0x1b: 1, # MultinameL 0x1c: 1, # MultinameLA } self.multinames = [''] for _c in range(1, multiname_count): kind = u30() assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind if kind == 0x07: u30() # namespace_idx name_idx = u30() self.multinames.append(self.constant_strings[name_idx]) elif kind == 0x09: name_idx = u30() u30() self.multinames.append(self.constant_strings[name_idx]) else: self.multinames.append(_Multiname(kind)) for _c2 in range(MULTINAME_SIZES[kind]): u30() # Methods method_count = u30() MethodInfo = collections.namedtuple( 'MethodInfo', ['NEED_ARGUMENTS', 'NEED_REST']) method_infos = [] for method_id in range(method_count): param_count = u30() u30() # return type for _ in range(param_count): u30() # param type u30() # name index (always 0 for youtube) flags = read_byte() if flags & 0x08 != 0: # Options present option_count = u30() for c in range(option_count): u30() # val read_bytes(1) # kind if flags & 0x80 != 0: # Param names present for _ in range(param_count): u30() # param name mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0) method_infos.append(mi) # Metadata metadata_count = u30() for _c in range(metadata_count): u30() # name item_count = u30() for _c2 in range(item_count): u30() # key u30() # value def parse_traits_info(): trait_name_idx = u30() kind_full = read_byte() kind = kind_full & 0x0f attrs = kind_full >> 4 methods = {} constants = None if kind == 0x00: # Slot u30() # Slot id u30() # type_name_idx vindex = u30() if vindex != 0: read_byte() # vkind elif kind == 0x06: # Const u30() # Slot id u30() # type_name_idx vindex = u30() vkind = 'any' if vindex != 0: vkind = read_byte() if vkind == 0x03: # Constant_Int value = self.constant_ints[vindex] elif vkind == 0x04: # Constant_UInt value = self.constant_uints[vindex] else: return {}, None # Ignore silently for now constants = {self.multinames[trait_name_idx]: value} elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter u30() # disp_id method_idx = u30() methods[self.multinames[trait_name_idx]] = method_idx elif kind == 0x04: # Class u30() # slot_id u30() # classi elif kind == 0x05: # Function u30() # slot_id function_idx = u30() methods[function_idx] = self.multinames[trait_name_idx] else: raise ExtractorError('Unsupported trait kind %d' % kind) if attrs & 0x4 != 0: # Metadata present metadata_count = u30() for _c3 in range(metadata_count): u30() # metadata index return methods, constants # Classes class_count = u30() classes = [] for class_id in range(class_count): name_idx = u30() cname = self.multinames[name_idx] avm_class = _AVMClass(name_idx, cname) classes.append(avm_class) u30() # super_name idx flags = read_byte() if flags & 0x08 != 0: # Protected namespace is present u30() # protected_ns_idx intrf_count = u30() for _c2 in range(intrf_count): u30() u30() # iinit trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) assert len(classes) == class_count self._classes_by_name = dict((c.name, c) for c in classes) for avm_class in classes: avm_class.cinit_idx = u30() trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) # Scripts script_count = u30() for _c in range(script_count): u30() # init trait_count = u30() for _c2 in range(trait_count): parse_traits_info() # Method bodies method_body_count = u30() Method = collections.namedtuple('Method', ['code', 'local_count']) self._all_methods = [] for _c in range(method_body_count): method_idx = u30() u30() # max_stack local_count = u30() u30() # init_scope_depth u30() # max_scope_depth code_length = u30() code = read_bytes(code_length) m = Method(code, local_count) self._all_methods.append(m) for avm_class in classes: if method_idx in avm_class.method_idxs: avm_class.methods[avm_class.method_idxs[method_idx]] = m exception_count = u30() for _c2 in range(exception_count): u30() # from u30() # to u30() # target u30() # exc_type u30() # var_name trait_count = u30() for _c2 in range(trait_count): parse_traits_info() assert p + code_reader.tell() == len(code_tag) def extract_class(self, class_name, call_cinit=True): try: res = self._classes_by_name[class_name] except KeyError: raise ExtractorError('Class %r not found' % class_name) if call_cinit and hasattr(res, 'cinit_idx'): res.register_methods({'$cinit': res.cinit_idx}) res.methods['$cinit'] = self._all_methods[res.cinit_idx] cinit = self.extract_function(res, '$cinit') cinit([]) return res
true
2
941
youtube_dl
youtube_dl.swfinterp
SWFInterpreter
extract_function
def extract_function(self, avm_class, func_name): p = self._patched_functions.get((avm_class, func_name)) if p: return p if func_name in avm_class.method_pyfunctions: return avm_class.method_pyfunctions[func_name] if func_name in self._classes_by_name: return self._classes_by_name[func_name].make_object() if func_name not in avm_class.methods: raise ExtractorError('Cannot find function %s.%s' % ( avm_class.name, func_name)) m = avm_class.methods[func_name] def resfunc(args): # Helper functions coder = io.BytesIO(m.code) s24 = lambda: _s24(coder) u30 = lambda: _u30(coder) registers = [avm_class.variables] + list(args) + [None] * m.local_count stack = [] scopes = collections.deque([ self._classes_by_name, avm_class.constants, avm_class.variables]) while True: opcode = _read_byte(coder) if opcode == 9: # label pass # Spec says: "Do nothing." elif opcode == 16: # jump offset = s24() coder.seek(coder.tell() + offset) elif opcode == 17: # iftrue offset = s24() value = stack.pop() if value: coder.seek(coder.tell() + offset) elif opcode == 18: # iffalse offset = s24() value = stack.pop() if not value: coder.seek(coder.tell() + offset) elif opcode == 19: # ifeq offset = s24() value2 = stack.pop() value1 = stack.pop() if value2 == value1: coder.seek(coder.tell() + offset) elif opcode == 20: # ifne offset = s24() value2 = stack.pop() value1 = stack.pop() if value2 != value1: coder.seek(coder.tell() + offset) elif opcode == 21: # iflt offset = s24() value2 = stack.pop() value1 = stack.pop() if value1 < value2: coder.seek(coder.tell() + offset) elif opcode == 32: # pushnull stack.append(None) elif opcode == 33: # pushundefined stack.append(undefined) elif opcode == 36: # pushbyte v = _read_byte(coder) stack.append(v) elif opcode == 37: # pushshort v = u30() stack.append(v) elif opcode == 38: # pushtrue stack.append(True) elif opcode == 39: # pushfalse stack.append(False) elif opcode == 40: # pushnan stack.append(float('NaN')) elif opcode == 42: # dup value = stack[-1] stack.append(value) elif opcode == 44: # pushstring idx = u30() stack.append(self.constant_strings[idx]) elif opcode == 48: # pushscope new_scope = stack.pop() scopes.append(new_scope) elif opcode == 66: # construct arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() res = obj.avm_class.make_object() stack.append(res) elif opcode == 70: # callproperty index = u30() mname = self.multinames[index] arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() if obj == StringClass: if mname == 'String': assert len(args) == 1 assert isinstance(args[0], ( int, compat_str, _Undefined)) if args[0] == undefined: res = 'undefined' else: res = compat_str(args[0]) stack.append(res) continue else: raise NotImplementedError( 'Function String.%s is not yet implemented' % mname) elif isinstance(obj, _AVMClass_Object): func = self.extract_function(obj.avm_class, mname) res = func(args) stack.append(res) continue elif isinstance(obj, _AVMClass): func = self.extract_function(obj, mname) res = func(args) stack.append(res) continue elif isinstance(obj, _ScopeDict): if mname in obj.avm_class.method_names: func = self.extract_function(obj.avm_class, mname) res = func(args) else: res = obj[mname] stack.append(res) continue elif isinstance(obj, compat_str): if mname == 'split': assert len(args) == 1 assert isinstance(args[0], compat_str) if args[0] == '': res = list(obj) else: res = obj.split(args[0]) stack.append(res) continue elif mname == 'charCodeAt': assert len(args) <= 1 idx = 0 if len(args) == 0 else args[0] assert isinstance(idx, int) res = ord(obj[idx]) stack.append(res) continue elif isinstance(obj, list): if mname == 'slice': assert len(args) == 1 assert isinstance(args[0], int) res = obj[args[0]:] stack.append(res) continue elif mname == 'join': assert len(args) == 1 assert isinstance(args[0], compat_str) res = args[0].join(obj) stack.append(res) continue raise NotImplementedError( 'Unsupported property %r on %r' % (mname, obj)) elif opcode == 71: # returnvoid res = undefined return res elif opcode == 72: # returnvalue res = stack.pop() return res elif opcode == 73: # constructsuper # Not yet implemented, just hope it works without it arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() elif opcode == 74: # constructproperty index = u30() arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() mname = self.multinames[index] assert isinstance(obj, _AVMClass) # We do not actually call the constructor for now; # we just pretend it does nothing stack.append(obj.make_object()) elif opcode == 79: # callpropvoid index = u30() mname = self.multinames[index] arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() if isinstance(obj, _AVMClass_Object): func = self.extract_function(obj.avm_class, mname) res = func(args) assert res is undefined continue if isinstance(obj, _ScopeDict): assert mname in obj.avm_class.method_names func = self.extract_function(obj.avm_class, mname) res = func(args) assert res is undefined continue if mname == 'reverse': assert isinstance(obj, list) obj.reverse() else: raise NotImplementedError( 'Unsupported (void) property %r on %r' % (mname, obj)) elif opcode == 86: # newarray arg_count = u30() arr = [] for i in range(arg_count): arr.append(stack.pop()) arr = arr[::-1] stack.append(arr) elif opcode == 93: # findpropstrict index = u30() mname = self.multinames[index] for s in reversed(scopes): if mname in s: res = s break else: res = scopes[0] if mname not in res and mname in _builtin_classes: stack.append(_builtin_classes[mname]) else: stack.append(res[mname]) elif opcode == 94: # findproperty index = u30() mname = self.multinames[index] for s in reversed(scopes): if mname in s: res = s break else: res = avm_class.variables stack.append(res) elif opcode == 96: # getlex index = u30() mname = self.multinames[index] for s in reversed(scopes): if mname in s: scope = s break else: scope = avm_class.variables if mname in scope: res = scope[mname] elif mname in _builtin_classes: res = _builtin_classes[mname] else: # Assume uninitialized # TODO warn here res = undefined stack.append(res) elif opcode == 97: # setproperty index = u30() value = stack.pop() idx = self.multinames[index] if isinstance(idx, _Multiname): idx = stack.pop() obj = stack.pop() obj[idx] = value elif opcode == 98: # getlocal index = u30() stack.append(registers[index]) elif opcode == 99: # setlocal index = u30() value = stack.pop() registers[index] = value elif opcode == 102: # getproperty index = u30() pname = self.multinames[index] if pname == 'length': obj = stack.pop() assert isinstance(obj, (compat_str, list)) stack.append(len(obj)) elif isinstance(pname, compat_str): # Member access obj = stack.pop() if isinstance(obj, _AVMClass): res = obj.static_properties[pname] stack.append(res) continue assert isinstance(obj, (dict, _ScopeDict)),\ 'Accessing member %r on %r' % (pname, obj) res = obj.get(pname, undefined) stack.append(res) else: # Assume attribute access idx = stack.pop() assert isinstance(idx, int) obj = stack.pop() assert isinstance(obj, list) stack.append(obj[idx]) elif opcode == 104: # initproperty index = u30() value = stack.pop() idx = self.multinames[index] if isinstance(idx, _Multiname): idx = stack.pop() obj = stack.pop() obj[idx] = value elif opcode == 115: # convert_ value = stack.pop() intvalue = int(value) stack.append(intvalue) elif opcode == 128: # coerce u30() elif opcode == 130: # coerce_a value = stack.pop() # um, yes, it's any value stack.append(value) elif opcode == 133: # coerce_s assert isinstance(stack[-1], (type(None), compat_str)) elif opcode == 147: # decrement value = stack.pop() assert isinstance(value, int) stack.append(value - 1) elif opcode == 149: # typeof value = stack.pop() return { _Undefined: 'undefined', compat_str: 'String', int: 'Number', float: 'Number', }[type(value)] elif opcode == 160: # add value2 = stack.pop() value1 = stack.pop() res = value1 + value2 stack.append(res) elif opcode == 161: # subtract value2 = stack.pop() value1 = stack.pop() res = value1 - value2 stack.append(res) elif opcode == 162: # multiply value2 = stack.pop() value1 = stack.pop() res = value1 * value2 stack.append(res) elif opcode == 164: # modulo value2 = stack.pop() value1 = stack.pop() res = value1 % value2 stack.append(res) elif opcode == 168: # bitand value2 = stack.pop() value1 = stack.pop() assert isinstance(value1, int) assert isinstance(value2, int) res = value1 & value2 stack.append(res) elif opcode == 171: # equals value2 = stack.pop() value1 = stack.pop() result = value1 == value2 stack.append(result) elif opcode == 175: # greaterequals value2 = stack.pop() value1 = stack.pop() result = value1 >= value2 stack.append(result) elif opcode == 192: # increment_i value = stack.pop() assert isinstance(value, int) stack.append(value + 1) elif opcode == 208: # getlocal_0 stack.append(registers[0]) elif opcode == 209: # getlocal_1 stack.append(registers[1]) elif opcode == 210: # getlocal_2 stack.append(registers[2]) elif opcode == 211: # getlocal_3 stack.append(registers[3]) elif opcode == 212: # setlocal_0 registers[0] = stack.pop() elif opcode == 213: # setlocal_1 registers[1] = stack.pop() elif opcode == 214: # setlocal_2 registers[2] = stack.pop() elif opcode == 215: # setlocal_3 registers[3] = stack.pop() else: raise NotImplementedError( 'Unsupported opcode %d' % opcode) avm_class.method_pyfunctions[func_name] = resfunc return resfunc
[ 437, 833 ]
false
[ "_u32", "StringClass", "ByteArrayClass", "TimerClass", "TimerEventClass", "_builtin_classes", "undefined" ]
import collections import io import zlib from .compat import ( compat_str, compat_struct_unpack, ) from .utils import ( ExtractorError, ) _u32 = _read_int StringClass = _AVMClass('(no name idx)', 'String') ByteArrayClass = _AVMClass('(no name idx)', 'ByteArray') TimerClass = _AVMClass('(no name idx)', 'Timer') TimerEventClass = _AVMClass('(no name idx)', 'TimerEvent', {'TIMER': 'timer'}) _builtin_classes = { StringClass.name: StringClass, ByteArrayClass.name: ByteArrayClass, TimerClass.name: TimerClass, TimerEventClass.name: TimerEventClass, } undefined = _Undefined() class _AVMClass_Object(object): def __init__(self, avm_class): self.avm_class = avm_class class _ScopeDict(dict): def __init__(self, avm_class): super(_ScopeDict, self).__init__() self.avm_class = avm_class class _AVMClass(object): def __init__(self, name_idx, name, static_properties=None): self.name_idx = name_idx self.name = name self.method_names = {} self.method_idxs = {} self.methods = {} self.method_pyfunctions = {} self.static_properties = static_properties if static_properties else {} self.variables = _ScopeDict(self) self.constants = {} class _Multiname(object): def __init__(self, kind): self.kind = kind class SWFInterpreter(object): def __init__(self, file_contents): self._patched_functions = { (TimerClass, 'addEventListener'): lambda params: undefined, } code_tag = next(tag for tag_code, tag in _extract_tags(file_contents) if tag_code == 82) p = code_tag.index(b'\0', 4) + 1 code_reader = io.BytesIO(code_tag[p:]) # Parse ABC (AVM2 ByteCode) # Define a couple convenience methods u30 = lambda *args: _u30(*args, reader=code_reader) s32 = lambda *args: _s32(*args, reader=code_reader) u32 = lambda *args: _u32(*args, reader=code_reader) read_bytes = lambda *args: _read_bytes(*args, reader=code_reader) read_byte = lambda *args: _read_byte(*args, reader=code_reader) # minor_version + major_version read_bytes(2 + 2) # Constant pool int_count = u30() self.constant_ints = [0] for _c in range(1, int_count): self.constant_ints.append(s32()) self.constant_uints = [0] uint_count = u30() for _c in range(1, uint_count): self.constant_uints.append(u32()) double_count = u30() read_bytes(max(0, (double_count - 1)) * 8) string_count = u30() self.constant_strings = [''] for _c in range(1, string_count): s = _read_string(code_reader) self.constant_strings.append(s) namespace_count = u30() for _c in range(1, namespace_count): read_bytes(1) # kind u30() # name ns_set_count = u30() for _c in range(1, ns_set_count): count = u30() for _c2 in range(count): u30() multiname_count = u30() MULTINAME_SIZES = { 0x07: 2, # QName 0x0d: 2, # QNameA 0x0f: 1, # RTQName 0x10: 1, # RTQNameA 0x11: 0, # RTQNameL 0x12: 0, # RTQNameLA 0x09: 2, # Multiname 0x0e: 2, # MultinameA 0x1b: 1, # MultinameL 0x1c: 1, # MultinameLA } self.multinames = [''] for _c in range(1, multiname_count): kind = u30() assert kind in MULTINAME_SIZES, 'Invalid multiname kind %r' % kind if kind == 0x07: u30() # namespace_idx name_idx = u30() self.multinames.append(self.constant_strings[name_idx]) elif kind == 0x09: name_idx = u30() u30() self.multinames.append(self.constant_strings[name_idx]) else: self.multinames.append(_Multiname(kind)) for _c2 in range(MULTINAME_SIZES[kind]): u30() # Methods method_count = u30() MethodInfo = collections.namedtuple( 'MethodInfo', ['NEED_ARGUMENTS', 'NEED_REST']) method_infos = [] for method_id in range(method_count): param_count = u30() u30() # return type for _ in range(param_count): u30() # param type u30() # name index (always 0 for youtube) flags = read_byte() if flags & 0x08 != 0: # Options present option_count = u30() for c in range(option_count): u30() # val read_bytes(1) # kind if flags & 0x80 != 0: # Param names present for _ in range(param_count): u30() # param name mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0) method_infos.append(mi) # Metadata metadata_count = u30() for _c in range(metadata_count): u30() # name item_count = u30() for _c2 in range(item_count): u30() # key u30() # value def parse_traits_info(): trait_name_idx = u30() kind_full = read_byte() kind = kind_full & 0x0f attrs = kind_full >> 4 methods = {} constants = None if kind == 0x00: # Slot u30() # Slot id u30() # type_name_idx vindex = u30() if vindex != 0: read_byte() # vkind elif kind == 0x06: # Const u30() # Slot id u30() # type_name_idx vindex = u30() vkind = 'any' if vindex != 0: vkind = read_byte() if vkind == 0x03: # Constant_Int value = self.constant_ints[vindex] elif vkind == 0x04: # Constant_UInt value = self.constant_uints[vindex] else: return {}, None # Ignore silently for now constants = {self.multinames[trait_name_idx]: value} elif kind in (0x01, 0x02, 0x03): # Method / Getter / Setter u30() # disp_id method_idx = u30() methods[self.multinames[trait_name_idx]] = method_idx elif kind == 0x04: # Class u30() # slot_id u30() # classi elif kind == 0x05: # Function u30() # slot_id function_idx = u30() methods[function_idx] = self.multinames[trait_name_idx] else: raise ExtractorError('Unsupported trait kind %d' % kind) if attrs & 0x4 != 0: # Metadata present metadata_count = u30() for _c3 in range(metadata_count): u30() # metadata index return methods, constants # Classes class_count = u30() classes = [] for class_id in range(class_count): name_idx = u30() cname = self.multinames[name_idx] avm_class = _AVMClass(name_idx, cname) classes.append(avm_class) u30() # super_name idx flags = read_byte() if flags & 0x08 != 0: # Protected namespace is present u30() # protected_ns_idx intrf_count = u30() for _c2 in range(intrf_count): u30() u30() # iinit trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) assert len(classes) == class_count self._classes_by_name = dict((c.name, c) for c in classes) for avm_class in classes: avm_class.cinit_idx = u30() trait_count = u30() for _c2 in range(trait_count): trait_methods, trait_constants = parse_traits_info() avm_class.register_methods(trait_methods) if trait_constants: avm_class.constants.update(trait_constants) # Scripts script_count = u30() for _c in range(script_count): u30() # init trait_count = u30() for _c2 in range(trait_count): parse_traits_info() # Method bodies method_body_count = u30() Method = collections.namedtuple('Method', ['code', 'local_count']) self._all_methods = [] for _c in range(method_body_count): method_idx = u30() u30() # max_stack local_count = u30() u30() # init_scope_depth u30() # max_scope_depth code_length = u30() code = read_bytes(code_length) m = Method(code, local_count) self._all_methods.append(m) for avm_class in classes: if method_idx in avm_class.method_idxs: avm_class.methods[avm_class.method_idxs[method_idx]] = m exception_count = u30() for _c2 in range(exception_count): u30() # from u30() # to u30() # target u30() # exc_type u30() # var_name trait_count = u30() for _c2 in range(trait_count): parse_traits_info() assert p + code_reader.tell() == len(code_tag) def extract_function(self, avm_class, func_name): p = self._patched_functions.get((avm_class, func_name)) if p: return p if func_name in avm_class.method_pyfunctions: return avm_class.method_pyfunctions[func_name] if func_name in self._classes_by_name: return self._classes_by_name[func_name].make_object() if func_name not in avm_class.methods: raise ExtractorError('Cannot find function %s.%s' % ( avm_class.name, func_name)) m = avm_class.methods[func_name] def resfunc(args): # Helper functions coder = io.BytesIO(m.code) s24 = lambda: _s24(coder) u30 = lambda: _u30(coder) registers = [avm_class.variables] + list(args) + [None] * m.local_count stack = [] scopes = collections.deque([ self._classes_by_name, avm_class.constants, avm_class.variables]) while True: opcode = _read_byte(coder) if opcode == 9: # label pass # Spec says: "Do nothing." elif opcode == 16: # jump offset = s24() coder.seek(coder.tell() + offset) elif opcode == 17: # iftrue offset = s24() value = stack.pop() if value: coder.seek(coder.tell() + offset) elif opcode == 18: # iffalse offset = s24() value = stack.pop() if not value: coder.seek(coder.tell() + offset) elif opcode == 19: # ifeq offset = s24() value2 = stack.pop() value1 = stack.pop() if value2 == value1: coder.seek(coder.tell() + offset) elif opcode == 20: # ifne offset = s24() value2 = stack.pop() value1 = stack.pop() if value2 != value1: coder.seek(coder.tell() + offset) elif opcode == 21: # iflt offset = s24() value2 = stack.pop() value1 = stack.pop() if value1 < value2: coder.seek(coder.tell() + offset) elif opcode == 32: # pushnull stack.append(None) elif opcode == 33: # pushundefined stack.append(undefined) elif opcode == 36: # pushbyte v = _read_byte(coder) stack.append(v) elif opcode == 37: # pushshort v = u30() stack.append(v) elif opcode == 38: # pushtrue stack.append(True) elif opcode == 39: # pushfalse stack.append(False) elif opcode == 40: # pushnan stack.append(float('NaN')) elif opcode == 42: # dup value = stack[-1] stack.append(value) elif opcode == 44: # pushstring idx = u30() stack.append(self.constant_strings[idx]) elif opcode == 48: # pushscope new_scope = stack.pop() scopes.append(new_scope) elif opcode == 66: # construct arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() res = obj.avm_class.make_object() stack.append(res) elif opcode == 70: # callproperty index = u30() mname = self.multinames[index] arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() if obj == StringClass: if mname == 'String': assert len(args) == 1 assert isinstance(args[0], ( int, compat_str, _Undefined)) if args[0] == undefined: res = 'undefined' else: res = compat_str(args[0]) stack.append(res) continue else: raise NotImplementedError( 'Function String.%s is not yet implemented' % mname) elif isinstance(obj, _AVMClass_Object): func = self.extract_function(obj.avm_class, mname) res = func(args) stack.append(res) continue elif isinstance(obj, _AVMClass): func = self.extract_function(obj, mname) res = func(args) stack.append(res) continue elif isinstance(obj, _ScopeDict): if mname in obj.avm_class.method_names: func = self.extract_function(obj.avm_class, mname) res = func(args) else: res = obj[mname] stack.append(res) continue elif isinstance(obj, compat_str): if mname == 'split': assert len(args) == 1 assert isinstance(args[0], compat_str) if args[0] == '': res = list(obj) else: res = obj.split(args[0]) stack.append(res) continue elif mname == 'charCodeAt': assert len(args) <= 1 idx = 0 if len(args) == 0 else args[0] assert isinstance(idx, int) res = ord(obj[idx]) stack.append(res) continue elif isinstance(obj, list): if mname == 'slice': assert len(args) == 1 assert isinstance(args[0], int) res = obj[args[0]:] stack.append(res) continue elif mname == 'join': assert len(args) == 1 assert isinstance(args[0], compat_str) res = args[0].join(obj) stack.append(res) continue raise NotImplementedError( 'Unsupported property %r on %r' % (mname, obj)) elif opcode == 71: # returnvoid res = undefined return res elif opcode == 72: # returnvalue res = stack.pop() return res elif opcode == 73: # constructsuper # Not yet implemented, just hope it works without it arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() elif opcode == 74: # constructproperty index = u30() arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() mname = self.multinames[index] assert isinstance(obj, _AVMClass) # We do not actually call the constructor for now; # we just pretend it does nothing stack.append(obj.make_object()) elif opcode == 79: # callpropvoid index = u30() mname = self.multinames[index] arg_count = u30() args = list(reversed( [stack.pop() for _ in range(arg_count)])) obj = stack.pop() if isinstance(obj, _AVMClass_Object): func = self.extract_function(obj.avm_class, mname) res = func(args) assert res is undefined continue if isinstance(obj, _ScopeDict): assert mname in obj.avm_class.method_names func = self.extract_function(obj.avm_class, mname) res = func(args) assert res is undefined continue if mname == 'reverse': assert isinstance(obj, list) obj.reverse() else: raise NotImplementedError( 'Unsupported (void) property %r on %r' % (mname, obj)) elif opcode == 86: # newarray arg_count = u30() arr = [] for i in range(arg_count): arr.append(stack.pop()) arr = arr[::-1] stack.append(arr) elif opcode == 93: # findpropstrict index = u30() mname = self.multinames[index] for s in reversed(scopes): if mname in s: res = s break else: res = scopes[0] if mname not in res and mname in _builtin_classes: stack.append(_builtin_classes[mname]) else: stack.append(res[mname]) elif opcode == 94: # findproperty index = u30() mname = self.multinames[index] for s in reversed(scopes): if mname in s: res = s break else: res = avm_class.variables stack.append(res) elif opcode == 96: # getlex index = u30() mname = self.multinames[index] for s in reversed(scopes): if mname in s: scope = s break else: scope = avm_class.variables if mname in scope: res = scope[mname] elif mname in _builtin_classes: res = _builtin_classes[mname] else: # Assume uninitialized # TODO warn here res = undefined stack.append(res) elif opcode == 97: # setproperty index = u30() value = stack.pop() idx = self.multinames[index] if isinstance(idx, _Multiname): idx = stack.pop() obj = stack.pop() obj[idx] = value elif opcode == 98: # getlocal index = u30() stack.append(registers[index]) elif opcode == 99: # setlocal index = u30() value = stack.pop() registers[index] = value elif opcode == 102: # getproperty index = u30() pname = self.multinames[index] if pname == 'length': obj = stack.pop() assert isinstance(obj, (compat_str, list)) stack.append(len(obj)) elif isinstance(pname, compat_str): # Member access obj = stack.pop() if isinstance(obj, _AVMClass): res = obj.static_properties[pname] stack.append(res) continue assert isinstance(obj, (dict, _ScopeDict)),\ 'Accessing member %r on %r' % (pname, obj) res = obj.get(pname, undefined) stack.append(res) else: # Assume attribute access idx = stack.pop() assert isinstance(idx, int) obj = stack.pop() assert isinstance(obj, list) stack.append(obj[idx]) elif opcode == 104: # initproperty index = u30() value = stack.pop() idx = self.multinames[index] if isinstance(idx, _Multiname): idx = stack.pop() obj = stack.pop() obj[idx] = value elif opcode == 115: # convert_ value = stack.pop() intvalue = int(value) stack.append(intvalue) elif opcode == 128: # coerce u30() elif opcode == 130: # coerce_a value = stack.pop() # um, yes, it's any value stack.append(value) elif opcode == 133: # coerce_s assert isinstance(stack[-1], (type(None), compat_str)) elif opcode == 147: # decrement value = stack.pop() assert isinstance(value, int) stack.append(value - 1) elif opcode == 149: # typeof value = stack.pop() return { _Undefined: 'undefined', compat_str: 'String', int: 'Number', float: 'Number', }[type(value)] elif opcode == 160: # add value2 = stack.pop() value1 = stack.pop() res = value1 + value2 stack.append(res) elif opcode == 161: # subtract value2 = stack.pop() value1 = stack.pop() res = value1 - value2 stack.append(res) elif opcode == 162: # multiply value2 = stack.pop() value1 = stack.pop() res = value1 * value2 stack.append(res) elif opcode == 164: # modulo value2 = stack.pop() value1 = stack.pop() res = value1 % value2 stack.append(res) elif opcode == 168: # bitand value2 = stack.pop() value1 = stack.pop() assert isinstance(value1, int) assert isinstance(value2, int) res = value1 & value2 stack.append(res) elif opcode == 171: # equals value2 = stack.pop() value1 = stack.pop() result = value1 == value2 stack.append(result) elif opcode == 175: # greaterequals value2 = stack.pop() value1 = stack.pop() result = value1 >= value2 stack.append(result) elif opcode == 192: # increment_i value = stack.pop() assert isinstance(value, int) stack.append(value + 1) elif opcode == 208: # getlocal_0 stack.append(registers[0]) elif opcode == 209: # getlocal_1 stack.append(registers[1]) elif opcode == 210: # getlocal_2 stack.append(registers[2]) elif opcode == 211: # getlocal_3 stack.append(registers[3]) elif opcode == 212: # setlocal_0 registers[0] = stack.pop() elif opcode == 213: # setlocal_1 registers[1] = stack.pop() elif opcode == 214: # setlocal_2 registers[2] = stack.pop() elif opcode == 215: # setlocal_3 registers[3] = stack.pop() else: raise NotImplementedError( 'Unsupported opcode %d' % opcode) avm_class.method_pyfunctions[func_name] = resfunc return resfunc
true
2