id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
7,700
torrent.py
CouchPotato_CouchPotatoServer/libs/rtorrent/torrent.py
# Copyright (c) 2013 Chris Lucas, <chris@chrisjlucas.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import rtorrent.rpc # from rtorrent.rpc import Method import rtorrent.peer import rtorrent.tracker import rtorrent.file import rtorrent.compat from rtorrent.common import safe_repr Peer = rtorrent.peer.Peer Tracker = rtorrent.tracker.Tracker File = rtorrent.file.File Method = rtorrent.rpc.Method class Torrent: """Represents an individual torrent within a L{RTorrent} instance.""" def __init__(self, _rt_obj, info_hash, **kwargs): self._rt_obj = _rt_obj self.info_hash = info_hash # : info hash for the torrent self.rpc_id = self.info_hash # : unique id to pass to rTorrent for k in kwargs.keys(): setattr(self, k, kwargs.get(k, None)) self.peers = [] self.trackers = [] self.files = [] self._call_custom_methods() def __repr__(self): return safe_repr("Torrent(info_hash=\"{0}\" name=\"{1}\")", self.info_hash, self.name) def _call_custom_methods(self): """only calls methods that check instance variables.""" self._is_hash_checking_queued() self._is_started() self._is_paused() def get_peers(self): """Get list of Peer instances for given torrent. @return: L{Peer} instances @rtype: list @note: also assigns return value to self.peers """ self.peers = [] retriever_methods = [m for m in rtorrent.peer.methods if m.is_retriever() and m.is_available(self._rt_obj)] # need to leave 2nd arg empty (dunno why) m = rtorrent.rpc.Multicall(self) m.add("p.multicall", self.info_hash, "", *[method.rpc_call + "=" for method in retriever_methods]) results = m.call()[0] # only sent one call, only need first result for result in results: results_dict = {} # build results_dict for m, r in zip(retriever_methods, result): results_dict[m.varname] = rtorrent.rpc.process_result(m, r) self.peers.append(Peer( self._rt_obj, self.info_hash, **results_dict)) return(self.peers) def get_trackers(self): """Get list of Tracker instances for given torrent. @return: L{Tracker} instances @rtype: list @note: also assigns return value to self.trackers """ self.trackers = [] retriever_methods = [m for m in rtorrent.tracker.methods if m.is_retriever() and m.is_available(self._rt_obj)] # need to leave 2nd arg empty (dunno why) m = rtorrent.rpc.Multicall(self) m.add("t.multicall", self.info_hash, "", *[method.rpc_call + "=" for method in retriever_methods]) results = m.call()[0] # only sent one call, only need first result for result in results: results_dict = {} # build results_dict for m, r in zip(retriever_methods, result): results_dict[m.varname] = rtorrent.rpc.process_result(m, r) self.trackers.append(Tracker( self._rt_obj, self.info_hash, **results_dict)) return(self.trackers) def get_files(self): """Get list of File instances for given torrent. @return: L{File} instances @rtype: list @note: also assigns return value to self.files """ self.files = [] retriever_methods = [m for m in rtorrent.file.methods if m.is_retriever() and m.is_available(self._rt_obj)] # 2nd arg can be anything, but it'll return all files in torrent # regardless m = rtorrent.rpc.Multicall(self) m.add("f.multicall", self.info_hash, "", *[method.rpc_call + "=" for method in retriever_methods]) results = m.call()[0] # only sent one call, only need first result offset_method_index = retriever_methods.index( rtorrent.rpc.find_method("f.offset")) # make a list of the offsets of all the files, sort appropriately offset_list = sorted([r[offset_method_index] for r in results]) for result in results: results_dict = {} # build results_dict for m, r in zip(retriever_methods, result): results_dict[m.varname] = rtorrent.rpc.process_result(m, r) # get proper index positions for each file (based on the file # offset) f_index = offset_list.index(results_dict["offset"]) self.files.append(File(self._rt_obj, self.info_hash, f_index, **results_dict)) return(self.files) def set_directory(self, d): """Modify download directory @note: Needs to stop torrent in order to change the directory. Also doesn't restart after directory is set, that must be called separately. """ m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.try_stop") self.multicall_add(m, "d.directory.set", d) self.directory = m.call()[-1] def set_directory_base(self, d): """Modify base download directory @note: Needs to stop torrent in order to change the directory. Also doesn't restart after directory is set, that must be called separately. """ m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.try_stop") self.multicall_add(m, "d.directory_base.set", d) def start(self): """Start the torrent""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.try_start") self.multicall_add(m, "d.is_active") self.active = m.call()[-1] return(self.active) def stop(self): """"Stop the torrent""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.try_stop") self.multicall_add(m, "d.is_active") self.active = m.call()[-1] return(self.active) def pause(self): """Pause the torrent""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.pause") return(m.call()[-1]) def resume(self): """Resume the torrent""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.resume") return(m.call()[-1]) def close(self): """Close the torrent and it's files""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.close") return(m.call()[-1]) def erase(self): """Delete the torrent @note: doesn't delete the downloaded files""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.erase") return(m.call()[-1]) def check_hash(self): """(Re)hash check the torrent""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.check_hash") return(m.call()[-1]) def poll(self): """poll rTorrent to get latest peer/tracker/file information""" self.get_peers() self.get_trackers() self.get_files() def update(self): """Refresh torrent data @note: All fields are stored as attributes to self. @return: None """ multicall = rtorrent.rpc.Multicall(self) retriever_methods = [m for m in methods if m.is_retriever() and m.is_available(self._rt_obj)] for method in retriever_methods: multicall.add(method, self.rpc_id) multicall.call() # custom functions (only call private methods, since they only check # local variables and are therefore faster) self._call_custom_methods() def accept_seeders(self, accept_seeds): """Enable/disable whether the torrent connects to seeders @param accept_seeds: enable/disable accepting seeders @type accept_seeds: bool""" if accept_seeds: call = "d.accepting_seeders.enable" else: call = "d.accepting_seeders.disable" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, call) return(m.call()[-1]) def announce(self): """Announce torrent info to tracker(s)""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.tracker_announce") return(m.call()[-1]) @staticmethod def _assert_custom_key_valid(key): assert type(key) == int and key > 0 and key < 6, \ "key must be an integer between 1-5" def get_custom(self, key): """ Get custom value @param key: the index for the custom field (between 1-5) @type key: int @rtype: str """ self._assert_custom_key_valid(key) m = rtorrent.rpc.Multicall(self) field = "custom{0}".format(key) self.multicall_add(m, "d.{0}".format(field)) setattr(self, field, m.call()[-1]) return (getattr(self, field)) def set_custom(self, key, value): """ Set custom value @param key: the index for the custom field (between 1-5) @type key: int @param value: the value to be stored @type value: str @return: if successful, value will be returned @rtype: str """ self._assert_custom_key_valid(key) m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.custom{0}.set".format(key), value) return(m.call()[-1]) def set_visible(self, view, visible=True): p = self._rt_obj._get_conn() if visible: return p.view.set_visible(self.info_hash, view) else: return p.view.set_not_visible(self.info_hash, view) ############################################################################ # CUSTOM METHODS (Not part of the official rTorrent API) ########################################################################## def _is_hash_checking_queued(self): """Only checks instance variables, shouldn't be called directly""" # if hashing == 3, then torrent is marked for hash checking # if hash_checking == False, then torrent is waiting to be checked self.hash_checking_queued = (self.hashing == 3 and self.hash_checking is False) return(self.hash_checking_queued) def is_hash_checking_queued(self): """Check if torrent is waiting to be hash checked @note: Variable where the result for this method is stored Torrent.hash_checking_queued""" m = rtorrent.rpc.Multicall(self) self.multicall_add(m, "d.hashing") self.multicall_add(m, "d.is_hash_checking") results = m.call() setattr(self, "hashing", results[0]) setattr(self, "hash_checking", results[1]) return(self._is_hash_checking_queued()) def _is_paused(self): """Only checks instance variables, shouldn't be called directly""" self.paused = (self.state == 0) return(self.paused) def is_paused(self): """Check if torrent is paused @note: Variable where the result for this method is stored: Torrent.paused""" self.get_state() return(self._is_paused()) def _is_started(self): """Only checks instance variables, shouldn't be called directly""" self.started = (self.state == 1) return(self.started) def is_started(self): """Check if torrent is started @note: Variable where the result for this method is stored: Torrent.started""" self.get_state() return(self._is_started()) methods = [ # RETRIEVERS Method(Torrent, 'is_hash_checked', 'd.is_hash_checked', boolean=True, ), Method(Torrent, 'is_hash_checking', 'd.is_hash_checking', boolean=True, ), Method(Torrent, 'get_peers_max', 'd.peers_max'), Method(Torrent, 'get_tracker_focus', 'd.tracker_focus'), Method(Torrent, 'get_skip_total', 'd.skip.total'), Method(Torrent, 'get_state', 'd.state'), Method(Torrent, 'get_peer_exchange', 'd.peer_exchange'), Method(Torrent, 'get_down_rate', 'd.down.rate'), Method(Torrent, 'get_connection_seed', 'd.connection_seed'), Method(Torrent, 'get_uploads_max', 'd.uploads_max'), Method(Torrent, 'get_priority_str', 'd.priority_str'), Method(Torrent, 'is_open', 'd.is_open', boolean=True, ), Method(Torrent, 'get_peers_min', 'd.peers_min'), Method(Torrent, 'get_peers_complete', 'd.peers_complete'), Method(Torrent, 'get_tracker_numwant', 'd.tracker_numwant'), Method(Torrent, 'get_connection_current', 'd.connection_current'), Method(Torrent, 'is_complete', 'd.complete', boolean=True, ), Method(Torrent, 'get_peers_connected', 'd.peers_connected'), Method(Torrent, 'get_chunk_size', 'd.chunk_size'), Method(Torrent, 'get_state_counter', 'd.state_counter'), Method(Torrent, 'get_base_filename', 'd.base_filename'), Method(Torrent, 'get_state_changed', 'd.state_changed'), Method(Torrent, 'get_peers_not_connected', 'd.peers_not_connected'), Method(Torrent, 'get_directory', 'd.directory'), Method(Torrent, 'is_incomplete', 'd.incomplete', boolean=True, ), Method(Torrent, 'get_tracker_size', 'd.tracker_size'), Method(Torrent, 'is_multi_file', 'd.is_multi_file', boolean=True, ), Method(Torrent, 'get_local_id', 'd.local_id'), Method(Torrent, 'get_ratio', 'd.ratio', post_process_func=lambda x: x / 1000.0, ), Method(Torrent, 'get_loaded_file', 'd.loaded_file'), Method(Torrent, 'get_max_file_size', 'd.max_file_size'), Method(Torrent, 'get_size_chunks', 'd.size_chunks'), Method(Torrent, 'is_pex_active', 'd.is_pex_active', boolean=True, ), Method(Torrent, 'get_hashing', 'd.hashing'), Method(Torrent, 'get_bitfield', 'd.bitfield'), Method(Torrent, 'get_local_id_html', 'd.local_id_html'), Method(Torrent, 'get_connection_leech', 'd.connection_leech'), Method(Torrent, 'get_peers_accounted', 'd.peers_accounted'), Method(Torrent, 'get_message', 'd.message'), Method(Torrent, 'is_active', 'd.is_active', boolean=True, ), Method(Torrent, 'get_size_bytes', 'd.size_bytes'), Method(Torrent, 'get_ignore_commands', 'd.ignore_commands'), Method(Torrent, 'get_creation_date', 'd.creation_date'), Method(Torrent, 'get_base_path', 'd.base_path'), Method(Torrent, 'get_left_bytes', 'd.left_bytes'), Method(Torrent, 'get_size_files', 'd.size_files'), Method(Torrent, 'get_size_pex', 'd.size_pex'), Method(Torrent, 'is_private', 'd.is_private', boolean=True, ), Method(Torrent, 'get_max_size_pex', 'd.max_size_pex'), Method(Torrent, 'get_num_chunks_hashed', 'd.chunks_hashed', aliases=("get_chunks_hashed",)), Method(Torrent, 'get_num_chunks_wanted', 'd.wanted_chunks'), Method(Torrent, 'get_priority', 'd.priority'), Method(Torrent, 'get_skip_rate', 'd.skip.rate'), Method(Torrent, 'get_completed_bytes', 'd.completed_bytes'), Method(Torrent, 'get_name', 'd.name'), Method(Torrent, 'get_completed_chunks', 'd.completed_chunks'), Method(Torrent, 'get_throttle_name', 'd.throttle_name'), Method(Torrent, 'get_free_diskspace', 'd.free_diskspace'), Method(Torrent, 'get_directory_base', 'd.directory_base'), Method(Torrent, 'get_hashing_failed', 'd.hashing_failed'), Method(Torrent, 'get_tied_to_file', 'd.tied_to_file'), Method(Torrent, 'get_down_total', 'd.down.total'), Method(Torrent, 'get_bytes_done', 'd.bytes_done'), Method(Torrent, 'get_up_rate', 'd.up.rate'), Method(Torrent, 'get_up_total', 'd.up.total'), Method(Torrent, 'is_accepting_seeders', 'd.accepting_seeders', boolean=True, ), Method(Torrent, "get_chunks_seen", "d.chunks_seen", min_version=(0, 9, 1), ), Method(Torrent, "is_partially_done", "d.is_partially_done", boolean=True, ), Method(Torrent, "is_not_partially_done", "d.is_not_partially_done", boolean=True, ), Method(Torrent, "get_time_started", "d.timestamp.started"), Method(Torrent, "get_custom1", "d.custom1"), Method(Torrent, "get_custom2", "d.custom2"), Method(Torrent, "get_custom3", "d.custom3"), Method(Torrent, "get_custom4", "d.custom4"), Method(Torrent, "get_custom5", "d.custom5"), # MODIFIERS Method(Torrent, 'set_uploads_max', 'd.uploads_max.set'), Method(Torrent, 'set_tied_to_file', 'd.tied_to_file.set'), Method(Torrent, 'set_tracker_numwant', 'd.tracker_numwant.set'), Method(Torrent, 'set_priority', 'd.priority.set'), Method(Torrent, 'set_peers_max', 'd.peers_max.set'), Method(Torrent, 'set_hashing_failed', 'd.hashing_failed.set'), Method(Torrent, 'set_message', 'd.message.set'), Method(Torrent, 'set_throttle_name', 'd.throttle_name.set'), Method(Torrent, 'set_peers_min', 'd.peers_min.set'), Method(Torrent, 'set_ignore_commands', 'd.ignore_commands.set'), Method(Torrent, 'set_max_file_size', 'd.max_file_size.set'), Method(Torrent, 'set_custom5', 'd.custom5.set'), Method(Torrent, 'set_custom4', 'd.custom4.set'), Method(Torrent, 'set_custom2', 'd.custom2.set'), Method(Torrent, 'set_custom1', 'd.custom1.set'), Method(Torrent, 'set_custom3', 'd.custom3.set'), Method(Torrent, 'set_connection_current', 'd.connection_current.set'), ]
18,788
Python
.py
418
36.626794
98
0.616058
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,701
compat.py
CouchPotato_CouchPotatoServer/libs/rtorrent/compat.py
# Copyright (c) 2013 Chris Lucas, <chris@chrisjlucas.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys def is_py3(): return sys.version_info[0] == 3 if is_py3(): import xmlrpc.client as xmlrpclib else: import xmlrpclib
1,258
Python
.py
26
46.769231
72
0.784202
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,702
connection.py
CouchPotato_CouchPotatoServer/libs/rtorrent/connection.py
import logging import urllib from rtorrent.common import convert_version_tuple_to_str, join_uri, update_uri from rtorrent.lib.xmlrpc.clients.http import HTTPServerProxy from rtorrent.lib.xmlrpc.clients.scgi import SCGIServerProxy from rtorrent.lib.xmlrpc.transports.basic_auth import BasicAuthTransport # Try import requests transport (optional) try: from rtorrent.lib.xmlrpc.transports.requests_ import RequestsTransport except ImportError: RequestsTransport = None MIN_RTORRENT_VERSION = (0, 8, 1) MIN_RTORRENT_VERSION_STR = convert_version_tuple_to_str(MIN_RTORRENT_VERSION) log = logging.getLogger(__name__) class Connection(object): def __init__(self, uri, auth=None, verify_ssl=True, sp=None, sp_kwargs=None): self.auth = auth self.verify_ssl = verify_ssl # Transform + Parse URI self.uri = self._transform_uri(uri) self.scheme = urllib.splittype(self.uri)[0] # Construct RPC Client self.sp = self._get_sp(self.scheme, sp) self.sp_kwargs = sp_kwargs or {} self._client = None self._client_version_tuple = () self._rpc_methods = [] @property def client(self): if self._client is None: # Construct new client self._client = self.connect() # Return client return self._client def connect(self): log.debug('Connecting to server: %r', self.uri) if self.auth: # Construct server proxy with authentication transport return self.sp(self.uri, transport=self._construct_transport(), **self.sp_kwargs) # Construct plain server proxy return self.sp(self.uri, **self.sp_kwargs) def test(self): try: self.verify() except: return False return True def verify(self): # check for rpc methods that should be available assert "system.client_version" in self._get_rpc_methods(), "Required RPC method not available." assert "system.library_version" in self._get_rpc_methods(), "Required RPC method not available." # minimum rTorrent version check assert self._meets_version_requirement() is True,\ "Error: Minimum rTorrent version required is {0}".format(MIN_RTORRENT_VERSION_STR) # # Private methods # def _construct_transport(self): # Ensure "auth" parameter is valid if type(self.auth) is not tuple or len(self.auth) != 3: raise ValueError('Invalid "auth" parameter format') # Construct transport with authentication details method, _, _ = self.auth secure = self.scheme == 'https' log.debug('Constructing transport for scheme: %r, authentication method: %r', self.scheme, method) # Use requests transport (if available) if RequestsTransport and method in ['basic', 'digest']: return RequestsTransport( secure, self.auth, verify_ssl=self.verify_ssl ) # Use basic authentication transport if method == 'basic': return BasicAuthTransport(secure, self.auth) # Unsupported authentication method if method == 'digest': raise Exception('Digest authentication requires the "requests" library') raise NotImplementedError('Unknown authentication method: %r' % method) def _get_client_version_tuple(self): if not self._client_version_tuple: if not hasattr(self, "client_version"): setattr(self, "client_version", self.client.system.client_version()) rtver = getattr(self, "client_version") self._client_version_tuple = tuple([int(i) for i in rtver.split(".")]) return self._client_version_tuple def _get_rpc_methods(self): """ Get list of raw RPC commands @return: raw RPC commands @rtype: list """ return(self._rpc_methods or self._update_rpc_methods()) @staticmethod def _get_sp(scheme, sp): if sp: return sp if scheme in ['http', 'https']: return HTTPServerProxy if scheme == 'scgi': return SCGIServerProxy raise NotImplementedError() def _meets_version_requirement(self): return self._get_client_version_tuple() >= MIN_RTORRENT_VERSION @staticmethod def _transform_uri(uri): scheme = urllib.splittype(uri)[0] if scheme == 'httprpc' or scheme.startswith('httprpc+'): # Try find HTTPRPC transport (token after '+' in 'httprpc+https'), otherwise assume HTTP transport = scheme[scheme.index('+') + 1:] if '+' in scheme else 'http' # Transform URI with new path and scheme uri = join_uri(uri, 'plugins/httprpc/action.php', construct=False) return update_uri(uri, scheme=transport) return uri def _update_rpc_methods(self): self._rpc_methods = self.client.system.listMethods() return self._rpc_methods
5,073
Python
.py
115
35.330435
106
0.645575
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,703
common.py
CouchPotato_CouchPotatoServer/libs/rtorrent/common.py
# Copyright (c) 2013 Chris Lucas, <chris@chrisjlucas.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import urlparse import os from rtorrent.compat import is_py3 def bool_to_int(value): """Translates python booleans to RPC-safe integers""" if value is True: return("1") elif value is False: return("0") else: return(value) def cmd_exists(cmds_list, cmd): """Check if given command is in list of available commands @param cmds_list: see L{RTorrent._rpc_methods} @type cmds_list: list @param cmd: name of command to be checked @type cmd: str @return: bool """ return(cmd in cmds_list) def find_torrent(info_hash, torrent_list): """Find torrent file in given list of Torrent classes @param info_hash: info hash of torrent @type info_hash: str @param torrent_list: list of L{Torrent} instances (see L{RTorrent.get_torrents}) @type torrent_list: list @return: L{Torrent} instance, or -1 if not found """ for t in torrent_list: if t.info_hash == info_hash: return t return None def is_valid_port(port): """Check if given port is valid""" return(0 <= int(port) <= 65535) def convert_version_tuple_to_str(t): return(".".join([str(n) for n in t])) def safe_repr(fmt, *args, **kwargs): """ Formatter that handles unicode arguments """ if not is_py3(): # unicode fmt can take str args, str fmt cannot take unicode args fmt = fmt.decode("utf-8") out = fmt.format(*args, **kwargs) return out.encode("utf-8") else: return fmt.format(*args, **kwargs) def split_path(path): fragments = path.split('/') if len(fragments) == 1: return fragments if not fragments[-1]: return fragments[:-1] return fragments def join_path(base, path): # Return if we have a new absolute path if os.path.isabs(path): return path # non-absolute base encountered if base and not os.path.isabs(base): raise NotImplementedError() return '/'.join(split_path(base) + split_path(path)) def join_uri(base, uri, construct=True): p_uri = urlparse.urlparse(uri) # Return if there is nothing to join if not p_uri.path: return base scheme, netloc, path, params, query, fragment = urlparse.urlparse(base) # Switch to 'uri' parts _, _, _, params, query, fragment = p_uri path = join_path(path, p_uri.path) result = urlparse.ParseResult(scheme, netloc, path, params, query, fragment) if not construct: return result # Construct from parts return urlparse.urlunparse(result) def update_uri(uri, construct=True, **kwargs): if isinstance(uri, urlparse.ParseResult): uri = dict(uri._asdict()) if type(uri) is not dict: raise ValueError("Unknown URI type") uri.update(kwargs) result = urlparse.ParseResult(**uri) if not construct: return result return urlparse.urlunparse(result)
4,050
Python
.py
104
33.951923
84
0.696845
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,704
group.py
CouchPotato_CouchPotatoServer/libs/rtorrent/group.py
# Copyright (c) 2013 Dean Gardiner, <gardiner91@gmail.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import rtorrent.rpc Method = rtorrent.rpc.Method class Group: __name__ = 'Group' def __init__(self, _rt_obj, name): self._rt_obj = _rt_obj self.name = name self.methods = [ # RETRIEVERS Method(Group, 'get_max', 'group.' + self.name + '.ratio.max', varname='max'), Method(Group, 'get_min', 'group.' + self.name + '.ratio.min', varname='min'), Method(Group, 'get_upload', 'group.' + self.name + '.ratio.upload', varname='upload'), # MODIFIERS Method(Group, 'set_max', 'group.' + self.name + '.ratio.max.set', varname='max'), Method(Group, 'set_min', 'group.' + self.name + '.ratio.min.set', varname='min'), Method(Group, 'set_upload', 'group.' + self.name + '.ratio.upload.set', varname='upload') ] rtorrent.rpc._build_rpc_methods(self, self.methods) # Setup multicall_add method caller = lambda multicall, method, *args: \ multicall.add(method, *args) setattr(self, "multicall_add", caller) def _get_prefix(self): return 'group.' + self.name + '.ratio.' def update(self): multicall = rtorrent.rpc.Multicall(self) retriever_methods = [m for m in self.methods if m.is_retriever() and m.is_available(self._rt_obj)] for method in retriever_methods: multicall.add(method) multicall.call() def enable(self): p = self._rt_obj._get_conn() return getattr(p, self._get_prefix() + 'enable')() def disable(self): p = self._rt_obj._get_conn() return getattr(p, self._get_prefix() + 'disable')() def set_command(self, *methods): methods = [m + '=' for m in methods] m = rtorrent.rpc.Multicall(self) self.multicall_add( m, 'system.method.set', self._get_prefix() + 'command', *methods ) return(m.call()[-1])
3,116
Python
.py
65
40.661538
101
0.64347
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,705
torrentparser.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/torrentparser.py
# Copyright (c) 2013 Chris Lucas, <chris@chrisjlucas.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from rtorrent.compat import is_py3 import os.path import re import rtorrent.lib.bencode as bencode import hashlib if is_py3(): from urllib.request import urlopen # @UnresolvedImport @UnusedImport else: from urllib2 import urlopen # @UnresolvedImport @Reimport class TorrentParser(): def __init__(self, torrent): """Decode and parse given torrent @param torrent: handles: urls, file paths, string of torrent data @type torrent: str @raise AssertionError: Can be raised for a couple reasons: - If _get_raw_torrent() couldn't figure out what X{torrent} is - if X{torrent} isn't a valid bencoded torrent file """ self.torrent = torrent self._raw_torrent = None # : testing yo self._torrent_decoded = None # : what up self.file_type = None self._get_raw_torrent() assert self._raw_torrent is not None, "Couldn't get raw_torrent." if self._torrent_decoded is None: self._decode_torrent() assert isinstance(self._torrent_decoded, dict), "Invalid torrent file." self._parse_torrent() def _is_raw(self): raw = False if isinstance(self.torrent, (str, bytes)): if isinstance(self._decode_torrent(self.torrent), dict): raw = True else: # reset self._torrent_decoded (currently equals False) self._torrent_decoded = None return(raw) def _get_raw_torrent(self): """Get raw torrent data by determining what self.torrent is""" # already raw? if self._is_raw(): self.file_type = "raw" self._raw_torrent = self.torrent return # local file? if os.path.isfile(self.torrent): self.file_type = "file" self._raw_torrent = open(self.torrent, "rb").read() # url? elif re.search("^(http|ftp):\/\/", self.torrent, re.I): self.file_type = "url" self._raw_torrent = urlopen(self.torrent).read() def _decode_torrent(self, raw_torrent=None): if raw_torrent is None: raw_torrent = self._raw_torrent self._torrent_decoded = bencode.decode(raw_torrent) return(self._torrent_decoded) def _calc_info_hash(self): self.info_hash = None if "info" in self._torrent_decoded.keys(): info_encoded = bencode.encode(self._torrent_decoded["info"]) if info_encoded: self.info_hash = hashlib.sha1(info_encoded).hexdigest().upper() return(self.info_hash) def _parse_torrent(self): for k in self._torrent_decoded: key = k.replace(" ", "_").lower() setattr(self, key, self._torrent_decoded[k]) self._calc_info_hash() class NewTorrentParser(object): @staticmethod def _read_file(fp): return fp.read() @staticmethod def _write_file(fp): fp.write() return fp @staticmethod def _decode_torrent(data): return bencode.decode(data) def __init__(self, input): self.input = input self._raw_torrent = None self._decoded_torrent = None self._hash_outdated = False if isinstance(self.input, (str, bytes)): # path to file? if os.path.isfile(self.input): self._raw_torrent = self._read_file(open(self.input, "rb")) else: # assume input was the raw torrent data (do we really want # this?) self._raw_torrent = self.input # file-like object? elif self.input.hasattr("read"): self._raw_torrent = self._read_file(self.input) assert self._raw_torrent is not None, "Invalid input: input must be a path or a file-like object" self._decoded_torrent = self._decode_torrent(self._raw_torrent) assert isinstance( self._decoded_torrent, dict), "File could not be decoded" def _calc_info_hash(self): self.info_hash = None info_dict = self._torrent_decoded["info"] self.info_hash = hashlib.sha1(bencode.encode( info_dict)).hexdigest().upper() return(self.info_hash) def set_tracker(self, tracker): self._decoded_torrent["announce"] = tracker def get_tracker(self): return self._decoded_torrent.get("announce")
5,641
Python
.py
130
34.769231
105
0.632914
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,706
bencode.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/bencode.py
# Copyright (C) 2011 by clueless <clueless.nospam ! mail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # Version: 20111107 # # Changelog # --------- # 2011-11-07 - Added support for Python2 (tested on 2.6) # 2011-10-03 - Fixed: moved check for end of list at the top of the while loop # in _decode_list (in case the list is empty) (Chris Lucas) # - Converted dictionary keys to str # 2011-04-24 - Changed date format to YYYY-MM-DD for versioning, bigger # integer denotes a newer version # - Fixed a bug that would treat False as an integral type but # encode it using the 'False' string, attempting to encode a # boolean now results in an error # - Fixed a bug where an integer value of 0 in a list or # dictionary resulted in a parse error while decoding # # 2011-04-03 - Original release import sys _py3 = sys.version_info[0] == 3 if _py3: _VALID_STRING_TYPES = (str,) else: _VALID_STRING_TYPES = (str, unicode) # @UndefinedVariable _TYPE_INT = 1 _TYPE_STRING = 2 _TYPE_LIST = 3 _TYPE_DICTIONARY = 4 _TYPE_END = 5 _TYPE_INVALID = 6 # Function to determine the type of he next value/item # Arguments: # char First character of the string that is to be decoded # Return value: # Returns an integer that describes what type the next value/item is def _gettype(char): if not isinstance(char, int): char = ord(char) if char == 0x6C: # 'l' return _TYPE_LIST elif char == 0x64: # 'd' return _TYPE_DICTIONARY elif char == 0x69: # 'i' return _TYPE_INT elif char == 0x65: # 'e' return _TYPE_END elif char >= 0x30 and char <= 0x39: # '0' '9' return _TYPE_STRING else: return _TYPE_INVALID # Function to parse a string from the bendcoded data # Arguments: # data bencoded data, must be guaranteed to be a string # Return Value: # Returns a tuple, the first member of the tuple is the parsed string # The second member is whatever remains of the bencoded data so it can # be used to parse the next part of the data def _decode_string(data): end = 1 # if py3, data[end] is going to be an int # if py2, data[end] will be a string if _py3: char = 0x3A else: char = chr(0x3A) while data[end] != char: # ':' end = end + 1 strlen = int(data[:end]) return (data[end + 1:strlen + end + 1], data[strlen + end + 1:]) # Function to parse an integer from the bencoded data # Arguments: # data bencoded data, must be guaranteed to be an integer # Return Value: # Returns a tuple, the first member of the tuple is the parsed string # The second member is whatever remains of the bencoded data so it can # be used to parse the next part of the data def _decode_int(data): end = 1 # if py3, data[end] is going to be an int # if py2, data[end] will be a string if _py3: char = 0x65 else: char = chr(0x65) while data[end] != char: # 'e' end = end + 1 return (int(data[1:end]), data[end + 1:]) # Function to parse a bencoded list # Arguments: # data bencoded data, must be guaranted to be the start of a list # Return Value: # Returns a tuple, the first member of the tuple is the parsed list # The second member is whatever remains of the bencoded data so it can # be used to parse the next part of the data def _decode_list(data): x = [] overflow = data[1:] while True: # Loop over the data if _gettype(overflow[0]) == _TYPE_END: # - Break if we reach the end of the list return (x, overflow[1:]) # and return the list and overflow value, overflow = _decode(overflow) # if isinstance(value, bool) or overflow == '': # - if we have a parse error return (False, False) # Die with error else: # - Otherwise x.append(value) # add the value to the list # Function to parse a bencoded list # Arguments: # data bencoded data, must be guaranted to be the start of a list # Return Value: # Returns a tuple, the first member of the tuple is the parsed dictionary # The second member is whatever remains of the bencoded data so it can # be used to parse the next part of the data def _decode_dict(data): x = {} overflow = data[1:] while True: # Loop over the data if _gettype(overflow[0]) != _TYPE_STRING: # - If the key is not a string return (False, False) # Die with error key, overflow = _decode(overflow) # if key == False or overflow == '': # - If parse error return (False, False) # Die with error value, overflow = _decode(overflow) # if isinstance(value, bool) or overflow == '': # - If parse error print("Error parsing value") print(value) print(overflow) return (False, False) # Die with error else: # don't use bytes for the key key = key.decode() x[key] = value if _gettype(overflow[0]) == _TYPE_END: return (x, overflow[1:]) # Arguments: # data bencoded data in bytes format # Return Values: # Returns a tuple, the first member is the parsed data, could be a string, # an integer, a list or a dictionary, or a combination of those # The second member is the leftover of parsing, if everything parses correctly this # should be an empty byte string def _decode(data): btype = _gettype(data[0]) if btype == _TYPE_INT: return _decode_int(data) elif btype == _TYPE_STRING: return _decode_string(data) elif btype == _TYPE_LIST: return _decode_list(data) elif btype == _TYPE_DICTIONARY: return _decode_dict(data) else: return (False, False) # Function to decode bencoded data # Arguments: # data bencoded data, can be str or bytes # Return Values: # Returns the decoded data on success, this coud be bytes, int, dict or list # or a combinatin of those # If an error occurs the return value is False def decode(data): # if isinstance(data, str): # data = data.encode() decoded, overflow = _decode(data) return decoded # Args: data as integer # return: encoded byte string def _encode_int(data): return b'i' + str(data).encode() + b'e' # Args: data as string or bytes # Return: encoded byte string def _encode_string(data): return str(len(data)).encode() + b':' + data # Args: data as list # Return: Encoded byte string, false on error def _encode_list(data): elist = b'l' for item in data: eitem = encode(item) if eitem == False: return False elist += eitem return elist + b'e' # Args: data as dict # Return: encoded byte string, false on error def _encode_dict(data): edict = b'd' keys = [] for key in data: if not isinstance(key, _VALID_STRING_TYPES) and not isinstance(key, bytes): return False keys.append(key) keys.sort() for key in keys: ekey = encode(key) eitem = encode(data[key]) if ekey == False or eitem == False: return False edict += ekey + eitem return edict + b'e' # Function to encode a variable in bencoding # Arguments: # data Variable to be encoded, can be a list, dict, str, bytes, int or a combination of those # Return Values: # Returns the encoded data as a byte string when successful # If an error occurs the return value is False def encode(data): if isinstance(data, bool): return False elif isinstance(data, (int, long)): return _encode_int(data) elif isinstance(data, bytes): return _encode_string(data) elif isinstance(data, _VALID_STRING_TYPES): return _encode_string(data.encode()) elif isinstance(data, list): return _encode_list(data) elif isinstance(data, dict): return _encode_dict(data) else: return False
9,140
Python
.py
239
33.786611
97
0.65583
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,707
scgi.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/xmlrpc/clients/scgi.py
#!/usr/bin/python # rtorrent_xmlrpc # (c) 2011 Roger Que <alerante@bellsouth.net> # # Modified portions: # (c) 2013 Dean Gardiner <gardiner91@gmail.com> # # Python module for interacting with rtorrent's XML-RPC interface # directly over SCGI, instead of through an HTTP server intermediary. # Inspired by Glenn Washburn's xmlrpc2scgi.py [1], but subclasses the # built-in xmlrpclib classes so that it is compatible with features # such as MultiCall objects. # # [1] <http://libtorrent.rakshasa.no/wiki/UtilsXmlrpc2scgi> # # Usage: server = SCGIServerProxy('scgi://localhost:7000/') # server = SCGIServerProxy('scgi:///path/to/scgi.sock') # print server.system.listMethods() # mc = xmlrpclib.MultiCall(server) # mc.get_up_rate() # mc.get_down_rate() # print mc() # # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # # You must obey the GNU General Public License in all respects for # all of the code used other than OpenSSL. If you modify file(s) # with this exception, you may extend this exception to your version # of the file(s), but you are not obligated to do so. If you do not # wish to do so, delete this exception statement from your version. # If you delete this exception statement from all source files in the # program, then also delete it here. # # # # Portions based on Python's xmlrpclib: # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. import urllib import xmlrpclib from rtorrent.lib.xmlrpc.transports.scgi import SCGITransport class SCGIServerProxy(xmlrpclib.ServerProxy): def __init__(self, uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False): type, uri = urllib.splittype(uri) if type not in ('scgi'): raise IOError('unsupported XML-RPC protocol') self.__host, self.__handler = urllib.splithost(uri) if not self.__handler: self.__handler = '/' if transport is None: transport = SCGITransport(use_datetime=use_datetime) self.__transport = transport self.__encoding = encoding self.__verbose = verbose self.__allow_none = allow_none def __close(self): self.__transport.close() def __request(self, methodname, params): # call a method on the remote server request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none) response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) == 1: response = response[0] return response def __repr__(self): return ( "<SCGIServerProxy for %s%s>" % (self.__host, self.__handler) ) __str__ = __repr__ def __getattr__(self, name): # magic method dispatcher return xmlrpclib._Method(self.__request, name) # note: to call a remote object with an non-standard name, use # result getattr(server, "strange-python-name")(args) def __call__(self, attr): """A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__ """ if attr == "close": return self.__close elif attr == "transport": return self.__transport raise AttributeError("Attribute %r not found" % (attr,))
5,670
Python
.py
134
37.865672
79
0.707503
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,708
http.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/xmlrpc/clients/http.py
# Copyright (c) 2013 Chris Lucas, <chris@chrisjlucas.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from rtorrent.compat import xmlrpclib HTTPServerProxy = xmlrpclib.ServerProxy
1,195
Python
.py
21
55.809524
72
0.799488
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,709
scgi.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/xmlrpc/transports/scgi.py
#!/usr/bin/python # rtorrent_xmlrpc # (c) 2011 Roger Que <alerante@bellsouth.net> # # Modified portions: # (c) 2013 Dean Gardiner <gardiner91@gmail.com> # # Python module for interacting with rtorrent's XML-RPC interface # directly over SCGI, instead of through an HTTP server intermediary. # Inspired by Glenn Washburn's xmlrpc2scgi.py [1], but subclasses the # built-in xmlrpclib classes so that it is compatible with features # such as MultiCall objects. # # [1] <http://libtorrent.rakshasa.no/wiki/UtilsXmlrpc2scgi> # # Usage: server = SCGIServerProxy('scgi://localhost:7000/') # server = SCGIServerProxy('scgi:///path/to/scgi.sock') # print server.system.listMethods() # mc = xmlrpclib.MultiCall(server) # mc.get_up_rate() # mc.get_down_rate() # print mc() # # # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # # You must obey the GNU General Public License in all respects for # all of the code used other than OpenSSL. If you modify file(s) # with this exception, you may extend this exception to your version # of the file(s), but you are not obligated to do so. If you do not # wish to do so, delete this exception statement from your version. # If you delete this exception statement from all source files in the # program, then also delete it here. # # # # Portions based on Python's xmlrpclib: # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. import errno import httplib import re import socket import urllib import xmlrpclib class SCGITransport(xmlrpclib.Transport): # Added request() from Python 2.7 xmlrpclib here to backport to Python 2.6 def request(self, host, handler, request_body, verbose=0): #retry request once if cached connection has gone cold for i in (0, 1): try: return self.single_request(host, handler, request_body, verbose) except socket.error, e: if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE): raise except httplib.BadStatusLine: #close after we sent request if i: raise def single_request(self, host, handler, request_body, verbose=0): # Add SCGI headers to the request. headers = {'CONTENT_LENGTH': str(len(request_body)), 'SCGI': '1'} header = '\x00'.join(('%s\x00%s' % item for item in headers.iteritems())) + '\x00' header = '%d:%s' % (len(header), header) request_body = '%s,%s' % (header, request_body) sock = None try: if host: host, port = urllib.splitport(host) addrinfo = socket.getaddrinfo(host, int(port), socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(*addrinfo[0][:3]) sock.connect(addrinfo[0][4]) else: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(handler) self.verbose = verbose sock.send(request_body) return self.parse_response(sock.makefile()) finally: if sock: sock.close() def parse_response(self, response): p, u = self.getparser() response_body = '' while True: data = response.read(1024) if not data: break response_body += data # Remove SCGI headers from the response. response_header, response_body = re.split(r'\n\s*?\n', response_body, maxsplit=1) if self.verbose: print 'body:', repr(response_body) p.feed(response_body) p.close() return u.close()
5,943
Python
.py
139
37.064748
91
0.686247
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,710
basic_auth.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/xmlrpc/transports/basic_auth.py
# # Copyright (c) 2013 Dean Gardiner, <gardiner91@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from base64 import b64encode import httplib import xmlrpclib class BasicAuthTransport(xmlrpclib.Transport): def __init__(self, secure=False, username=None, password=None): xmlrpclib.Transport.__init__(self) self.secure = secure self.username = username self.password = password def send_auth(self, h): if not self.username or not self.password: return auth = b64encode("%s:%s" % (self.username, self.password)) h.putheader('Authorization', "Basic %s" % auth) def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] chost, self._extra_headers, x509 = self.get_host_info(host) if self.secure: try: self._connection = host, httplib.HTTPSConnection(chost, None, **(x509 or {})) except AttributeError: raise NotImplementedError( "your version of httplib doesn't support HTTPS" ) else: self._connection = host, httplib.HTTPConnection(chost) return self._connection[1] def single_request(self, host, handler, request_body, verbose=0): # issue XML-RPC request h = self.make_connection(host) if verbose: h.set_debuglevel(1) try: self.send_request(h, handler, request_body) self.send_host(h, host) self.send_user_agent(h) self.send_auth(h) self.send_content(h, request_body) response = h.getresponse(buffering=True) if response.status == 200: self.verbose = verbose return self.parse_response(response) except xmlrpclib.Fault: raise except Exception: self.close() raise #discard any response data and raise exception if response.getheader("content-length", 0): response.read() raise xmlrpclib.ProtocolError( host + handler, response.status, response.reason, response.msg, )
3,291
Python
.py
77
34.597403
93
0.660826
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,711
requests_.py
CouchPotato_CouchPotatoServer/libs/rtorrent/lib/xmlrpc/transports/requests_.py
import requests import requests.auth import xmlrpclib class RequestsTransport(xmlrpclib.Transport): def __init__(self, secure, auth=None, proxies=None, verify_ssl=True): xmlrpclib.Transport.__init__(self) self.secure = secure # Construct session self.session = requests.Session() self.session.auth = self.parse_auth(auth) self.session.proxies = proxies or {} self.session.verify = verify_ssl @property def scheme(self): if self.secure: return 'https' return 'http' def build_url(self, host, handler): return '%s://%s' % (self.scheme, host + handler) def request(self, host, handler, request_body, verbose=0): # Retry request once if cached connection has gone cold for i in (0, 1): try: return self.single_request(host, handler, request_body, verbose) except requests.ConnectionError: if i: raise except requests.Timeout: if i: raise def single_request(self, host, handler, request_body, verbose=0): url = self.build_url(host, handler) # Send request response = self.session.post( url, data=request_body, headers={ 'Content-Type': 'text/xml' }, stream=True ) if response.status_code == 200: return self.parse_response(response) # Invalid response returned raise xmlrpclib.ProtocolError( host + handler, response.status_code, response.reason, response.headers ) def parse_auth(self, auth): # Parse "auth" parameter if type(auth) is not tuple or len(auth) != 3: return None method, username, password = auth # Basic Authentication if method == 'basic': return requests.auth.HTTPBasicAuth(username, password) # Digest Authentication if method == 'digest': return requests.auth.HTTPDigestAuth(username, password) raise NotImplementedError('Unsupported authentication method: %r' % method) def parse_response(self, response): p, u = self.getparser() # Write chunks to parser for chunk in response.iter_content(1024): p.feed(chunk) # Close parser p.close() # Close unmarshaller return u.close()
2,530
Python
.py
70
25.985714
83
0.588356
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,712
__init__.py
CouchPotato_CouchPotatoServer/libs/rtorrent/rpc/__init__.py
# Copyright (c) 2013 Chris Lucas, <chris@chrisjlucas.com> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import inspect import rtorrent import re from rtorrent.common import bool_to_int, convert_version_tuple_to_str,\ safe_repr from rtorrent.err import MethodError from rtorrent.compat import xmlrpclib def get_varname(rpc_call): """Transform rpc method into variable name. @newfield example: Example @example: if the name of the rpc method is 'p.get_down_rate', the variable name will be 'down_rate' """ # extract variable name from xmlrpc func name r = re.search( "([ptdf]\.|system\.|get\_|is\_|set\_)+([^=]*)", rpc_call, re.I) if r: return(r.groups()[-1].replace(".","_")) else: return(None) def _handle_unavailable_rpc_method(method, rt_obj): msg = "Method " + str(method) + " isn't available." if rt_obj.connection._get_client_version_tuple() < method.min_version: msg = "This method is only available in " \ "RTorrent version v{0} or later".format( convert_version_tuple_to_str(method.min_version)) raise MethodError(msg) class DummyClass: def __init__(self): pass class Method: """Represents an individual RPC method""" def __init__(self, _class, method_name, rpc_call, docstring=None, varname=None, **kwargs): self._class = _class # : Class this method is associated with self.class_name = _class.__name__ self.method_name = method_name # : name of public-facing method self.rpc_call = rpc_call # : name of rpc method self.docstring = docstring # : docstring for rpc method (optional) self.varname = varname # : variable for the result of the method call, usually set to self.varname self.min_version = kwargs.get("min_version", ( 0, 0, 0)) # : Minimum version of rTorrent required self.boolean = kwargs.get("boolean", False) # : returns boolean value? self.post_process_func = kwargs.get( "post_process_func", None) # : custom post process function self.aliases = kwargs.get( "aliases", []) # : aliases for method (optional) self.required_args = [] #: Arguments required when calling the method (not utilized) self.method_type = self._get_method_type() if self.varname is None: self.varname = get_varname(self.rpc_call) assert self.varname is not None, "Couldn't get variable name." def __repr__(self): return safe_repr("Method(method_name='{0}', rpc_call='{1}')", self.method_name, self.rpc_call) def _get_method_type(self): """Determine whether method is a modifier or a retriever""" if self.method_name[:4] == "set_" or self.method_name[-4:] == ".set": return('m') # modifier else: return('r') # retriever def is_modifier(self): if self.method_type == 'm': return(True) else: return(False) def is_retriever(self): if self.method_type == 'r': return(True) else: return(False) def is_available(self, rt_obj): if rt_obj.connection._get_client_version_tuple() < self.min_version or \ self.rpc_call not in rt_obj.connection._get_rpc_methods(): return(False) else: return(True) class Multicall: def __init__(self, class_obj, **kwargs): self.class_obj = class_obj if class_obj.__class__.__name__ == "RTorrent": self.rt_obj = class_obj else: self.rt_obj = class_obj._rt_obj self.calls = [] def add(self, method, *args): """Add call to multicall @param method: L{Method} instance or name of raw RPC method @type method: Method or str @param args: call arguments """ # if a raw rpc method was given instead of a Method instance, # try and find the instance for it. And if all else fails, create a # dummy Method instance if isinstance(method, str): result = find_method(method) # if result not found if result == -1: method = Method(DummyClass, method, method) else: method = result # ensure method is available before adding if not method.is_available(self.rt_obj): _handle_unavailable_rpc_method(method, self.rt_obj) self.calls.append((method, args)) def list_calls(self): for c in self.calls: print(c) def call(self): """Execute added multicall calls @return: the results (post-processed), in the order they were added @rtype: tuple """ m = xmlrpclib.MultiCall(self.rt_obj._get_conn()) for call in self.calls: method, args = call rpc_call = getattr(method, "rpc_call") getattr(m, rpc_call)(*args) results = m() results = tuple(results) results_processed = [] for r, c in zip(results, self.calls): method = c[0] # Method instance result = process_result(method, r) results_processed.append(result) # assign result to class_obj exists = hasattr(self.class_obj, method.varname) if not exists or not inspect.ismethod(getattr(self.class_obj, method.varname)): setattr(self.class_obj, method.varname, result) return(tuple(results_processed)) def call_method(class_obj, method, *args): """Handles single RPC calls @param class_obj: Peer/File/Torrent/Tracker/RTorrent instance @type class_obj: object @param method: L{Method} instance or name of raw RPC method @type method: Method or str """ if method.is_retriever(): args = args[:-1] else: assert args[-1] is not None, "No argument given." if class_obj.__class__.__name__ == "RTorrent": rt_obj = class_obj else: rt_obj = class_obj._rt_obj # check if rpc method is even available if not method.is_available(rt_obj): _handle_unavailable_rpc_method(method, rt_obj) m = Multicall(class_obj) m.add(method, *args) # only added one method, only getting one result back ret_value = m.call()[0] ####### OBSOLETE ########################################################## # if method.is_retriever(): # #value = process_result(method, ret_value) # value = ret_value #MultiCall already processed the result # else: # # we're setting the user's input to method.varname # # but we'll return the value that xmlrpc gives us # value = process_result(method, args[-1]) ########################################################################## return(ret_value) def find_method(rpc_call): """Return L{Method} instance associated with given RPC call""" method_lists = [ rtorrent.methods, rtorrent.file.methods, rtorrent.tracker.methods, rtorrent.peer.methods, rtorrent.torrent.methods, ] for l in method_lists: for m in l: if m.rpc_call.lower() == rpc_call.lower(): return(m) return(-1) def process_result(method, result): """Process given C{B{result}} based on flags set in C{B{method}} @param method: L{Method} instance @type method: Method @param result: result to be processed (the result of given L{Method} instance) @note: Supported Processing: - boolean - convert ones and zeros returned by rTorrent and convert to python boolean values """ # handle custom post processing function if method.post_process_func is not None: result = method.post_process_func(result) # is boolean? if method.boolean: if result in [1, '1']: result = True elif result in [0, '0']: result = False return(result) def _build_rpc_methods(class_, method_list): """Build glorified aliases to raw RPC methods""" instance = None if not inspect.isclass(class_): instance = class_ class_ = instance.__class__ for m in method_list: class_name = m.class_name if class_name != class_.__name__: continue if class_name == "RTorrent": caller = lambda self, arg = None, method = m:\ call_method(self, method, bool_to_int(arg)) elif class_name == "Torrent": caller = lambda self, arg = None, method = m:\ call_method(self, method, self.rpc_id, bool_to_int(arg)) elif class_name in ["Tracker", "File"]: caller = lambda self, arg = None, method = m:\ call_method(self, method, self.rpc_id, bool_to_int(arg)) elif class_name == "Peer": caller = lambda self, arg = None, method = m:\ call_method(self, method, self.rpc_id, bool_to_int(arg)) elif class_name == "Group": caller = lambda arg = None, method = m: \ call_method(instance, method, bool_to_int(arg)) if m.docstring is None: m.docstring = "" # print(m) docstring = """{0} @note: Variable where the result for this method is stored: {1}.{2}""".format( m.docstring, class_name, m.varname) caller.__doc__ = docstring for method_name in [m.method_name] + list(m.aliases): if instance is None: setattr(class_, method_name, caller) else: setattr(instance, method_name, caller)
10,880
Python
.py
256
34
107
0.606098
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,713
relativedelta.py
CouchPotato_CouchPotatoServer/libs/dateutil/relativedelta.py
""" Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ __license__ = "Simplified BSD" import datetime import calendar from six import integer_types __all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)]) class relativedelta(object): """ The relativedelta type is based on the specification of the excelent work done by M.-A. Lemburg in his mx.DateTime extension. However, notice that this type does *NOT* implement the same algorithm as his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. There's two different ways to build a relativedelta instance. The first one is passing it two date/datetime classes: relativedelta(datetime1, datetime2) And the other way is to use the following keyword arguments: year, month, day, hour, minute, second, microsecond: Absolute information. years, months, weeks, days, hours, minutes, seconds, microseconds: Relative information, may be negative. weekday: One of the weekday instances (MO, TU, etc). These instances may receive a parameter N, specifying the Nth weekday, which could be positive or negative (like MO(+1) or MO(-2). Not specifying it is the same as specifying +1. You can also use an integer, where 0=MO. leapdays: Will add given days to the date found, if year is a leap year, and the date found is post 28 of february. yearday, nlyearday: Set the yearday or the non-leap year day (jump leap days). These are converted to day/month/leapdays information. Here is the behavior of operations with relativedelta: 1) Calculate the absolute year, using the 'year' argument, or the original datetime year, if the argument is not present. 2) Add the relative 'years' argument to the absolute year. 3) Do steps 1 and 2 for month/months. 4) Calculate the absolute day, using the 'day' argument, or the original datetime day, if the argument is not present. Then, subtract from the day until it fits in the year and month found after their operations. 5) Add the relative 'days' argument to the absolute day. Notice that the 'weeks' argument is multiplied by 7 and added to 'days'. 6) Do steps 1 and 2 for hour/hours, minute/minutes, second/seconds, microsecond/microseconds. 7) If the 'weekday' argument is present, calculate the weekday, with the given (wday, nth) tuple. wday is the index of the weekday (0-6, 0=Mon), and nth is the number of weeks to add forward or backward, depending on its signal. Notice that if the calculated date is already Monday, for example, using (0, 1) or (0, -1) won't change the day. """ def __init__(self, dt1=None, dt2=None, years=0, months=0, days=0, leapdays=0, weeks=0, hours=0, minutes=0, seconds=0, microseconds=0, year=None, month=None, day=None, weekday=None, yearday=None, nlyearday=None, hour=None, minute=None, second=None, microsecond=None): if dt1 and dt2: if (not isinstance(dt1, datetime.date)) or (not isinstance(dt2, datetime.date)): raise TypeError("relativedelta only diffs datetime/date") if not type(dt1) == type(dt2): #isinstance(dt1, type(dt2)): if not isinstance(dt1, datetime.datetime): dt1 = datetime.datetime.fromordinal(dt1.toordinal()) elif not isinstance(dt2, datetime.datetime): dt2 = datetime.datetime.fromordinal(dt2.toordinal()) self.years = 0 self.months = 0 self.days = 0 self.leapdays = 0 self.hours = 0 self.minutes = 0 self.seconds = 0 self.microseconds = 0 self.year = None self.month = None self.day = None self.weekday = None self.hour = None self.minute = None self.second = None self.microsecond = None self._has_time = 0 months = (dt1.year*12+dt1.month)-(dt2.year*12+dt2.month) self._set_months(months) dtm = self.__radd__(dt2) if dt1 < dt2: while dt1 > dtm: months += 1 self._set_months(months) dtm = self.__radd__(dt2) else: while dt1 < dtm: months -= 1 self._set_months(months) dtm = self.__radd__(dt2) delta = dt1 - dtm self.seconds = delta.seconds+delta.days*86400 self.microseconds = delta.microseconds else: self.years = years self.months = months self.days = days+weeks*7 self.leapdays = leapdays self.hours = hours self.minutes = minutes self.seconds = seconds self.microseconds = microseconds self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.microsecond = microsecond if isinstance(weekday, integer_types): self.weekday = weekdays[weekday] else: self.weekday = weekday yday = 0 if nlyearday: yday = nlyearday elif yearday: yday = yearday if yearday > 59: self.leapdays = -1 if yday: ydayidx = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 366] for idx, ydays in enumerate(ydayidx): if yday <= ydays: self.month = idx+1 if idx == 0: self.day = yday else: self.day = yday-ydayidx[idx-1] break else: raise ValueError("invalid year day (%d)" % yday) self._fix() def _fix(self): if abs(self.microseconds) > 999999: s = self.microseconds//abs(self.microseconds) div, mod = divmod(self.microseconds*s, 1000000) self.microseconds = mod*s self.seconds += div*s if abs(self.seconds) > 59: s = self.seconds//abs(self.seconds) div, mod = divmod(self.seconds*s, 60) self.seconds = mod*s self.minutes += div*s if abs(self.minutes) > 59: s = self.minutes//abs(self.minutes) div, mod = divmod(self.minutes*s, 60) self.minutes = mod*s self.hours += div*s if abs(self.hours) > 23: s = self.hours//abs(self.hours) div, mod = divmod(self.hours*s, 24) self.hours = mod*s self.days += div*s if abs(self.months) > 11: s = self.months//abs(self.months) div, mod = divmod(self.months*s, 12) self.months = mod*s self.years += div*s if (self.hours or self.minutes or self.seconds or self.microseconds or self.hour is not None or self.minute is not None or self.second is not None or self.microsecond is not None): self._has_time = 1 else: self._has_time = 0 def _set_months(self, months): self.months = months if abs(self.months) > 11: s = self.months//abs(self.months) div, mod = divmod(self.months*s, 12) self.months = mod*s self.years = div*s else: self.years = 0 def __add__(self, other): if isinstance(other, relativedelta): return relativedelta(years=other.years+self.years, months=other.months+self.months, days=other.days+self.days, hours=other.hours+self.hours, minutes=other.minutes+self.minutes, seconds=other.seconds+self.seconds, microseconds=other.microseconds+self.microseconds, leapdays=other.leapdays or self.leapdays, year=other.year or self.year, month=other.month or self.month, day=other.day or self.day, weekday=other.weekday or self.weekday, hour=other.hour or self.hour, minute=other.minute or self.minute, second=other.second or self.second, microsecond=other.microsecond or self.microsecond) if not isinstance(other, datetime.date): raise TypeError("unsupported type for add operation") elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth)-1)*7 if nth > 0: jumpdays += (7-ret.weekday()+weekday)%7 else: jumpdays += (ret.weekday()-weekday)%7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret def __radd__(self, other): return self.__add__(other) def __rsub__(self, other): return self.__neg__().__radd__(other) def __sub__(self, other): if not isinstance(other, relativedelta): raise TypeError("unsupported type for sub operation") return relativedelta(years=self.years-other.years, months=self.months-other.months, days=self.days-other.days, hours=self.hours-other.hours, minutes=self.minutes-other.minutes, seconds=self.seconds-other.seconds, microseconds=self.microseconds-other.microseconds, leapdays=self.leapdays or other.leapdays, year=self.year or other.year, month=self.month or other.month, day=self.day or other.day, weekday=self.weekday or other.weekday, hour=self.hour or other.hour, minute=self.minute or other.minute, second=self.second or other.second, microsecond=self.microsecond or other.microsecond) def __neg__(self): return relativedelta(years=-self.years, months=-self.months, days=-self.days, hours=-self.hours, minutes=-self.minutes, seconds=-self.seconds, microseconds=-self.microseconds, leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) def __bool__(self): return not (not self.years and not self.months and not self.days and not self.hours and not self.minutes and not self.seconds and not self.microseconds and not self.leapdays and self.year is None and self.month is None and self.day is None and self.weekday is None and self.hour is None and self.minute is None and self.second is None and self.microsecond is None) def __mul__(self, other): f = float(other) return relativedelta(years=int(self.years*f), months=int(self.months*f), days=int(self.days*f), hours=int(self.hours*f), minutes=int(self.minutes*f), seconds=int(self.seconds*f), microseconds=int(self.microseconds*f), leapdays=self.leapdays, year=self.year, month=self.month, day=self.day, weekday=self.weekday, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond) __rmul__ = __mul__ def __eq__(self, other): if not isinstance(other, relativedelta): return False if self.weekday or other.weekday: if not self.weekday or not other.weekday: return False if self.weekday.weekday != other.weekday.weekday: return False n1, n2 = self.weekday.n, other.weekday.n if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): return False return (self.years == other.years and self.months == other.months and self.days == other.days and self.hours == other.hours and self.minutes == other.minutes and self.seconds == other.seconds and self.leapdays == other.leapdays and self.year == other.year and self.month == other.month and self.day == other.day and self.hour == other.hour and self.minute == other.minute and self.second == other.second and self.microsecond == other.microsecond) def __ne__(self, other): return not self.__eq__(other) def __div__(self, other): return self.__mul__(1/float(other)) __truediv__ = __div__ def __repr__(self): l = [] for attr in ["years", "months", "days", "leapdays", "hours", "minutes", "seconds", "microseconds"]: value = getattr(self, attr) if value: l.append("%s=%+d" % (attr, value)) for attr in ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) # vim:ts=4:sw=4:et
17,224
Python
.py
388
29.546392
92
0.517096
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,714
easter.py
CouchPotato_CouchPotatoServer/libs/dateutil/easter.py
""" Copyright (c) 2003-2007 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ __license__ = "Simplified BSD" import datetime __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 def easter(year, method=EASTER_WESTERN): """ This method was ported from the work done by GM Arts, on top of the algorithm by Claus Tondering, which was based in part on the algorithm of Ouding (1940), as quoted in "Explanatory Supplement to the Astronomical Almanac", P. Kenneth Seidelmann, editor. This algorithm implements three different easter calculation methods: 1 - Original calculation in Julian calendar, valid in dates after 326 AD 2 - Original method, with date converted to Gregorian calendar, valid in years 1583 to 4099 3 - Revised method, in Gregorian calendar, valid in years 1583 to 4099 as well These methods are represented by the constants: EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 The default method is method 3. More about the algorithm may be found at: http://users.chariot.net.au/~gmarts/eastalg.htm and http://www.tondering.dk/claus/calendar.html """ if not (1 <= method <= 3): raise ValueError("invalid method") # g - Golden year - 1 # c - Century # h - (23 - Epact) mod 30 # i - Number of days from March 21 to Paschal Full Moon # j - Weekday for PFM (0=Sunday, etc) # p - Number of days from March 21 to Sunday on or before PFM # (-6 to 28 methods 1 & 3, to 56 for method 2) # e - Extra days to add for method 2 (converting Julian # date to Gregorian date) y = year g = y % 19 e = 0 if method < 3: # Old method i = (19*g+15)%30 j = (y+y//4+i)%7 if method == 2: # Extra dates to convert Julian to Gregorian date e = 10 if y > 1600: e = e+y//100-16-(y//100-16)//4 else: # New method c = y//100 h = (c-c//4-(8*c+13)//25+19*g+15)%30 i = h-(h//28)*(1-(h//28)*(29//(h+1))*((21-g)//11)) j = (y+y//4+i+2-c+c//4)%7 # p can be from -6 to 56 corresponding to dates 22 March to 23 May # (later dates apply to method 2, although 23 May never actually occurs) p = i-j+e d = 1+(p+27+(p+6)//40)%31 m = 3+(p+26)//30 return datetime.date(int(y), int(m), int(d))
2,578
Python
.py
71
30.352113
76
0.622832
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,715
__init__.py
CouchPotato_CouchPotatoServer/libs/dateutil/__init__.py
# -*- coding: utf-8 -*- """ Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ __author__ = "Tomi Pievil√§inen <tomi.pievilainen@iki.fi>" __license__ = "Simplified BSD" __version__ = "2.1"
278
Python
.py
9
29.777778
64
0.705224
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,716
rrule.py
CouchPotato_CouchPotatoServer/libs/dateutil/rrule.py
""" Copyright (c) 2003-2010 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ __license__ = "Simplified BSD" import itertools import datetime import calendar try: import _thread except ImportError: import thread as _thread import sys from six import advance_iterator, integer_types __all__ = ["rrule", "rruleset", "rrulestr", "YEARLY", "MONTHLY", "WEEKLY", "DAILY", "HOURLY", "MINUTELY", "SECONDLY", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] # Every mask is 7 days longer to handle cross-year weekly periods. M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30+ [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) M365MASK = list(M366MASK) M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) MDAY365MASK = list(MDAY366MASK) M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) NMDAY365MASK = list(NMDAY366MASK) M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] MDAY365MASK = tuple(MDAY365MASK) M365MASK = tuple(M365MASK) (YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY) = list(range(7)) # Imported on demand. easter = None parser = None class weekday(object): __slots__ = ["weekday", "n"] def __init__(self, weekday, n=None): if n == 0: raise ValueError("Can't create weekday with n == 0") self.weekday = weekday self.n = n def __call__(self, n): if n == self.n: return self else: return self.__class__(self.weekday, n) def __eq__(self, other): try: if self.weekday != other.weekday or self.n != other.n: return False except AttributeError: return False return True def __repr__(self): s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] if not self.n: return s else: return "%s(%+d)" % (s, self.n) MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)]) class rrulebase(object): def __init__(self, cache=False): if cache: self._cache = [] self._cache_lock = _thread.allocate_lock() self._cache_gen = self._iter() self._cache_complete = False else: self._cache = None self._cache_complete = False self._len = None def __iter__(self): if self._cache_complete: return iter(self._cache) elif self._cache is None: return self._iter() else: return self._iter_cached() def _iter_cached(self): i = 0 gen = self._cache_gen cache = self._cache acquire = self._cache_lock.acquire release = self._cache_lock.release while gen: if i == len(cache): acquire() if self._cache_complete: break try: for j in range(10): cache.append(advance_iterator(gen)) except StopIteration: self._cache_gen = gen = None self._cache_complete = True break release() yield cache[i] i += 1 while i < self._len: yield cache[i] i += 1 def __getitem__(self, item): if self._cache_complete: return self._cache[item] elif isinstance(item, slice): if item.step and item.step < 0: return list(iter(self))[item] else: return list(itertools.islice(self, item.start or 0, item.stop or sys.maxsize, item.step or 1)) elif item >= 0: gen = iter(self) try: for i in range(item+1): res = advance_iterator(gen) except StopIteration: raise IndexError return res else: return list(iter(self))[item] def __contains__(self, item): if self._cache_complete: return item in self._cache else: for i in self: if i == item: return True elif i > item: return False return False # __len__() introduces a large performance penality. def count(self): if self._len is None: for x in self: pass return self._len def before(self, dt, inc=False): if self._cache_complete: gen = self._cache else: gen = self last = None if inc: for i in gen: if i > dt: break last = i else: for i in gen: if i >= dt: break last = i return last def after(self, dt, inc=False): if self._cache_complete: gen = self._cache else: gen = self if inc: for i in gen: if i >= dt: return i else: for i in gen: if i > dt: return i return None def between(self, after, before, inc=False): if self._cache_complete: gen = self._cache else: gen = self started = False l = [] if inc: for i in gen: if i > before: break elif not started: if i >= after: started = True l.append(i) else: l.append(i) else: for i in gen: if i >= before: break elif not started: if i > after: started = True l.append(i) else: l.append(i) return l class rrule(rrulebase): def __init__(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False): super(rrule, self).__init__(cache) global easter if not dtstart: dtstart = datetime.datetime.now().replace(microsecond=0) elif not isinstance(dtstart, datetime.datetime): dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) else: dtstart = dtstart.replace(microsecond=0) self._dtstart = dtstart self._tzinfo = dtstart.tzinfo self._freq = freq self._interval = interval self._count = count if until and not isinstance(until, datetime.datetime): until = datetime.datetime.fromordinal(until.toordinal()) self._until = until if wkst is None: self._wkst = calendar.firstweekday() elif isinstance(wkst, integer_types): self._wkst = wkst else: self._wkst = wkst.weekday if bysetpos is None: self._bysetpos = None elif isinstance(bysetpos, integer_types): if bysetpos == 0 or not (-366 <= bysetpos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") self._bysetpos = (bysetpos,) else: self._bysetpos = tuple(bysetpos) for pos in self._bysetpos: if pos == 0 or not (-366 <= pos <= 366): raise ValueError("bysetpos must be between 1 and 366, " "or between -366 and -1") if not (byweekno or byyearday or bymonthday or byweekday is not None or byeaster is not None): if freq == YEARLY: if not bymonth: bymonth = dtstart.month bymonthday = dtstart.day elif freq == MONTHLY: bymonthday = dtstart.day elif freq == WEEKLY: byweekday = dtstart.weekday() # bymonth if not bymonth: self._bymonth = None elif isinstance(bymonth, integer_types): self._bymonth = (bymonth,) else: self._bymonth = tuple(bymonth) # byyearday if not byyearday: self._byyearday = None elif isinstance(byyearday, integer_types): self._byyearday = (byyearday,) else: self._byyearday = tuple(byyearday) # byeaster if byeaster is not None: if not easter: from dateutil import easter if isinstance(byeaster, integer_types): self._byeaster = (byeaster,) else: self._byeaster = tuple(byeaster) else: self._byeaster = None # bymonthay if not bymonthday: self._bymonthday = () self._bynmonthday = () elif isinstance(bymonthday, integer_types): if bymonthday < 0: self._bynmonthday = (bymonthday,) self._bymonthday = () else: self._bymonthday = (bymonthday,) self._bynmonthday = () else: self._bymonthday = tuple([x for x in bymonthday if x > 0]) self._bynmonthday = tuple([x for x in bymonthday if x < 0]) # byweekno if byweekno is None: self._byweekno = None elif isinstance(byweekno, integer_types): self._byweekno = (byweekno,) else: self._byweekno = tuple(byweekno) # byweekday / bynweekday if byweekday is None: self._byweekday = None self._bynweekday = None elif isinstance(byweekday, integer_types): self._byweekday = (byweekday,) self._bynweekday = None elif hasattr(byweekday, "n"): if not byweekday.n or freq > MONTHLY: self._byweekday = (byweekday.weekday,) self._bynweekday = None else: self._bynweekday = ((byweekday.weekday, byweekday.n),) self._byweekday = None else: self._byweekday = [] self._bynweekday = [] for wday in byweekday: if isinstance(wday, integer_types): self._byweekday.append(wday) elif not wday.n or freq > MONTHLY: self._byweekday.append(wday.weekday) else: self._bynweekday.append((wday.weekday, wday.n)) self._byweekday = tuple(self._byweekday) self._bynweekday = tuple(self._bynweekday) if not self._byweekday: self._byweekday = None elif not self._bynweekday: self._bynweekday = None # byhour if byhour is None: if freq < HOURLY: self._byhour = (dtstart.hour,) else: self._byhour = None elif isinstance(byhour, integer_types): self._byhour = (byhour,) else: self._byhour = tuple(byhour) # byminute if byminute is None: if freq < MINUTELY: self._byminute = (dtstart.minute,) else: self._byminute = None elif isinstance(byminute, integer_types): self._byminute = (byminute,) else: self._byminute = tuple(byminute) # bysecond if bysecond is None: if freq < SECONDLY: self._bysecond = (dtstart.second,) else: self._bysecond = None elif isinstance(bysecond, integer_types): self._bysecond = (bysecond,) else: self._bysecond = tuple(bysecond) if self._freq >= HOURLY: self._timeset = None else: self._timeset = [] for hour in self._byhour: for minute in self._byminute: for second in self._bysecond: self._timeset.append( datetime.time(hour, minute, second, tzinfo=self._tzinfo)) self._timeset.sort() self._timeset = tuple(self._timeset) def _iter(self): year, month, day, hour, minute, second, weekday, yearday, _ = \ self._dtstart.timetuple() # Some local variables to speed things up a bit freq = self._freq interval = self._interval wkst = self._wkst until = self._until bymonth = self._bymonth byweekno = self._byweekno byyearday = self._byyearday byweekday = self._byweekday byeaster = self._byeaster bymonthday = self._bymonthday bynmonthday = self._bynmonthday bysetpos = self._bysetpos byhour = self._byhour byminute = self._byminute bysecond = self._bysecond ii = _iterinfo(self) ii.rebuild(year, month) getdayset = {YEARLY:ii.ydayset, MONTHLY:ii.mdayset, WEEKLY:ii.wdayset, DAILY:ii.ddayset, HOURLY:ii.ddayset, MINUTELY:ii.ddayset, SECONDLY:ii.ddayset}[freq] if freq < HOURLY: timeset = self._timeset else: gettimeset = {HOURLY:ii.htimeset, MINUTELY:ii.mtimeset, SECONDLY:ii.stimeset}[freq] if ((freq >= HOURLY and self._byhour and hour not in self._byhour) or (freq >= MINUTELY and self._byminute and minute not in self._byminute) or (freq >= SECONDLY and self._bysecond and second not in self._bysecond)): timeset = () else: timeset = gettimeset(hour, minute, second) total = 0 count = self._count while True: # Get dayset with the right frequency dayset, start, end = getdayset(year, month, day) # Do the "hard" work ;-) filtered = False for i in dayset[start:end]: if ((bymonth and ii.mmask[i] not in bymonth) or (byweekno and not ii.wnomask[i]) or (byweekday and ii.wdaymask[i] not in byweekday) or (ii.nwdaymask and not ii.nwdaymask[i]) or (byeaster and not ii.eastermask[i]) or ((bymonthday or bynmonthday) and ii.mdaymask[i] not in bymonthday and ii.nmdaymask[i] not in bynmonthday) or (byyearday and ((i < ii.yearlen and i+1 not in byyearday and -ii.yearlen+i not in byyearday) or (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and -ii.nextyearlen+i-ii.yearlen not in byyearday)))): dayset[i] = None filtered = True # Output results if bysetpos and timeset: poslist = [] for pos in bysetpos: if pos < 0: daypos, timepos = divmod(pos, len(timeset)) else: daypos, timepos = divmod(pos-1, len(timeset)) try: i = [x for x in dayset[start:end] if x is not None][daypos] time = timeset[timepos] except IndexError: pass else: date = datetime.date.fromordinal(ii.yearordinal+i) res = datetime.datetime.combine(date, time) if res not in poslist: poslist.append(res) poslist.sort() for res in poslist: if until and res > until: self._len = total return elif res >= self._dtstart: total += 1 yield res if count: count -= 1 if not count: self._len = total return else: for i in dayset[start:end]: if i is not None: date = datetime.date.fromordinal(ii.yearordinal+i) for time in timeset: res = datetime.datetime.combine(date, time) if until and res > until: self._len = total return elif res >= self._dtstart: total += 1 yield res if count: count -= 1 if not count: self._len = total return # Handle frequency and interval fixday = False if freq == YEARLY: year += interval if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == MONTHLY: month += interval if month > 12: div, mod = divmod(month, 12) month = mod year += div if month == 0: month = 12 year -= 1 if year > datetime.MAXYEAR: self._len = total return ii.rebuild(year, month) elif freq == WEEKLY: if wkst > weekday: day += -(weekday+1+(6-wkst))+self._interval*7 else: day += -(weekday-wkst)+self._interval*7 weekday = wkst fixday = True elif freq == DAILY: day += interval fixday = True elif freq == HOURLY: if filtered: # Jump to one iteration before next day hour += ((23-hour)//interval)*interval while True: hour += interval div, mod = divmod(hour, 24) if div: hour = mod day += div fixday = True if not byhour or hour in byhour: break timeset = gettimeset(hour, minute, second) elif freq == MINUTELY: if filtered: # Jump to one iteration before next day minute += ((1439-(hour*60+minute))//interval)*interval while True: minute += interval div, mod = divmod(minute, 60) if div: minute = mod hour += div div, mod = divmod(hour, 24) if div: hour = mod day += div fixday = True filtered = False if ((not byhour or hour in byhour) and (not byminute or minute in byminute)): break timeset = gettimeset(hour, minute, second) elif freq == SECONDLY: if filtered: # Jump to one iteration before next day second += (((86399-(hour*3600+minute*60+second)) //interval)*interval) while True: second += self._interval div, mod = divmod(second, 60) if div: second = mod minute += div div, mod = divmod(minute, 60) if div: minute = mod hour += div div, mod = divmod(hour, 24) if div: hour = mod day += div fixday = True if ((not byhour or hour in byhour) and (not byminute or minute in byminute) and (not bysecond or second in bysecond)): break timeset = gettimeset(hour, minute, second) if fixday and day > 28: daysinmonth = calendar.monthrange(year, month)[1] if day > daysinmonth: while day > daysinmonth: day -= daysinmonth month += 1 if month == 13: month = 1 year += 1 if year > datetime.MAXYEAR: self._len = total return daysinmonth = calendar.monthrange(year, month)[1] ii.rebuild(year, month) class _iterinfo(object): __slots__ = ["rrule", "lastyear", "lastmonth", "yearlen", "nextyearlen", "yearordinal", "yearweekday", "mmask", "mrange", "mdaymask", "nmdaymask", "wdaymask", "wnomask", "nwdaymask", "eastermask"] def __init__(self, rrule): for attr in self.__slots__: setattr(self, attr, None) self.rrule = rrule def rebuild(self, year, month): # Every mask is 7 days longer to handle cross-year weekly periods. rr = self.rrule if year != self.lastyear: self.yearlen = 365+calendar.isleap(year) self.nextyearlen = 365+calendar.isleap(year+1) firstyday = datetime.date(year, 1, 1) self.yearordinal = firstyday.toordinal() self.yearweekday = firstyday.weekday() wday = datetime.date(year, 1, 1).weekday() if self.yearlen == 365: self.mmask = M365MASK self.mdaymask = MDAY365MASK self.nmdaymask = NMDAY365MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M365RANGE else: self.mmask = M366MASK self.mdaymask = MDAY366MASK self.nmdaymask = NMDAY366MASK self.wdaymask = WDAYMASK[wday:] self.mrange = M366RANGE if not rr._byweekno: self.wnomask = None else: self.wnomask = [0]*(self.yearlen+7) #no1wkst = firstwkst = self.wdaymask.index(rr._wkst) no1wkst = firstwkst = (7-self.yearweekday+rr._wkst)%7 if no1wkst >= 4: no1wkst = 0 # Number of days in the year, plus the days we got # from last year. wyearlen = self.yearlen+(self.yearweekday-rr._wkst)%7 else: # Number of days in the year, minus the days we # left in last year. wyearlen = self.yearlen-no1wkst div, mod = divmod(wyearlen, 7) numweeks = div+mod//4 for n in rr._byweekno: if n < 0: n += numweeks+1 if not (0 < n <= numweeks): continue if n > 1: i = no1wkst+(n-1)*7 if no1wkst != firstwkst: i -= 7-firstwkst else: i = no1wkst for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if 1 in rr._byweekno: # Check week number 1 of next year as well # TODO: Check -numweeks for next year. i = no1wkst+numweeks*7 if no1wkst != firstwkst: i -= 7-firstwkst if i < self.yearlen: # If week starts in next year, we # don't care about it. for j in range(7): self.wnomask[i] = 1 i += 1 if self.wdaymask[i] == rr._wkst: break if no1wkst: # Check last week number of last year as # well. If no1wkst is 0, either the year # started on week start, or week number 1 # got days from last year, so there are no # days from last year's last week number in # this year. if -1 not in rr._byweekno: lyearweekday = datetime.date(year-1, 1, 1).weekday() lno1wkst = (7-lyearweekday+rr._wkst)%7 lyearlen = 365+calendar.isleap(year-1) if lno1wkst >= 4: lno1wkst = 0 lnumweeks = 52+(lyearlen+ (lyearweekday-rr._wkst)%7)%7//4 else: lnumweeks = 52+(self.yearlen-no1wkst)%7//4 else: lnumweeks = -1 if lnumweeks in rr._byweekno: for i in range(no1wkst): self.wnomask[i] = 1 if (rr._bynweekday and (month != self.lastmonth or year != self.lastyear)): ranges = [] if rr._freq == YEARLY: if rr._bymonth: for month in rr._bymonth: ranges.append(self.mrange[month-1:month+1]) else: ranges = [(0, self.yearlen)] elif rr._freq == MONTHLY: ranges = [self.mrange[month-1:month+1]] if ranges: # Weekly frequency won't get here, so we may not # care about cross-year weekly periods. self.nwdaymask = [0]*self.yearlen for first, last in ranges: last -= 1 for wday, n in rr._bynweekday: if n < 0: i = last+(n+1)*7 i -= (self.wdaymask[i]-wday)%7 else: i = first+(n-1)*7 i += (7-self.wdaymask[i]+wday)%7 if first <= i <= last: self.nwdaymask[i] = 1 if rr._byeaster: self.eastermask = [0]*(self.yearlen+7) eyday = easter.easter(year).toordinal()-self.yearordinal for offset in rr._byeaster: self.eastermask[eyday+offset] = 1 self.lastyear = year self.lastmonth = month def ydayset(self, year, month, day): return list(range(self.yearlen)), 0, self.yearlen def mdayset(self, year, month, day): set = [None]*self.yearlen start, end = self.mrange[month-1:month+1] for i in range(start, end): set[i] = i return set, start, end def wdayset(self, year, month, day): # We need to handle cross-year weeks here. set = [None]*(self.yearlen+7) i = datetime.date(year, month, day).toordinal()-self.yearordinal start = i for j in range(7): set[i] = i i += 1 #if (not (0 <= i < self.yearlen) or # self.wdaymask[i] == self.rrule._wkst): # This will cross the year boundary, if necessary. if self.wdaymask[i] == self.rrule._wkst: break return set, start, i def ddayset(self, year, month, day): set = [None]*self.yearlen i = datetime.date(year, month, day).toordinal()-self.yearordinal set[i] = i return set, i, i+1 def htimeset(self, hour, minute, second): set = [] rr = self.rrule for minute in rr._byminute: for second in rr._bysecond: set.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) set.sort() return set def mtimeset(self, hour, minute, second): set = [] rr = self.rrule for second in rr._bysecond: set.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) set.sort() return set def stimeset(self, hour, minute, second): return (datetime.time(hour, minute, second, tzinfo=self.rrule._tzinfo),) class rruleset(rrulebase): class _genitem(object): def __init__(self, genlist, gen): try: self.dt = advance_iterator(gen) genlist.append(self) except StopIteration: pass self.genlist = genlist self.gen = gen def __next__(self): try: self.dt = advance_iterator(self.gen) except StopIteration: self.genlist.remove(self) next = __next__ def __lt__(self, other): return self.dt < other.dt def __gt__(self, other): return self.dt > other.dt def __eq__(self, other): return self.dt == other.dt def __ne__(self, other): return self.dt != other.dt def __init__(self, cache=False): super(rruleset, self).__init__(cache) self._rrule = [] self._rdate = [] self._exrule = [] self._exdate = [] def rrule(self, rrule): self._rrule.append(rrule) def rdate(self, rdate): self._rdate.append(rdate) def exrule(self, exrule): self._exrule.append(exrule) def exdate(self, exdate): self._exdate.append(exdate) def _iter(self): rlist = [] self._rdate.sort() self._genitem(rlist, iter(self._rdate)) for gen in [iter(x) for x in self._rrule]: self._genitem(rlist, gen) rlist.sort() exlist = [] self._exdate.sort() self._genitem(exlist, iter(self._exdate)) for gen in [iter(x) for x in self._exrule]: self._genitem(exlist, gen) exlist.sort() lastdt = None total = 0 while rlist: ritem = rlist[0] if not lastdt or lastdt != ritem.dt: while exlist and exlist[0] < ritem: advance_iterator(exlist[0]) exlist.sort() if not exlist or ritem != exlist[0]: total += 1 yield ritem.dt lastdt = ritem.dt advance_iterator(ritem) rlist.sort() self._len = total class _rrulestr(object): _freq_map = {"YEARLY": YEARLY, "MONTHLY": MONTHLY, "WEEKLY": WEEKLY, "DAILY": DAILY, "HOURLY": HOURLY, "MINUTELY": MINUTELY, "SECONDLY": SECONDLY} _weekday_map = {"MO":0,"TU":1,"WE":2,"TH":3,"FR":4,"SA":5,"SU":6} def _handle_int(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = int(value) def _handle_int_list(self, rrkwargs, name, value, **kwargs): rrkwargs[name.lower()] = [int(x) for x in value.split(',')] _handle_INTERVAL = _handle_int _handle_COUNT = _handle_int _handle_BYSETPOS = _handle_int_list _handle_BYMONTH = _handle_int_list _handle_BYMONTHDAY = _handle_int_list _handle_BYYEARDAY = _handle_int_list _handle_BYEASTER = _handle_int_list _handle_BYWEEKNO = _handle_int_list _handle_BYHOUR = _handle_int_list _handle_BYMINUTE = _handle_int_list _handle_BYSECOND = _handle_int_list def _handle_FREQ(self, rrkwargs, name, value, **kwargs): rrkwargs["freq"] = self._freq_map[value] def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): global parser if not parser: from dateutil import parser try: rrkwargs["until"] = parser.parse(value, ignoretz=kwargs.get("ignoretz"), tzinfos=kwargs.get("tzinfos")) except ValueError: raise ValueError("invalid until date") def _handle_WKST(self, rrkwargs, name, value, **kwargs): rrkwargs["wkst"] = self._weekday_map[value] def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwarsg): l = [] for wday in value.split(','): for i in range(len(wday)): if wday[i] not in '+-0123456789': break n = wday[:i] or None w = wday[i:] if n: n = int(n) l.append(weekdays[self._weekday_map[w]](n)) rrkwargs["byweekday"] = l _handle_BYDAY = _handle_BYWEEKDAY def _parse_rfc_rrule(self, line, dtstart=None, cache=False, ignoretz=False, tzinfos=None): if line.find(':') != -1: name, value = line.split(':') if name != "RRULE": raise ValueError("unknown parameter name") else: value = line rrkwargs = {} for pair in value.split(';'): name, value = pair.split('=') name = name.upper() value = value.upper() try: getattr(self, "_handle_"+name)(rrkwargs, name, value, ignoretz=ignoretz, tzinfos=tzinfos) except AttributeError: raise ValueError("unknown parameter '%s'" % name) except (KeyError, ValueError): raise ValueError("invalid '%s': %s" % (name, value)) return rrule(dtstart=dtstart, cache=cache, **rrkwargs) def _parse_rfc(self, s, dtstart=None, cache=False, unfold=False, forceset=False, compatible=False, ignoretz=False, tzinfos=None): global parser if compatible: forceset = True unfold = True s = s.upper() if not s.strip(): raise ValueError("empty string") if unfold: lines = s.splitlines() i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 else: lines = s.split() if (not forceset and len(lines) == 1 and (s.find(':') == -1 or s.startswith('RRULE:'))): return self._parse_rfc_rrule(lines[0], cache=cache, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos) else: rrulevals = [] rdatevals = [] exrulevals = [] exdatevals = [] for line in lines: if not line: continue if line.find(':') == -1: name = "RRULE" value = line else: name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError("empty property name") name = parms[0] parms = parms[1:] if name == "RRULE": for parm in parms: raise ValueError("unsupported RRULE parm: "+parm) rrulevals.append(value) elif name == "RDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError("unsupported RDATE parm: "+parm) rdatevals.append(value) elif name == "EXRULE": for parm in parms: raise ValueError("unsupported EXRULE parm: "+parm) exrulevals.append(value) elif name == "EXDATE": for parm in parms: if parm != "VALUE=DATE-TIME": raise ValueError("unsupported RDATE parm: "+parm) exdatevals.append(value) elif name == "DTSTART": for parm in parms: raise ValueError("unsupported DTSTART parm: "+parm) if not parser: from dateutil import parser dtstart = parser.parse(value, ignoretz=ignoretz, tzinfos=tzinfos) else: raise ValueError("unsupported property: "+name) if (forceset or len(rrulevals) > 1 or rdatevals or exrulevals or exdatevals): if not parser and (rdatevals or exdatevals): from dateutil import parser set = rruleset(cache=cache) for value in rrulevals: set.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in rdatevals: for datestr in value.split(','): set.rdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exrulevals: set.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, ignoretz=ignoretz, tzinfos=tzinfos)) for value in exdatevals: for datestr in value.split(','): set.exdate(parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos)) if compatible and dtstart: set.rdate(dtstart) return set else: return self._parse_rfc_rrule(rrulevals[0], dtstart=dtstart, cache=cache, ignoretz=ignoretz, tzinfos=tzinfos) def __call__(self, s, **kwargs): return self._parse_rfc(s, **kwargs) rrulestr = _rrulestr() # vim:ts=4:sw=4:et
41,036
Python
.py
1,032
23.849806
78
0.456784
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,717
tzwin.py
CouchPotato_CouchPotatoServer/libs/dateutil/tzwin.py
# This code was originally contributed by Jeffrey Harris. import datetime import struct import winreg __all__ = ["tzwin", "tzwinlocal"] ONEWEEK = datetime.timedelta(7) TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" def _settzkeyname(): global TZKEYNAME handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) try: winreg.OpenKey(handle, TZKEYNAMENT).Close() TZKEYNAME = TZKEYNAMENT except WindowsError: TZKEYNAME = TZKEYNAME9X handle.Close() _settzkeyname() class tzwinbase(datetime.tzinfo): """tzinfo class based on win32's timezones available in the registry.""" def utcoffset(self, dt): if self._isdst(dt): return datetime.timedelta(minutes=self._dstoffset) else: return datetime.timedelta(minutes=self._stdoffset) def dst(self, dt): if self._isdst(dt): minutes = self._dstoffset - self._stdoffset return datetime.timedelta(minutes=minutes) else: return datetime.timedelta(0) def tzname(self, dt): if self._isdst(dt): return self._dstname else: return self._stdname def list(): """Return a list of all time zones known to the system.""" handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzkey = winreg.OpenKey(handle, TZKEYNAME) result = [winreg.EnumKey(tzkey, i) for i in range(winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result list = staticmethod(list) def display(self): return self._display def _isdst(self, dt): dston = picknthweekday(dt.year, self._dstmonth, self._dstdayofweek, self._dsthour, self._dstminute, self._dstweeknumber) dstoff = picknthweekday(dt.year, self._stdmonth, self._stddayofweek, self._stdhour, self._stdminute, self._stdweeknumber) if dston < dstoff: return dston <= dt.replace(tzinfo=None) < dstoff else: return not dstoff <= dt.replace(tzinfo=None) < dston class tzwin(tzwinbase): def __init__(self, name): self._name = name handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzkey = winreg.OpenKey(handle, "%s\%s" % (TZKEYNAME, name)) keydict = valuestodict(tzkey) tzkey.Close() handle.Close() self._stdname = keydict["Std"].encode("iso-8859-1") self._dstname = keydict["Dlt"].encode("iso-8859-1") self._display = keydict["Display"] # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm tup = struct.unpack("=3l16h", keydict["TZI"]) self._stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 self._dstoffset = self._stdoffset-tup[2] # + DaylightBias * -1 (self._stdmonth, self._stddayofweek, # Sunday = 0 self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[4:9] (self._dstmonth, self._dstdayofweek, # Sunday = 0 self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[12:17] def __repr__(self): return "tzwin(%s)" % repr(self._name) def __reduce__(self): return (self.__class__, (self._name,)) class tzwinlocal(tzwinbase): def __init__(self): handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) tzlocalkey = winreg.OpenKey(handle, TZLOCALKEYNAME) keydict = valuestodict(tzlocalkey) tzlocalkey.Close() self._stdname = keydict["StandardName"].encode("iso-8859-1") self._dstname = keydict["DaylightName"].encode("iso-8859-1") try: tzkey = winreg.OpenKey(handle, "%s\%s"%(TZKEYNAME, self._stdname)) _keydict = valuestodict(tzkey) self._display = _keydict["Display"] tzkey.Close() except OSError: self._display = None handle.Close() self._stdoffset = -keydict["Bias"]-keydict["StandardBias"] self._dstoffset = self._stdoffset-keydict["DaylightBias"] # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm tup = struct.unpack("=8h", keydict["StandardStart"]) (self._stdmonth, self._stddayofweek, # Sunday = 0 self._stdweeknumber, # Last = 5 self._stdhour, self._stdminute) = tup[1:6] tup = struct.unpack("=8h", keydict["DaylightStart"]) (self._dstmonth, self._dstdayofweek, # Sunday = 0 self._dstweeknumber, # Last = 5 self._dsthour, self._dstminute) = tup[1:6] def __reduce__(self): return (self.__class__, ()) def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek 5 means last instance""" first = datetime.datetime(year, month, 1, hour, minute) weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1)) for n in range(whichweek): dt = weekdayone+(whichweek-n)*ONEWEEK if dt.month == month: return dt def valuestodict(key): """Convert a registry key's values to a dictionary.""" dict = {} size = winreg.QueryInfoKey(key)[1] for i in range(size): data = winreg.EnumValue(key, i) dict[data[0]] = data[1] return dict
5,737
Python
.py
138
32.391304
78
0.613991
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,718
parser.py
CouchPotato_CouchPotatoServer/libs/dateutil/parser.py
# -*- coding:iso-8859-1 -*- """ Copyright (c) 2003-2007 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ from __future__ import unicode_literals __license__ = "Simplified BSD" import datetime import string import time import collections try: from io import StringIO except ImportError: from io import StringIO from six import text_type, binary_type, integer_types from . import relativedelta from . import tz __all__ = ["parse", "parserinfo"] # Some pointers: # # http://www.cl.cam.ac.uk/~mgk25/iso-time.html # http://www.iso.ch/iso/en/prods-services/popstds/datesandtime.html # http://www.w3.org/TR/NOTE-datetime # http://ringmaster.arc.nasa.gov/tools/time_formats.html # http://search.cpan.org/author/MUIR/Time-modules-2003.0211/lib/Time/ParseDate.pm # http://stein.cshl.org/jade/distrib/docs/java.text.SimpleDateFormat.html class _timelex(object): def __init__(self, instream): if isinstance(instream, text_type): instream = StringIO(instream) self.instream = instream self.wordchars = ('abcdfeghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_' 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ') self.numchars = '0123456789' self.whitespace = ' \t\r\n' self.charstack = [] self.tokenstack = [] self.eof = False def get_token(self): if self.tokenstack: return self.tokenstack.pop(0) seenletters = False token = None state = None wordchars = self.wordchars numchars = self.numchars whitespace = self.whitespace while not self.eof: if self.charstack: nextchar = self.charstack.pop(0) else: nextchar = self.instream.read(1) while nextchar == '\x00': nextchar = self.instream.read(1) if not nextchar: self.eof = True break elif not state: token = nextchar if nextchar in wordchars: state = 'a' elif nextchar in numchars: state = '0' elif nextchar in whitespace: token = ' ' break # emit token else: break # emit token elif state == 'a': seenletters = True if nextchar in wordchars: token += nextchar elif nextchar == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token elif state == '0': if nextchar in numchars: token += nextchar elif nextchar == '.': token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == 'a.': seenletters = True if nextchar == '.' or nextchar in wordchars: token += nextchar elif nextchar in numchars and token[-1] == '.': token += nextchar state = '0.' else: self.charstack.append(nextchar) break # emit token elif state == '0.': if nextchar == '.' or nextchar in numchars: token += nextchar elif nextchar in wordchars and token[-1] == '.': token += nextchar state = 'a.' else: self.charstack.append(nextchar) break # emit token if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or token[-1] == '.')): l = token.split('.') token = l[0] for tok in l[1:]: self.tokenstack.append('.') if tok: self.tokenstack.append(tok) return token def __iter__(self): return self def __next__(self): token = self.get_token() if token is None: raise StopIteration return token def next(self): return self.__next__() # Python 2.x support def split(cls, s): return list(cls(s)) split = classmethod(split) class _resultbase(object): def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def _repr(self, classname): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (classname, ", ".join(l)) def __repr__(self): return self._repr(self.__class__.__name__) class parserinfo(object): # m from a.m/p.m, t from ISO T separator JUMP = [" ", ".", ",", ";", "-", "/", "'", "at", "on", "and", "ad", "m", "t", "of", "st", "nd", "rd", "th"] WEEKDAYS = [("Mon", "Monday"), ("Tue", "Tuesday"), ("Wed", "Wednesday"), ("Thu", "Thursday"), ("Fri", "Friday"), ("Sat", "Saturday"), ("Sun", "Sunday")] MONTHS = [("Jan", "January"), ("Feb", "February"), ("Mar", "March"), ("Apr", "April"), ("May", "May"), ("Jun", "June"), ("Jul", "July"), ("Aug", "August"), ("Sep", "Sept", "September"), ("Oct", "October"), ("Nov", "November"), ("Dec", "December")] HMS = [("h", "hour", "hours"), ("m", "minute", "minutes"), ("s", "second", "seconds")] AMPM = [("am", "a"), ("pm", "p")] UTCZONE = ["UTC", "GMT", "Z"] PERTAIN = ["of"] TZOFFSET = {} def __init__(self, dayfirst = False, yearfirst = False): self._jump = self._convert(self.JUMP) self._weekdays = self._convert(self.WEEKDAYS) self._months = self._convert(self.MONTHS) self._hms = self._convert(self.HMS) self._ampm = self._convert(self.AMPM) self._utczone = self._convert(self.UTCZONE) self._pertain = self._convert(self.PERTAIN) self.dayfirst = dayfirst self.yearfirst = yearfirst self._year = time.localtime().tm_year self._century = self._year // 100 * 100 def _convert(self, lst): dct = {} for i in range(len(lst)): v = lst[i] if isinstance(v, tuple): for v in v: dct[v.lower()] = i else: dct[v.lower()] = i return dct def jump(self, name): return name.lower() in self._jump def weekday(self, name): if len(name) >= 3: try: return self._weekdays[name.lower()] except KeyError: pass return None def month(self, name): if len(name) >= 3: try: return self._months[name.lower()] + 1 except KeyError: pass return None def hms(self, name): try: return self._hms[name.lower()] except KeyError: return None def ampm(self, name): try: return self._ampm[name.lower()] except KeyError: return None def pertain(self, name): return name.lower() in self._pertain def utczone(self, name): return name.lower() in self._utczone def tzoffset(self, name): if name in self._utczone: return 0 return self.TZOFFSET.get(name) def convertyear(self, year): if year < 100: year += self._century if abs(year - self._year) >= 50: if year < self._year: year += 100 else: year -= 100 return year def validate(self, res): # move to info if res.year is not None: res.year = self.convertyear(res.year) if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z': res.tzname = "UTC" res.tzoffset = 0 elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): res.tzoffset = 0 return True class parser(object): def __init__(self, info = None): self.info = info or parserinfo() def parse(self, timestr, default = None, ignoretz = False, tzinfos = None, **kwargs): if not default: default = datetime.datetime.now().replace(hour = 0, minute = 0, second = 0, microsecond = 0) res = self._parse(timestr, **kwargs) if res is None: raise ValueError("unknown string format") repl = {} for attr in ["year", "month", "day", "hour", "minute", "second", "microsecond"]: value = getattr(res, attr) if value is not None: repl[attr] = value ret = default.replace(**repl) if res.weekday is not None and not res.day: ret = ret + relativedelta.relativedelta(weekday = res.weekday) if not ignoretz: if isinstance(tzinfos, collections.Callable) or tzinfos and res.tzname in tzinfos: if isinstance(tzinfos, collections.Callable): tzdata = tzinfos(res.tzname, res.tzoffset) else: tzdata = tzinfos.get(res.tzname) if isinstance(tzdata, datetime.tzinfo): tzinfo = tzdata elif isinstance(tzdata, text_type): tzinfo = tz.tzstr(tzdata) elif isinstance(tzdata, integer_types): tzinfo = tz.tzoffset(res.tzname, tzdata) else: raise ValueError("offset must be tzinfo subclass, " \ "tz string, or int offset") ret = ret.replace(tzinfo = tzinfo) elif res.tzname and res.tzname in time.tzname: ret = ret.replace(tzinfo = tz.tzlocal()) elif res.tzoffset == 0: ret = ret.replace(tzinfo = tz.tzutc()) elif res.tzoffset: ret = ret.replace(tzinfo = tz.tzoffset(res.tzname, res.tzoffset)) return ret class _result(_resultbase): __slots__ = ["year", "month", "day", "weekday", "hour", "minute", "second", "microsecond", "tzname", "tzoffset"] def _parse(self, timestr, dayfirst = None, yearfirst = None, fuzzy = False): info = self.info if dayfirst is None: dayfirst = info.dayfirst if yearfirst is None: yearfirst = info.yearfirst res = self._result() l = _timelex.split(timestr) try: # year/month/day list ymd = [] # Index of the month string in ymd mstridx = -1 len_l = len(l) i = 0 while i < len_l: # Check if it's a number try: value_repr = l[i] value = float(value_repr) except ValueError: value = None if value is not None: # Token is a number len_li = len(l[i]) i += 1 if (len(ymd) == 3 and len_li in (2, 4) and (i >= len_l or (l[i] != ':' and info.hms(l[i]) is None))): # 19990101T23[59] s = l[i - 1] res.hour = int(s[:2]) if len_li == 4: res.minute = int(s[2:]) elif len_li == 6 or (len_li > 6 and l[i - 1].find('.') == 6): # YYMMDD or HHMMSS[.ss] s = l[i - 1] if not ymd and l[i - 1].find('.') == -1: ymd.append(info.convertyear(int(s[:2]))) ymd.append(int(s[2:4])) ymd.append(int(s[4:])) else: # 19990101T235959[.59] res.hour = int(s[:2]) res.minute = int(s[2:4]) res.second, res.microsecond = _parsems(s[4:]) elif len_li == 8: # YYYYMMDD s = l[i - 1] ymd.append(int(s[:4])) ymd.append(int(s[4:6])) ymd.append(int(s[6:])) elif len_li in (12, 14): # YYYYMMDDhhmm[ss] s = l[i - 1] ymd.append(int(s[:4])) ymd.append(int(s[4:6])) ymd.append(int(s[6:8])) res.hour = int(s[8:10]) res.minute = int(s[10:12]) if len_li == 14: res.second = int(s[12:]) elif ((i < len_l and info.hms(l[i]) is not None) or (i + 1 < len_l and l[i] == ' ' and info.hms(l[i + 1]) is not None)): # HH[ ]h or MM[ ]m or SS[.ss][ ]s if l[i] == ' ': i += 1 idx = info.hms(l[i]) while True: if idx == 0: res.hour = int(value) if value % 1: res.minute = int(60 * (value % 1)) elif idx == 1: res.minute = int(value) if value % 1: res.second = int(60 * (value % 1)) elif idx == 2: res.second, res.microsecond = \ _parsems(value_repr) i += 1 if i >= len_l or idx == 2: break # 12h00 try: value_repr = l[i] value = float(value_repr) except ValueError: break else: i += 1 idx += 1 if i < len_l: newidx = info.hms(l[i]) if newidx is not None: idx = newidx elif i == len_l and l[i - 2] == ' ' and info.hms(l[i - 3]) is not None: # X h MM or X m SS idx = info.hms(l[i - 3]) + 1 if idx == 1: res.minute = int(value) if value % 1: res.second = int(60 * (value % 1)) elif idx == 2: res.second, res.microsecond = \ _parsems(value_repr) i += 1 elif i + 1 < len_l and l[i] == ':': # HH:MM[:SS[.ss]] res.hour = int(value) i += 1 value = float(l[i]) res.minute = int(value) if value % 1: res.second = int(60 * (value % 1)) i += 1 if i < len_l and l[i] == ':': res.second, res.microsecond = _parsems(l[i + 1]) i += 2 elif i < len_l and l[i] in ('-', '/', '.'): sep = l[i] ymd.append(int(value)) i += 1 if i < len_l and not info.jump(l[i]): try: # 01-01[-01] ymd.append(int(l[i])) except ValueError: # 01-Jan[-01] value = info.month(l[i]) if value is not None: ymd.append(value) assert mstridx == -1 mstridx = len(ymd) - 1 else: return None i += 1 if i < len_l and l[i] == sep: # We have three members i += 1 value = info.month(l[i]) if value is not None: ymd.append(value) mstridx = len(ymd) - 1 assert mstridx == -1 else: ymd.append(int(l[i])) i += 1 elif i >= len_l or info.jump(l[i]): if i + 1 < len_l and info.ampm(l[i + 1]) is not None: # 12 am res.hour = int(value) if res.hour < 12 and info.ampm(l[i + 1]) == 1: res.hour += 12 elif res.hour == 12 and info.ampm(l[i + 1]) == 0: res.hour = 0 i += 1 else: # Year, month or day ymd.append(int(value)) i += 1 elif info.ampm(l[i]) is not None: # 12am res.hour = int(value) if res.hour < 12 and info.ampm(l[i]) == 1: res.hour += 12 elif res.hour == 12 and info.ampm(l[i]) == 0: res.hour = 0 i += 1 elif not fuzzy: return None else: i += 1 continue # Check weekday value = info.weekday(l[i]) if value is not None: res.weekday = value i += 1 continue # Check month name value = info.month(l[i]) if value is not None: ymd.append(value) assert mstridx == -1 mstridx = len(ymd) - 1 i += 1 if i < len_l: if l[i] in ('-', '/'): # Jan-01[-99] sep = l[i] i += 1 ymd.append(int(l[i])) i += 1 if i < len_l and l[i] == sep: # Jan-01-99 i += 1 ymd.append(int(l[i])) i += 1 elif (i + 3 < len_l and l[i] == l[i + 2] == ' ' and info.pertain(l[i + 1])): # Jan of 01 # In this case, 01 is clearly year try: value = int(l[i + 3]) except ValueError: # Wrong guess pass else: # Convert it here to become unambiguous ymd.append(info.convertyear(value)) i += 4 continue # Check am/pm value = info.ampm(l[i]) if value is not None: if value == 1 and res.hour < 12: res.hour += 12 elif value == 0 and res.hour == 12: res.hour = 0 i += 1 continue # Check for a timezone name if (res.hour is not None and len(l[i]) <= 5 and res.tzname is None and res.tzoffset is None and not [x for x in l[i] if x not in string.ascii_uppercase]): res.tzname = l[i] res.tzoffset = info.tzoffset(res.tzname) i += 1 # Check for something like GMT+3, or BRST+3. Notice # that it doesn't mean "I am 3 hours after GMT", but # "my time +3 is GMT". If found, we reverse the # logic so that timezone parsing code will get it # right. if i < len_l and l[i] in ('+', '-'): l[i] = ('+', '-')[l[i] == '+'] res.tzoffset = None if info.utczone(res.tzname): # With something like GMT+3, the timezone # is *not* GMT. res.tzname = None continue # Check for a numbered timezone if res.hour is not None and l[i] in ('+', '-'): signal = (-1, 1)[l[i] == '+'] i += 1 len_li = len(l[i]) if len_li == 4: # -0300 res.tzoffset = int(l[i][:2]) * 3600 + int(l[i][2:]) * 60 elif i + 1 < len_l and l[i + 1] == ':': # -03:00 res.tzoffset = int(l[i]) * 3600 + int(l[i + 2]) * 60 i += 2 elif len_li <= 2: # -[0]3 res.tzoffset = int(l[i][:2]) * 3600 else: return None i += 1 res.tzoffset *= signal # Look for a timezone name between parenthesis if (i + 3 < len_l and info.jump(l[i]) and l[i + 1] == '(' and l[i + 3] == ')' and 3 <= len(l[i + 2]) <= 5 and not [x for x in l[i + 2] if x not in string.ascii_uppercase]): # -0300 (BRST) res.tzname = l[i + 2] i += 4 continue # Check jumps if not (info.jump(l[i]) or fuzzy): return None i += 1 # Process year/month/day len_ymd = len(ymd) if len_ymd > 3: # More than three members!? return None elif len_ymd == 1 or (mstridx != -1 and len_ymd == 2): # One member, or two members with a month string if mstridx != -1: res.month = ymd[mstridx] del ymd[mstridx] if len_ymd > 1 or mstridx == -1: if ymd[0] > 31: res.year = ymd[0] else: res.day = ymd[0] elif len_ymd == 2: # Two members with numbers if ymd[0] > 31: # 99-01 res.year, res.month = ymd elif ymd[1] > 31: # 01-99 res.month, res.year = ymd elif dayfirst and ymd[1] <= 12: # 13-01 res.day, res.month = ymd else: # 01-13 res.month, res.day = ymd if len_ymd == 3: # Three members if mstridx == 0: res.month, res.day, res.year = ymd elif mstridx == 1: if ymd[0] > 31 or (yearfirst and ymd[2] <= 31): # 99-Jan-01 res.year, res.month, res.day = ymd else: # 01-Jan-01 # Give precendence to day-first, since # two-digit years is usually hand-written. res.day, res.month, res.year = ymd elif mstridx == 2: # WTF!? if ymd[1] > 31: # 01-99-Jan res.day, res.year, res.month = ymd else: # 99-01-Jan res.year, res.day, res.month = ymd else: if ymd[0] > 31 or \ (yearfirst and ymd[1] <= 12 and ymd[2] <= 31): # 99-01-01 res.year, res.month, res.day = ymd elif ymd[0] > 12 or (dayfirst and ymd[1] <= 12): # 13-01-01 res.day, res.month, res.year = ymd else: # 01-13-01 res.month, res.day, res.year = ymd except (IndexError, ValueError, AssertionError): return None if not info.validate(res): return None return res DEFAULTPARSER = parser() def parse(timestr, parserinfo = None, **kwargs): # Python 2.x support: datetimes return their string presentation as # bytes in 2.x and unicode in 3.x, so it's reasonable to expect that # the parser will get both kinds. Internally we use unicode only. if isinstance(timestr, binary_type): timestr = timestr.decode() if parserinfo: return parser(parserinfo).parse(timestr, **kwargs) else: return DEFAULTPARSER.parse(timestr, **kwargs) class _tzparser(object): class _result(_resultbase): __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] class _attr(_resultbase): __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] def __repr__(self): return self._repr("") def __init__(self): _resultbase.__init__(self) self.start = self._attr() self.end = self._attr() def parse(self, tzstr): res = self._result() l = _timelex.split(tzstr) try: len_l = len(l) i = 0 while i < len_l: # BRST+3[BRDT[+2]] j = i while j < len_l and not [x for x in l[j] if x in "0123456789:,-+"]: j += 1 if j != i: if not res.stdabbr: offattr = "stdoffset" res.stdabbr = "".join(l[i:j]) else: offattr = "dstoffset" res.dstabbr = "".join(l[i:j]) i = j if (i < len_l and (l[i] in ('+', '-') or l[i][0] in "0123456789")): if l[i] in ('+', '-'): # Yes, that's right. See the TZ variable # documentation. signal = (1, -1)[l[i] == '+'] i += 1 else: signal = -1 len_li = len(l[i]) if len_li == 4: # -0300 setattr(res, offattr, (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) * signal) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 setattr(res, offattr, (int(l[i]) * 3600 + int(l[i + 2]) * 60) * signal) i += 2 elif len_li <= 2: # -[0]3 setattr(res, offattr, int(l[i][:2]) * 3600 * signal) else: return None i += 1 if res.dstabbr: break else: break if i < len_l: for j in range(i, len_l): if l[j] == ';': l[j] = ',' assert l[i] == ',' i += 1 if i >= len_l: pass elif (8 <= l.count(',') <= 9 and not [y for x in l[i:] if x != ',' for y in x if y not in "0123456789"]): # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] for x in (res.start, res.end): x.month = int(l[i]) i += 2 if l[i] == '-': value = int(l[i + 1]) * -1 i += 1 else: value = int(l[i]) i += 2 if value: x.week = value x.weekday = (int(l[i]) - 1) % 7 else: x.day = int(l[i]) i += 2 x.time = int(l[i]) i += 2 if i < len_l: if l[i] in ('-', '+'): signal = (-1, 1)[l[i] == "+"] i += 1 else: signal = 1 res.dstoffset = (res.stdoffset + int(l[i])) * signal elif (l.count(',') == 2 and l[i:].count('/') <= 2 and not [y for x in l[i:] if x not in (',', '/', 'J', 'M', '.', '-', ':') for y in x if y not in "0123456789"]): for x in (res.start, res.end): if l[i] == 'J': # non-leap year day (1 based) i += 1 x.jyday = int(l[i]) elif l[i] == 'M': # month[-.]week[-.]weekday i += 1 x.month = int(l[i]) i += 1 assert l[i] in ('-', '.') i += 1 x.week = int(l[i]) if x.week == 5: x.week = -1 i += 1 assert l[i] in ('-', '.') i += 1 x.weekday = (int(l[i]) - 1) % 7 else: # year day (zero based) x.yday = int(l[i]) + 1 i += 1 if i < len_l and l[i] == '/': i += 1 # start time len_li = len(l[i]) if len_li == 4: # -0300 x.time = (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) elif i + 1 < len_l and l[i + 1] == ':': # -03:00 x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 i += 2 if i + 1 < len_l and l[i + 1] == ':': i += 2 x.time += int(l[i]) elif len_li <= 2: # -[0]3 x.time = (int(l[i][:2]) * 3600) else: return None i += 1 assert i == len_l or l[i] == ',' i += 1 assert i >= len_l except (IndexError, ValueError, AssertionError): return None return res DEFAULTTZPARSER = _tzparser() def _parsetz(tzstr): return DEFAULTTZPARSER.parse(tzstr) def _parsems(value): """Parse a I[.F] seconds value into (seconds, microseconds).""" if "." not in value: return int(value), 0 else: i, f = value.split(".") return int(i), int(f.ljust(6, "0")[:6]) # vim:ts=4:sw=4:et
33,736
Python
.py
814
22.362408
94
0.368211
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,719
tz.py
CouchPotato_CouchPotatoServer/libs/dateutil/tz.py
""" Copyright (c) 2003-2007 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ __license__ = "Simplified BSD" from six import string_types, PY3 import datetime import struct import time import sys import os relativedelta = None parser = None rrule = None __all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz"] try: from dateutil.tzwin import tzwin, tzwinlocal except (ImportError, OSError): tzwin, tzwinlocal = None, None def tzname_in_python2(myfunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ def inner_func(*args, **kwargs): if PY3: return myfunc(*args, **kwargs) else: return myfunc(*args, **kwargs).encode() return inner_func ZERO = datetime.timedelta(0) EPOCHORDINAL = datetime.datetime.utcfromtimestamp(0).toordinal() class tzutc(datetime.tzinfo): def utcoffset(self, dt): return ZERO def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return "UTC" def __eq__(self, other): return (isinstance(other, tzutc) or (isinstance(other, tzoffset) and other._offset == ZERO)) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzoffset(datetime.tzinfo): def __init__(self, name, offset): self._name = name self._offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self._offset def dst(self, dt): return ZERO @tzname_in_python2 def tzname(self, dt): return self._name def __eq__(self, other): return (isinstance(other, tzoffset) and self._offset == other._offset) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s(%s, %s)" % (self.__class__.__name__, repr(self._name), self._offset.days*86400+self._offset.seconds) __reduce__ = object.__reduce__ class tzlocal(datetime.tzinfo): _std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: _dst_offset = datetime.timedelta(seconds=-time.altzone) else: _dst_offset = _std_offset def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): return time.tzname[self._isdst(dt)] def _isdst(self, dt): # We can't use mktime here. It is unstable when deciding if # the hour near to a change is DST or not. # # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, # dt.minute, dt.second, dt.weekday(), 0, -1)) # return time.localtime(timestamp).tm_isdst # # The code above yields the following result: # #>>> import tz, datetime #>>> t = tz.tzlocal() #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRST' #>>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() #'BRDT' #>>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() #'BRDT' # # Here is a more stable implementation: # timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute * 60 + dt.second) return time.localtime(timestamp+time.timezone).tm_isdst def __eq__(self, other): if not isinstance(other, tzlocal): return False return (self._std_offset == other._std_offset and self._dst_offset == other._dst_offset) return True def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s()" % self.__class__.__name__ __reduce__ = object.__reduce__ class _ttinfo(object): __slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt"] def __init__(self): for attr in self.__slots__: setattr(self, attr, None) def __repr__(self): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, repr(value))) return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) def __eq__(self, other): if not isinstance(other, _ttinfo): return False return (self.offset == other.offset and self.delta == other.delta and self.isdst == other.isdst and self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt) def __ne__(self, other): return not self.__eq__(other) def __getstate__(self): state = {} for name in self.__slots__: state[name] = getattr(self, name, None) return state def __setstate__(self, state): for name in self.__slots__: if name in state: setattr(self, name, state[name]) class tzfile(datetime.tzinfo): # http://www.twinsun.com/tz/tz-link.htm # ftp://ftp.iana.org/tz/tz*.tar.gz def __init__(self, fileobj): if isinstance(fileobj, string_types): self._filename = fileobj fileobj = open(fileobj, 'rb') elif hasattr(fileobj, "name"): self._filename = fileobj.name else: self._filename = repr(fileobj) # From tzfile(5): # # The time zone information files used by tzset(3) # begin with the magic characters "TZif" to identify # them as time zone information files, followed by # sixteen bytes reserved for future use, followed by # six four-byte values of type long, written in a # ``standard'' byte order (the high-order byte # of the value is written first). if fileobj.read(4).decode() != "TZif": raise ValueError("magic not found") fileobj.read(16) ( # The number of UTC/local indicators stored in the file. ttisgmtcnt, # The number of standard/wall indicators stored in the file. ttisstdcnt, # The number of leap seconds for which data is # stored in the file. leapcnt, # The number of "transition times" for which data # is stored in the file. timecnt, # The number of "local time types" for which data # is stored in the file (must not be zero). typecnt, # The number of characters of "time zone # abbreviation strings" stored in the file. charcnt, ) = struct.unpack(">6l", fileobj.read(24)) # The above header is followed by tzh_timecnt four-byte # values of type long, sorted in ascending order. # These values are written in ``standard'' byte order. # Each is used as a transition time (as returned by # time(2)) at which the rules for computing local time # change. if timecnt: self._trans_list = struct.unpack(">%dl" % timecnt, fileobj.read(timecnt*4)) else: self._trans_list = [] # Next come tzh_timecnt one-byte values of type unsigned # char; each one tells which of the different types of # ``local time'' types described in the file is associated # with the same-indexed transition time. These values # serve as indices into an array of ttinfo structures that # appears next in the file. if timecnt: self._trans_idx = struct.unpack(">%dB" % timecnt, fileobj.read(timecnt)) else: self._trans_idx = [] # Each ttinfo structure is written as a four-byte value # for tt_gmtoff of type long, in a standard byte # order, followed by a one-byte value for tt_isdst # and a one-byte value for tt_abbrind. In each # structure, tt_gmtoff gives the number of # seconds to be added to UTC, tt_isdst tells whether # tm_isdst should be set by localtime(3), and # tt_abbrind serves as an index into the array of # time zone abbreviation characters that follow the # ttinfo structure(s) in the file. ttinfo = [] for i in range(typecnt): ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) abbr = fileobj.read(charcnt).decode() # Then there are tzh_leapcnt pairs of four-byte # values, written in standard byte order; the # first value of each pair gives the time (as # returned by time(2)) at which a leap second # occurs; the second gives the total number of # leap seconds to be applied after the given time. # The pairs of values are sorted in ascending order # by time. # Not used, for now if leapcnt: leap = struct.unpack(">%dl" % (leapcnt*2), fileobj.read(leapcnt*8)) # Then there are tzh_ttisstdcnt standard/wall # indicators, each stored as a one-byte value; # they tell whether the transition times associated # with local time types were specified as standard # time or wall clock time, and are used when # a time zone file is used in handling POSIX-style # time zone environment variables. if ttisstdcnt: isstd = struct.unpack(">%db" % ttisstdcnt, fileobj.read(ttisstdcnt)) # Finally, there are tzh_ttisgmtcnt UTC/local # indicators, each stored as a one-byte value; # they tell whether the transition times associated # with local time types were specified as UTC or # local time, and are used when a time zone file # is used in handling POSIX-style time zone envi- # ronment variables. if ttisgmtcnt: isgmt = struct.unpack(">%db" % ttisgmtcnt, fileobj.read(ttisgmtcnt)) # ** Everything has been read ** # Build ttinfo list self._ttinfo_list = [] for i in range(typecnt): gmtoff, isdst, abbrind = ttinfo[i] # Round to full-minutes if that's not the case. Python's # datetime doesn't accept sub-minute timezones. Check # http://python.org/sf/1447945 for some information. gmtoff = (gmtoff+30)//60*60 tti = _ttinfo() tti.offset = gmtoff tti.delta = datetime.timedelta(seconds=gmtoff) tti.isdst = isdst tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] tti.isstd = (ttisstdcnt > i and isstd[i] != 0) tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) self._ttinfo_list.append(tti) # Replace ttinfo indexes for ttinfo objects. trans_idx = [] for idx in self._trans_idx: trans_idx.append(self._ttinfo_list[idx]) self._trans_idx = tuple(trans_idx) # Set standard, dst, and before ttinfos. before will be # used when a given time is before any transitions, # and will be set to the first non-dst ttinfo, or to # the first dst, if all of them are dst. self._ttinfo_std = None self._ttinfo_dst = None self._ttinfo_before = None if self._ttinfo_list: if not self._trans_list: self._ttinfo_std = self._ttinfo_first = self._ttinfo_list[0] else: for i in range(timecnt-1, -1, -1): tti = self._trans_idx[i] if not self._ttinfo_std and not tti.isdst: self._ttinfo_std = tti elif not self._ttinfo_dst and tti.isdst: self._ttinfo_dst = tti if self._ttinfo_std and self._ttinfo_dst: break else: if self._ttinfo_dst and not self._ttinfo_std: self._ttinfo_std = self._ttinfo_dst for tti in self._ttinfo_list: if not tti.isdst: self._ttinfo_before = tti break else: self._ttinfo_before = self._ttinfo_list[0] # Now fix transition times to become relative to wall time. # # I'm not sure about this. In my tests, the tz source file # is setup to wall time, and in the binary file isstd and # isgmt are off, so it should be in wall time. OTOH, it's # always in gmt time. Let me know if you have comments # about this. laststdoffset = 0 self._trans_list = list(self._trans_list) for i in range(len(self._trans_list)): tti = self._trans_idx[i] if not tti.isdst: # This is std time. self._trans_list[i] += tti.offset laststdoffset = tti.offset else: # This is dst time. Convert to std. self._trans_list[i] += laststdoffset self._trans_list = tuple(self._trans_list) def _find_ttinfo(self, dt, laststd=0): timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400 + dt.hour * 3600 + dt.minute * 60 + dt.second) idx = 0 for trans in self._trans_list: if timestamp < trans: break idx += 1 else: return self._ttinfo_std if idx == 0: return self._ttinfo_before if laststd: while idx > 0: tti = self._trans_idx[idx-1] if not tti.isdst: return tti idx -= 1 else: return self._ttinfo_std else: return self._trans_idx[idx-1] def utcoffset(self, dt): if not self._ttinfo_std: return ZERO return self._find_ttinfo(dt).delta def dst(self, dt): if not self._ttinfo_dst: return ZERO tti = self._find_ttinfo(dt) if not tti.isdst: return ZERO # The documentation says that utcoffset()-dst() must # be constant for every dt. return tti.delta-self._find_ttinfo(dt, laststd=1).delta # An alternative for that would be: # # return self._ttinfo_dst.offset-self._ttinfo_std.offset # # However, this class stores historical changes in the # dst offset, so I belive that this wouldn't be the right # way to implement this. @tzname_in_python2 def tzname(self, dt): if not self._ttinfo_std: return None return self._find_ttinfo(dt).abbr def __eq__(self, other): if not isinstance(other, tzfile): return False return (self._trans_list == other._trans_list and self._trans_idx == other._trans_idx and self._ttinfo_list == other._ttinfo_list) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) def __reduce__(self): if not os.path.isfile(self._filename): raise ValueError("Unpickable %s class" % self.__class__.__name__) return (self.__class__, (self._filename,)) class tzrange(datetime.tzinfo): def __init__(self, stdabbr, stdoffset=None, dstabbr=None, dstoffset=None, start=None, end=None): global relativedelta if not relativedelta: from dateutil import relativedelta self._std_abbr = stdabbr self._dst_abbr = dstabbr if stdoffset is not None: self._std_offset = datetime.timedelta(seconds=stdoffset) else: self._std_offset = ZERO if dstoffset is not None: self._dst_offset = datetime.timedelta(seconds=dstoffset) elif dstabbr and stdoffset is not None: self._dst_offset = self._std_offset+datetime.timedelta(hours=+1) else: self._dst_offset = ZERO if dstabbr and start is None: self._start_delta = relativedelta.relativedelta( hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) else: self._start_delta = start if dstabbr and end is None: self._end_delta = relativedelta.relativedelta( hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) else: self._end_delta = end def utcoffset(self, dt): if self._isdst(dt): return self._dst_offset else: return self._std_offset def dst(self, dt): if self._isdst(dt): return self._dst_offset-self._std_offset else: return ZERO @tzname_in_python2 def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr def _isdst(self, dt): if not self._start_delta: return False year = datetime.datetime(dt.year, 1, 1) start = year+self._start_delta end = year+self._end_delta dt = dt.replace(tzinfo=None) if start < end: return dt >= start and dt < end else: return dt >= start or dt < end def __eq__(self, other): if not isinstance(other, tzrange): return False return (self._std_abbr == other._std_abbr and self._dst_abbr == other._dst_abbr and self._std_offset == other._std_offset and self._dst_offset == other._dst_offset and self._start_delta == other._start_delta and self._end_delta == other._end_delta) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "%s(...)" % self.__class__.__name__ __reduce__ = object.__reduce__ class tzstr(tzrange): def __init__(self, s): global parser if not parser: from dateutil import parser self._s = s res = parser._parsetz(s) if res is None: raise ValueError("unknown string format") # Here we break the compatibility with the TZ variable handling. # GMT-3 actually *means* the timezone -3. if res.stdabbr in ("GMT", "UTC"): res.stdoffset *= -1 # We must initialize it first, since _delta() needs # _std_offset and _dst_offset set. Use False in start/end # to avoid building it two times. tzrange.__init__(self, res.stdabbr, res.stdoffset, res.dstabbr, res.dstoffset, start=False, end=False) if not res.dstabbr: self._start_delta = None self._end_delta = None else: self._start_delta = self._delta(res.start) if self._start_delta: self._end_delta = self._delta(res.end, isend=1) def _delta(self, x, isend=0): kwargs = {} if x.month is not None: kwargs["month"] = x.month if x.weekday is not None: kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) if x.week > 0: kwargs["day"] = 1 else: kwargs["day"] = 31 elif x.day: kwargs["day"] = x.day elif x.yday is not None: kwargs["yearday"] = x.yday elif x.jyday is not None: kwargs["nlyearday"] = x.jyday if not kwargs: # Default is to start on first sunday of april, and end # on last sunday of october. if not isend: kwargs["month"] = 4 kwargs["day"] = 1 kwargs["weekday"] = relativedelta.SU(+1) else: kwargs["month"] = 10 kwargs["day"] = 31 kwargs["weekday"] = relativedelta.SU(-1) if x.time is not None: kwargs["seconds"] = x.time else: # Default is 2AM. kwargs["seconds"] = 7200 if isend: # Convert to standard time, to follow the documented way # of working with the extra hour. See the documentation # of the tzinfo class. delta = self._dst_offset-self._std_offset kwargs["seconds"] -= delta.seconds+delta.days*86400 return relativedelta.relativedelta(**kwargs) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._s)) class _tzicalvtzcomp(object): def __init__(self, tzoffsetfrom, tzoffsetto, isdst, tzname=None, rrule=None): self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom self.isdst = isdst self.tzname = tzname self.rrule = rrule class _tzicalvtz(datetime.tzinfo): def __init__(self, tzid, comps=[]): self._tzid = tzid self._comps = comps self._cachedate = [] self._cachecomp = [] def _find_comp(self, dt): if len(self._comps) == 1: return self._comps[0] dt = dt.replace(tzinfo=None) try: return self._cachecomp[self._cachedate.index(dt)] except ValueError: pass lastcomp = None lastcompdt = None for comp in self._comps: if not comp.isdst: # Handle the extra hour in DST -> STD compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True) else: compdt = comp.rrule.before(dt, inc=True) if compdt and (not lastcompdt or lastcompdt < compdt): lastcompdt = compdt lastcomp = comp if not lastcomp: # RFC says nothing about what to do when a given # time is before the first onset date. We'll look for the # first standard component, or the first component, if # none is found. for comp in self._comps: if not comp.isdst: lastcomp = comp break else: lastcomp = comp[0] self._cachedate.insert(0, dt) self._cachecomp.insert(0, lastcomp) if len(self._cachedate) > 10: self._cachedate.pop() self._cachecomp.pop() return lastcomp def utcoffset(self, dt): return self._find_comp(dt).tzoffsetto def dst(self, dt): comp = self._find_comp(dt) if comp.isdst: return comp.tzoffsetdiff else: return ZERO @tzname_in_python2 def tzname(self, dt): return self._find_comp(dt).tzname def __repr__(self): return "<tzicalvtz %s>" % repr(self._tzid) __reduce__ = object.__reduce__ class tzical(object): def __init__(self, fileobj): global rrule if not rrule: from dateutil import rrule if isinstance(fileobj, string_types): self._s = fileobj fileobj = open(fileobj, 'r') # ical should be encoded in UTF-8 with CRLF elif hasattr(fileobj, "name"): self._s = fileobj.name else: self._s = repr(fileobj) self._vtz = {} self._parse_rfc(fileobj.read()) def keys(self): return list(self._vtz.keys()) def get(self, tzid=None): if tzid is None: keys = list(self._vtz.keys()) if len(keys) == 0: raise ValueError("no timezones defined") elif len(keys) > 1: raise ValueError("more than one timezone available") tzid = keys[0] return self._vtz.get(tzid) def _parse_offset(self, s): s = s.strip() if not s: raise ValueError("empty offset") if s[0] in ('+', '-'): signal = (-1, +1)[s[0]=='+'] s = s[1:] else: signal = +1 if len(s) == 4: return (int(s[:2])*3600+int(s[2:])*60)*signal elif len(s) == 6: return (int(s[:2])*3600+int(s[2:4])*60+int(s[4:]))*signal else: raise ValueError("invalid offset: "+s) def _parse_rfc(self, s): lines = s.splitlines() if not lines: raise ValueError("empty string") # Unfold i = 0 while i < len(lines): line = lines[i].rstrip() if not line: del lines[i] elif i > 0 and line[0] == " ": lines[i-1] += line[1:] del lines[i] else: i += 1 tzid = None comps = [] invtz = False comptype = None for line in lines: if not line: continue name, value = line.split(':', 1) parms = name.split(';') if not parms: raise ValueError("empty property name") name = parms[0].upper() parms = parms[1:] if invtz: if name == "BEGIN": if value in ("STANDARD", "DAYLIGHT"): # Process component pass else: raise ValueError("unknown component: "+value) comptype = value founddtstart = False tzoffsetfrom = None tzoffsetto = None rrulelines = [] tzname = None elif name == "END": if value == "VTIMEZONE": if comptype: raise ValueError("component not closed: "+comptype) if not tzid: raise ValueError("mandatory TZID not found") if not comps: raise ValueError("at least one component is needed") # Process vtimezone self._vtz[tzid] = _tzicalvtz(tzid, comps) invtz = False elif value == comptype: if not founddtstart: raise ValueError("mandatory DTSTART not found") if tzoffsetfrom is None: raise ValueError("mandatory TZOFFSETFROM not found") if tzoffsetto is None: raise ValueError("mandatory TZOFFSETFROM not found") # Process component rr = None if rrulelines: rr = rrule.rrulestr("\n".join(rrulelines), compatible=True, ignoretz=True, cache=True) comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, (comptype == "DAYLIGHT"), tzname, rr) comps.append(comp) comptype = None else: raise ValueError("invalid component end: "+value) elif comptype: if name == "DTSTART": rrulelines.append(line) founddtstart = True elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): rrulelines.append(line) elif name == "TZOFFSETFROM": if parms: raise ValueError("unsupported %s parm: %s "%(name, parms[0])) tzoffsetfrom = self._parse_offset(value) elif name == "TZOFFSETTO": if parms: raise ValueError("unsupported TZOFFSETTO parm: "+parms[0]) tzoffsetto = self._parse_offset(value) elif name == "TZNAME": if parms: raise ValueError("unsupported TZNAME parm: "+parms[0]) tzname = value elif name == "COMMENT": pass else: raise ValueError("unsupported property: "+name) else: if name == "TZID": if parms: raise ValueError("unsupported TZID parm: "+parms[0]) tzid = value elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): pass else: raise ValueError("unsupported property: "+name) elif name == "BEGIN" and value == "VTIMEZONE": tzid = None comps = [] invtz = True def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self._s)) if sys.platform != "win32": TZFILES = ["/etc/localtime", "localtime"] TZPATHS = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"] else: TZFILES = [] TZPATHS = [] def gettz(name=None): tz = None if not name: try: name = os.environ["TZ"] except KeyError: pass if name is None or name == ":": for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for path in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = tzlocal() else: if name.startswith(":"): name = name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz = None else: for path in TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = None if tzwin: try: tz = tzwin(name) except OSError: pass if not tz: from dateutil.zoneinfo import gettz tz = gettz(name) if not tz: for c in name: # name must have at least one offset to be a tzstr if c in "0123456789": try: tz = tzstr(name) except ValueError: pass break else: if name in ("GMT", "UTC"): tz = tzutc() elif name in time.tzname: tz = tzlocal() return tz # vim:ts=4:sw=4:et
32,988
Python
.py
833
26.872749
89
0.516259
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,720
__init__.py
CouchPotato_CouchPotatoServer/libs/dateutil/zoneinfo/__init__.py
# -*- coding: utf-8 -*- """ Copyright (c) 2003-2005 Gustavo Niemeyer <gustavo@niemeyer.net> This module offers extensions to the standard Python datetime module. """ from dateutil.tz import tzfile from tarfile import TarFile import os __author__ = "Tomi Pievil√§inen <tomi.pievilainen@iki.fi>" __license__ = "Simplified BSD" __all__ = ["setcachesize", "gettz", "rebuild"] CACHE = [] CACHESIZE = 10 class tzfile(tzfile): def __reduce__(self): return (gettz, (self._filename,)) def getzoneinfofile(): filenames = sorted(os.listdir(os.path.join(os.path.dirname(__file__)))) filenames.reverse() for entry in filenames: if entry.startswith("zoneinfo") and ".tar." in entry: return os.path.join(os.path.dirname(__file__), entry) return None ZONEINFOFILE = getzoneinfofile() del getzoneinfofile def setcachesize(size): global CACHESIZE, CACHE CACHESIZE = size del CACHE[size:] def gettz(name): tzinfo = None if ZONEINFOFILE: for cachedname, tzinfo in CACHE: if cachedname == name: break else: tf = TarFile.open(ZONEINFOFILE) try: zonefile = tf.extractfile(name) except KeyError: tzinfo = None else: tzinfo = tzfile(zonefile) tf.close() CACHE.insert(0, (name, tzinfo)) del CACHE[CACHESIZE:] return tzinfo def rebuild(filename, tag=None, format="gz"): import tempfile, shutil tmpdir = tempfile.mkdtemp() zonedir = os.path.join(tmpdir, "zoneinfo") moduledir = os.path.dirname(__file__) if tag: tag = "-"+tag targetname = "zoneinfo%s.tar.%s" % (tag, format) try: tf = TarFile.open(filename) # The "backwards" zone file contains links to other files, so must be # processed as last for name in sorted(tf.getnames(), key=lambda k: k != "backward" and k or "z"): if not (name.endswith(".sh") or name.endswith(".tab") or name == "leapseconds"): tf.extract(name, tmpdir) filepath = os.path.join(tmpdir, name) os.system("zic -d %s %s" % (zonedir, filepath)) tf.close() target = os.path.join(moduledir, targetname) for entry in os.listdir(moduledir): if entry.startswith("zoneinfo") and ".tar." in entry: os.unlink(os.path.join(moduledir, entry)) tf = TarFile.open(target, "w:%s" % format) for entry in os.listdir(zonedir): entrypath = os.path.join(zonedir, entry) tf.add(entrypath, entry) tf.close() finally: shutil.rmtree(tmpdir)
2,773
Python
.py
79
27.037975
77
0.596347
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,721
shim.py
CouchPotato_CouchPotatoServer/libs/gntp/shim.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE """ Python2.5 and Python3.3 compatibility shim Heavily inspirted by the "six" library. https://pypi.python.org/pypi/six """ import sys PY3 = sys.version_info[0] == 3 if PY3: def b(s): if isinstance(s, bytes): return s return s.encode('utf8', 'replace') def u(s): if isinstance(s, bytes): return s.decode('utf8', 'replace') return s from io import BytesIO as StringIO from configparser import RawConfigParser else: def b(s): if isinstance(s, unicode): return s.encode('utf8', 'replace') return s def u(s): if isinstance(s, unicode): return s if isinstance(s, int): s = str(s) return unicode(s, "utf8", "replace") from StringIO import StringIO from ConfigParser import RawConfigParser b.__doc__ = "Ensure we have a byte string" u.__doc__ = "Ensure we have a unicode string"
931
Python
.py
35
24.142857
76
0.724605
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,722
errors.py
CouchPotato_CouchPotatoServer/libs/gntp/errors.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE class BaseError(Exception): pass class ParseError(BaseError): errorcode = 500 errordesc = 'Error parsing the message' class AuthError(BaseError): errorcode = 400 errordesc = 'Error with authorization' class UnsupportedError(BaseError): errorcode = 500 errordesc = 'Currently unsupported by gntp.py' class NetworkError(BaseError): errorcode = 500 errordesc = "Error connecting to growl server"
519
Python
.py
16
30.3125
76
0.807692
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,723
config.py
CouchPotato_CouchPotatoServer/libs/gntp/config.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE """ The gntp.config module is provided as an extended GrowlNotifier object that takes advantage of the ConfigParser module to allow us to setup some default values (such as hostname, password, and port) in a more global way to be shared among programs using gntp """ import logging import os import gntp.notifier import gntp.shim __all__ = [ 'mini', 'GrowlNotifier' ] logger = logging.getLogger(__name__) class GrowlNotifier(gntp.notifier.GrowlNotifier): """ ConfigParser enhanced GrowlNotifier object For right now, we are only interested in letting users overide certain values from ~/.gntp :: [gntp] hostname = ? password = ? port = ? """ def __init__(self, *args, **kwargs): config = gntp.shim.RawConfigParser({ 'hostname': kwargs.get('hostname', 'localhost'), 'password': kwargs.get('password'), 'port': kwargs.get('port', 23053), }) config.read([os.path.expanduser('~/.gntp')]) # If the file does not exist, then there will be no gntp section defined # and the config.get() lines below will get confused. Since we are not # saving the config, it should be safe to just add it here so the # code below doesn't complain if not config.has_section('gntp'): logger.info('Error reading ~/.gntp config file') config.add_section('gntp') kwargs['password'] = config.get('gntp', 'password') kwargs['hostname'] = config.get('gntp', 'hostname') kwargs['port'] = config.getint('gntp', 'port') super(GrowlNotifier, self).__init__(*args, **kwargs) def mini(description, **kwargs): """Single notification function Simple notification function in one line. Has only one required parameter and attempts to use reasonable defaults for everything else :param string description: Notification message """ kwargs['notifierFactory'] = GrowlNotifier gntp.notifier.mini(description, **kwargs) if __name__ == '__main__': # If we're running this module directly we're likely running it as a test # so extra debugging is useful logging.basicConfig(level=logging.INFO) mini('Testing mini notification')
2,173
Python
.py
59
34.389831
81
0.741889
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,724
cli.py
CouchPotato_CouchPotatoServer/libs/gntp/cli.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE import logging import os import sys from optparse import OptionParser, OptionGroup from gntp.notifier import GrowlNotifier from gntp.shim import RawConfigParser from gntp.version import __version__ DEFAULT_CONFIG = os.path.expanduser('~/.gntp') config = RawConfigParser({ 'hostname': 'localhost', 'password': None, 'port': 23053, }) config.read([DEFAULT_CONFIG]) if not config.has_section('gntp'): config.add_section('gntp') class ClientParser(OptionParser): def __init__(self): OptionParser.__init__(self, version="%%prog %s" % __version__) group = OptionGroup(self, "Network Options") group.add_option("-H", "--host", dest="host", default=config.get('gntp', 'hostname'), help="Specify a hostname to which to send a remote notification. [%default]") group.add_option("--port", dest="port", default=config.getint('gntp', 'port'), type="int", help="port to listen on [%default]") group.add_option("-P", "--password", dest='password', default=config.get('gntp', 'password'), help="Network password") self.add_option_group(group) group = OptionGroup(self, "Notification Options") group.add_option("-n", "--name", dest="app", default='Python GNTP Test Client', help="Set the name of the application [%default]") group.add_option("-s", "--sticky", dest='sticky', default=False, action="store_true", help="Make the notification sticky [%default]") group.add_option("--image", dest="icon", default=None, help="Icon for notification (URL or /path/to/file)") group.add_option("-m", "--message", dest="message", default=None, help="Sets the message instead of using stdin") group.add_option("-p", "--priority", dest="priority", default=0, type="int", help="-2 to 2 [%default]") group.add_option("-d", "--identifier", dest="identifier", help="Identifier for coalescing") group.add_option("-t", "--title", dest="title", default=None, help="Set the title of the notification [%default]") group.add_option("-N", "--notification", dest="name", default='Notification', help="Set the notification name [%default]") group.add_option("--callback", dest="callback", help="URL callback") self.add_option_group(group) # Extra Options self.add_option('-v', '--verbose', dest='verbose', default=0, action='count', help="Verbosity levels") def parse_args(self, args=None, values=None): values, args = OptionParser.parse_args(self, args, values) if values.message is None: print('Enter a message followed by Ctrl-D') try: message = sys.stdin.read() except KeyboardInterrupt: exit() else: message = values.message if values.title is None: values.title = ' '.join(args) # If we still have an empty title, use the # first bit of the message as the title if values.title == '': values.title = message[:20] values.verbose = logging.WARNING - values.verbose * 10 return values, message def main(): (options, message) = ClientParser().parse_args() logging.basicConfig(level=options.verbose) if not os.path.exists(DEFAULT_CONFIG): logging.info('No config read found at %s', DEFAULT_CONFIG) growl = GrowlNotifier( applicationName=options.app, notifications=[options.name], defaultNotifications=[options.name], hostname=options.host, password=options.password, port=options.port, ) result = growl.register() if result is not True: exit(result) # This would likely be better placed within the growl notifier # class but until I make _checkIcon smarter this is "easier" if options.icon is not None and not options.icon.startswith('http'): logging.info('Loading image %s', options.icon) f = open(options.icon) options.icon = f.read() f.close() result = growl.notify( noteType=options.name, title=options.title, description=message, icon=options.icon, sticky=options.sticky, priority=options.priority, callback=options.callback, identifier=options.identifier, ) if result is not True: exit(result) if __name__ == "__main__": main()
4,143
Python
.py
120
31.5
80
0.713393
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,725
notifier.py
CouchPotato_CouchPotatoServer/libs/gntp/notifier.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE """ The gntp.notifier module is provided as a simple way to send notifications using GNTP .. note:: This class is intended to mostly mirror the older Python bindings such that you should be able to replace instances of the old bindings with this class. `Original Python bindings <http://code.google.com/p/growl/source/browse/Bindings/python/Growl.py>`_ """ import logging import platform import socket import sys from gntp.version import __version__ import gntp.core import gntp.errors as errors import gntp.shim __all__ = [ 'mini', 'GrowlNotifier', ] logger = logging.getLogger(__name__) class GrowlNotifier(object): """Helper class to simplfy sending Growl messages :param string applicationName: Sending application name :param list notification: List of valid notifications :param list defaultNotifications: List of notifications that should be enabled by default :param string applicationIcon: Icon URL :param string hostname: Remote host :param integer port: Remote port """ passwordHash = 'MD5' socketTimeout = 3 def __init__(self, applicationName='Python GNTP', notifications=[], defaultNotifications=None, applicationIcon=None, hostname='localhost', password=None, port=23053): self.applicationName = applicationName self.notifications = list(notifications) if defaultNotifications: self.defaultNotifications = list(defaultNotifications) else: self.defaultNotifications = self.notifications self.applicationIcon = applicationIcon self.password = password self.hostname = hostname self.port = int(port) def _checkIcon(self, data): ''' Check the icon to see if it's valid If it's a simple URL icon, then we return True. If it's a data icon then we return False ''' logger.info('Checking icon') return gntp.shim.u(data).startswith('http') def register(self): """Send GNTP Registration .. warning:: Before sending notifications to Growl, you need to have sent a registration message at least once """ logger.info('Sending registration to %s:%s', self.hostname, self.port) register = gntp.core.GNTPRegister() register.add_header('Application-Name', self.applicationName) for notification in self.notifications: enabled = notification in self.defaultNotifications register.add_notification(notification, enabled) if self.applicationIcon: if self._checkIcon(self.applicationIcon): register.add_header('Application-Icon', self.applicationIcon) else: resource = register.add_resource(self.applicationIcon) register.add_header('Application-Icon', resource) if self.password: register.set_password(self.password, self.passwordHash) self.add_origin_info(register) self.register_hook(register) return self._send('register', register) def notify(self, noteType, title, description, icon=None, sticky=False, priority=None, callback=None, identifier=None, custom={}): """Send a GNTP notifications .. warning:: Must have registered with growl beforehand or messages will be ignored :param string noteType: One of the notification names registered earlier :param string title: Notification title (usually displayed on the notification) :param string description: The main content of the notification :param string icon: Icon URL path :param boolean sticky: Sticky notification :param integer priority: Message priority level from -2 to 2 :param string callback: URL callback :param dict custom: Custom attributes. Key names should be prefixed with X- according to the spec but this is not enforced by this class .. warning:: For now, only URL callbacks are supported. In the future, the callback argument will also support a function """ logger.info('Sending notification [%s] to %s:%s', noteType, self.hostname, self.port) assert noteType in self.notifications notice = gntp.core.GNTPNotice() notice.add_header('Application-Name', self.applicationName) notice.add_header('Notification-Name', noteType) notice.add_header('Notification-Title', title) if self.password: notice.set_password(self.password, self.passwordHash) if sticky: notice.add_header('Notification-Sticky', sticky) if priority: notice.add_header('Notification-Priority', priority) if icon: if self._checkIcon(icon): notice.add_header('Notification-Icon', icon) else: resource = notice.add_resource(icon) notice.add_header('Notification-Icon', resource) if description: notice.add_header('Notification-Text', description) if callback: notice.add_header('Notification-Callback-Target', callback) if identifier: notice.add_header('Notification-Coalescing-ID', identifier) for key in custom: notice.add_header(key, custom[key]) self.add_origin_info(notice) self.notify_hook(notice) return self._send('notify', notice) def subscribe(self, id, name, port): """Send a Subscribe request to a remote machine""" sub = gntp.core.GNTPSubscribe() sub.add_header('Subscriber-ID', id) sub.add_header('Subscriber-Name', name) sub.add_header('Subscriber-Port', port) if self.password: sub.set_password(self.password, self.passwordHash) self.add_origin_info(sub) self.subscribe_hook(sub) return self._send('subscribe', sub) def add_origin_info(self, packet): """Add optional Origin headers to message""" packet.add_header('Origin-Machine-Name', platform.node()) packet.add_header('Origin-Software-Name', 'gntp.py') packet.add_header('Origin-Software-Version', __version__) packet.add_header('Origin-Platform-Name', platform.system()) packet.add_header('Origin-Platform-Version', platform.platform()) def register_hook(self, packet): pass def notify_hook(self, packet): pass def subscribe_hook(self, packet): pass def _send(self, messagetype, packet): """Send the GNTP Packet""" packet.validate() data = packet.encode() logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(self.socketTimeout) try: s.connect((self.hostname, self.port)) s.send(data) recv_data = s.recv(1024) while not recv_data.endswith(gntp.shim.b("\r\n\r\n")): recv_data += s.recv(1024) except socket.error: # Python2.5 and Python3 compatibile exception exc = sys.exc_info()[1] raise errors.NetworkError(exc) response = gntp.core.parse_gntp(recv_data) s.close() logger.debug('From : %s:%s <%s>\n%s', self.hostname, self.port, response.__class__, response) if type(response) == gntp.core.GNTPOK: return True logger.error('Invalid response: %s', response.error()) return response.error() def mini(description, applicationName='PythonMini', noteType="Message", title="Mini Message", applicationIcon=None, hostname='localhost', password=None, port=23053, sticky=False, priority=None, callback=None, notificationIcon=None, identifier=None, notifierFactory=GrowlNotifier): """Single notification function Simple notification function in one line. Has only one required parameter and attempts to use reasonable defaults for everything else :param string description: Notification message .. warning:: For now, only URL callbacks are supported. In the future, the callback argument will also support a function """ try: growl = notifierFactory( applicationName=applicationName, notifications=[noteType], defaultNotifications=[noteType], applicationIcon=applicationIcon, hostname=hostname, password=password, port=port, ) result = growl.register() if result is not True: return result return growl.notify( noteType=noteType, title=title, description=description, icon=notificationIcon, sticky=sticky, priority=priority, callback=callback, identifier=identifier, ) except Exception: # We want the "mini" function to be simple and swallow Exceptions # in order to be less invasive logger.exception("Growl error") if __name__ == '__main__': # If we're running this module directly we're likely running it as a test # so extra debugging is useful logging.basicConfig(level=logging.INFO) mini('Testing mini notification')
8,299
Python
.py
220
34.563636
100
0.759895
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,726
core.py
CouchPotato_CouchPotatoServer/libs/gntp/core.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE import hashlib import re import time import gntp.shim import gntp.errors as errors __all__ = [ 'GNTPRegister', 'GNTPNotice', 'GNTPSubscribe', 'GNTPOK', 'GNTPError', 'parse_gntp', ] #GNTP/<version> <messagetype> <encryptionAlgorithmID>[:<ivValue>][ <keyHashAlgorithmID>:<keyHash>.<salt>] GNTP_INFO_LINE = re.compile( 'GNTP/(?P<version>\d+\.\d+) (?P<messagetype>REGISTER|NOTIFY|SUBSCRIBE|\-OK|\-ERROR)' + ' (?P<encryptionAlgorithmID>[A-Z0-9]+(:(?P<ivValue>[A-F0-9]+))?) ?' + '((?P<keyHashAlgorithmID>[A-Z0-9]+):(?P<keyHash>[A-F0-9]+).(?P<salt>[A-F0-9]+))?\r\n', re.IGNORECASE ) GNTP_INFO_LINE_SHORT = re.compile( 'GNTP/(?P<version>\d+\.\d+) (?P<messagetype>REGISTER|NOTIFY|SUBSCRIBE|\-OK|\-ERROR)', re.IGNORECASE ) GNTP_HEADER = re.compile('([\w-]+):(.+)') GNTP_EOL = gntp.shim.b('\r\n') GNTP_SEP = gntp.shim.b(': ') class _GNTPBuffer(gntp.shim.StringIO): """GNTP Buffer class""" def writeln(self, value=None): if value: self.write(gntp.shim.b(value)) self.write(GNTP_EOL) def writeheader(self, key, value): if not isinstance(value, str): value = str(value) self.write(gntp.shim.b(key)) self.write(GNTP_SEP) self.write(gntp.shim.b(value)) self.write(GNTP_EOL) class _GNTPBase(object): """Base initilization :param string messagetype: GNTP Message type :param string version: GNTP Protocol version :param string encription: Encryption protocol """ def __init__(self, messagetype=None, version='1.0', encryption=None): self.info = { 'version': version, 'messagetype': messagetype, 'encryptionAlgorithmID': encryption } self.hash_algo = { 'MD5': hashlib.md5, 'SHA1': hashlib.sha1, 'SHA256': hashlib.sha256, 'SHA512': hashlib.sha512, } self.headers = {} self.resources = {} def __str__(self): return self.encode() def _parse_info(self, data): """Parse the first line of a GNTP message to get security and other info values :param string data: GNTP Message :return dict: Parsed GNTP Info line """ match = GNTP_INFO_LINE.match(data) if not match: raise errors.ParseError('ERROR_PARSING_INFO_LINE') info = match.groupdict() if info['encryptionAlgorithmID'] == 'NONE': info['encryptionAlgorithmID'] = None return info def set_password(self, password, encryptAlgo='MD5'): """Set a password for a GNTP Message :param string password: Null to clear password :param string encryptAlgo: Supports MD5, SHA1, SHA256, SHA512 """ if not password: self.info['encryptionAlgorithmID'] = None self.info['keyHashAlgorithm'] = None return self.password = gntp.shim.b(password) self.encryptAlgo = encryptAlgo.upper() if not self.encryptAlgo in self.hash_algo: raise errors.UnsupportedError('INVALID HASH "%s"' % self.encryptAlgo) hashfunction = self.hash_algo.get(self.encryptAlgo) password = password.encode('utf8') seed = time.ctime().encode('utf8') salt = hashfunction(seed).hexdigest() saltHash = hashfunction(seed).digest() keyBasis = password + saltHash key = hashfunction(keyBasis).digest() keyHash = hashfunction(key).hexdigest() self.info['keyHashAlgorithmID'] = self.encryptAlgo self.info['keyHash'] = keyHash.upper() self.info['salt'] = salt.upper() def _decode_hex(self, value): """Helper function to decode hex string to `proper` hex string :param string value: Human readable hex string :return string: Hex string """ result = '' for i in range(0, len(value), 2): tmp = int(value[i:i + 2], 16) result += chr(tmp) return result def _decode_binary(self, rawIdentifier, identifier): rawIdentifier += '\r\n\r\n' dataLength = int(identifier['Length']) pointerStart = self.raw.find(rawIdentifier) + len(rawIdentifier) pointerEnd = pointerStart + dataLength data = self.raw[pointerStart:pointerEnd] if not len(data) == dataLength: raise errors.ParseError('INVALID_DATA_LENGTH Expected: %s Recieved %s' % (dataLength, len(data))) return data def _validate_password(self, password): """Validate GNTP Message against stored password""" self.password = password if password is None: raise errors.AuthError('Missing password') keyHash = self.info.get('keyHash', None) if keyHash is None and self.password is None: return True if keyHash is None: raise errors.AuthError('Invalid keyHash') if self.password is None: raise errors.AuthError('Missing password') keyHashAlgorithmID = self.info.get('keyHashAlgorithmID','MD5') password = self.password.encode('utf8') saltHash = self._decode_hex(self.info['salt']) keyBasis = password + saltHash self.key = self.hash_algo[keyHashAlgorithmID](keyBasis).digest() keyHash = self.hash_algo[keyHashAlgorithmID](self.key).hexdigest() if not keyHash.upper() == self.info['keyHash'].upper(): raise errors.AuthError('Invalid Hash') return True def validate(self): """Verify required headers""" for header in self._requiredHeaders: if not self.headers.get(header, False): raise errors.ParseError('Missing Notification Header: ' + header) def _format_info(self): """Generate info line for GNTP Message :return string: """ info = 'GNTP/%s %s' % ( self.info.get('version'), self.info.get('messagetype'), ) if self.info.get('encryptionAlgorithmID', None): info += ' %s:%s' % ( self.info.get('encryptionAlgorithmID'), self.info.get('ivValue'), ) else: info += ' NONE' if self.info.get('keyHashAlgorithmID', None): info += ' %s:%s.%s' % ( self.info.get('keyHashAlgorithmID'), self.info.get('keyHash'), self.info.get('salt') ) return info def _parse_dict(self, data): """Helper function to parse blocks of GNTP headers into a dictionary :param string data: :return dict: Dictionary of parsed GNTP Headers """ d = {} for line in data.split('\r\n'): match = GNTP_HEADER.match(line) if not match: continue key = match.group(1).strip() val = match.group(2).strip() d[key] = val return d def add_header(self, key, value): self.headers[key] = value def add_resource(self, data): """Add binary resource :param string data: Binary Data """ data = gntp.shim.b(data) identifier = hashlib.md5(data).hexdigest() self.resources[identifier] = data return 'x-growl-resource://%s' % identifier def decode(self, data, password=None): """Decode GNTP Message :param string data: """ self.password = password self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self.headers = self._parse_dict(parts[0]) def encode(self): """Encode a generic GNTP Message :return string: GNTP Message ready to be sent. Returned as a byte string """ buff = _GNTPBuffer() buff.writeln(self._format_info()) #Headers for k, v in self.headers.items(): buff.writeheader(k, v) buff.writeln() #Resources for resource, data in self.resources.items(): buff.writeheader('Identifier', resource) buff.writeheader('Length', len(data)) buff.writeln() buff.write(data) buff.writeln() buff.writeln() return buff.getvalue() class GNTPRegister(_GNTPBase): """Represents a GNTP Registration Command :param string data: (Optional) See decode() :param string password: (Optional) Password to use while encoding/decoding messages """ _requiredHeaders = [ 'Application-Name', 'Notifications-Count' ] _requiredNotificationHeaders = ['Notification-Name'] def __init__(self, data=None, password=None): _GNTPBase.__init__(self, 'REGISTER') self.notifications = [] if data: self.decode(data, password) else: self.set_password(password) self.add_header('Application-Name', 'pygntp') self.add_header('Notifications-Count', 0) def validate(self): '''Validate required headers and validate notification headers''' for header in self._requiredHeaders: if not self.headers.get(header, False): raise errors.ParseError('Missing Registration Header: ' + header) for notice in self.notifications: for header in self._requiredNotificationHeaders: if not notice.get(header, False): raise errors.ParseError('Missing Notification Header: ' + header) def decode(self, data, password): """Decode existing GNTP Registration message :param string data: Message to decode """ self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) for i, part in enumerate(parts): if i == 0: continue # Skip Header if part.strip() == '': continue notice = self._parse_dict(part) if notice.get('Notification-Name', False): self.notifications.append(notice) elif notice.get('Identifier', False): notice['Data'] = self._decode_binary(part, notice) #open('register.png','wblol').write(notice['Data']) self.resources[notice.get('Identifier')] = notice def add_notification(self, name, enabled=True): """Add new Notification to Registration message :param string name: Notification Name :param boolean enabled: Enable this notification by default """ notice = {} notice['Notification-Name'] = name notice['Notification-Enabled'] = enabled self.notifications.append(notice) self.add_header('Notifications-Count', len(self.notifications)) def encode(self): """Encode a GNTP Registration Message :return string: Encoded GNTP Registration message. Returned as a byte string """ buff = _GNTPBuffer() buff.writeln(self._format_info()) #Headers for k, v in self.headers.items(): buff.writeheader(k, v) buff.writeln() #Notifications if len(self.notifications) > 0: for notice in self.notifications: for k, v in notice.items(): buff.writeheader(k, v) buff.writeln() #Resources for resource, data in self.resources.items(): buff.writeheader('Identifier', resource) buff.writeheader('Length', len(data)) buff.writeln() buff.write(data) buff.writeln() buff.writeln() return buff.getvalue() class GNTPNotice(_GNTPBase): """Represents a GNTP Notification Command :param string data: (Optional) See decode() :param string app: (Optional) Set Application-Name :param string name: (Optional) Set Notification-Name :param string title: (Optional) Set Notification Title :param string password: (Optional) Password to use while encoding/decoding messages """ _requiredHeaders = [ 'Application-Name', 'Notification-Name', 'Notification-Title' ] def __init__(self, data=None, app=None, name=None, title=None, password=None): _GNTPBase.__init__(self, 'NOTIFY') if data: self.decode(data, password) else: self.set_password(password) if app: self.add_header('Application-Name', app) if name: self.add_header('Notification-Name', name) if title: self.add_header('Notification-Title', title) def decode(self, data, password): """Decode existing GNTP Notification message :param string data: Message to decode. """ self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) for i, part in enumerate(parts): if i == 0: continue # Skip Header if part.strip() == '': continue notice = self._parse_dict(part) if notice.get('Identifier', False): notice['Data'] = self._decode_binary(part, notice) #open('notice.png','wblol').write(notice['Data']) self.resources[notice.get('Identifier')] = notice class GNTPSubscribe(_GNTPBase): """Represents a GNTP Subscribe Command :param string data: (Optional) See decode() :param string password: (Optional) Password to use while encoding/decoding messages """ _requiredHeaders = [ 'Subscriber-ID', 'Subscriber-Name', ] def __init__(self, data=None, password=None): _GNTPBase.__init__(self, 'SUBSCRIBE') if data: self.decode(data, password) else: self.set_password(password) class GNTPOK(_GNTPBase): """Represents a GNTP OK Response :param string data: (Optional) See _GNTPResponse.decode() :param string action: (Optional) Set type of action the OK Response is for """ _requiredHeaders = ['Response-Action'] def __init__(self, data=None, action=None): _GNTPBase.__init__(self, '-OK') if data: self.decode(data) if action: self.add_header('Response-Action', action) class GNTPError(_GNTPBase): """Represents a GNTP Error response :param string data: (Optional) See _GNTPResponse.decode() :param string errorcode: (Optional) Error code :param string errordesc: (Optional) Error Description """ _requiredHeaders = ['Error-Code', 'Error-Description'] def __init__(self, data=None, errorcode=None, errordesc=None): _GNTPBase.__init__(self, '-ERROR') if data: self.decode(data) if errorcode: self.add_header('Error-Code', errorcode) self.add_header('Error-Description', errordesc) def error(self): return (self.headers.get('Error-Code', None), self.headers.get('Error-Description', None)) def parse_gntp(data, password=None): """Attempt to parse a message as a GNTP message :param string data: Message to be parsed :param string password: Optional password to be used to verify the message """ data = gntp.shim.u(data) match = GNTP_INFO_LINE_SHORT.match(data) if not match: raise errors.ParseError('INVALID_GNTP_INFO') info = match.groupdict() if info['messagetype'] == 'REGISTER': return GNTPRegister(data, password=password) elif info['messagetype'] == 'NOTIFY': return GNTPNotice(data, password=password) elif info['messagetype'] == 'SUBSCRIBE': return GNTPSubscribe(data, password=password) elif info['messagetype'] == '-OK': return GNTPOK(data) elif info['messagetype'] == '-ERROR': return GNTPError(data) raise errors.ParseError('INVALID_GNTP_MESSAGE')
13,975
Python
.py
412
30.694175
105
0.714869
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,727
version.py
CouchPotato_CouchPotatoServer/libs/gntp/version.py
# Copyright: 2013 Paul Traylor # These sources are released under the terms of the MIT license: see LICENSE __version__ = '1.0.2'
131
Python
.py
3
42.333333
76
0.748031
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,728
windows.py
CouchPotato_CouchPotatoServer/libs/unrar2/windows.py
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Low level interface - see UnRARDLL\UNRARDLL.TXT from __future__ import generators from couchpotato.environment import Env from shutil import copyfile import ctypes, ctypes.wintypes import os, os.path, re import time from rar_exceptions import * ERAR_END_ARCHIVE = 10 ERAR_NO_MEMORY = 11 ERAR_BAD_DATA = 12 ERAR_BAD_ARCHIVE = 13 ERAR_UNKNOWN_FORMAT = 14 ERAR_EOPEN = 15 ERAR_ECREATE = 16 ERAR_ECLOSE = 17 ERAR_EREAD = 18 ERAR_EWRITE = 19 ERAR_SMALL_BUF = 20 ERAR_UNKNOWN = 21 ERAR_MISSING_PASSWORD = 22 RAR_OM_LIST = 0 RAR_OM_EXTRACT = 1 RAR_SKIP = 0 RAR_TEST = 1 RAR_EXTRACT = 2 RAR_VOL_ASK = 0 RAR_VOL_NOTIFY = 1 RAR_DLL_VERSION = 3 # enum UNRARCALLBACK_MESSAGES UCM_CHANGEVOLUME = 0 UCM_PROCESSDATA = 1 UCM_NEEDPASSWORD = 2 architecture_bits = ctypes.sizeof(ctypes.c_voidp)*8 dll_name = "unrar.dll" if architecture_bits == 64: dll_name = "unrar64.dll" # Copy dll first dll_file = os.path.join(os.path.dirname(__file__), dll_name) dll_copy = os.path.join(Env.get('cache_dir'), 'copied.dll') if os.path.isfile(dll_copy): os.remove(dll_copy) copyfile(dll_file, dll_copy) volume_naming1 = re.compile("\.r([0-9]{2})$") volume_naming2 = re.compile("\.([0-9]{3}).rar$") volume_naming3 = re.compile("\.part([0-9]+).rar$") unrar = ctypes.WinDLL(dll_copy) class RAROpenArchiveDataEx(ctypes.Structure): def __init__(self, ArcName=None, ArcNameW=u'', OpenMode=RAR_OM_LIST): self.CmtBuf = ctypes.c_buffer(64*1024) ctypes.Structure.__init__(self, ArcName=ArcName, ArcNameW=ArcNameW, OpenMode=OpenMode, _CmtBuf=ctypes.addressof(self.CmtBuf), CmtBufSize=ctypes.sizeof(self.CmtBuf)) _fields_ = [ ('ArcName', ctypes.c_char_p), ('ArcNameW', ctypes.c_wchar_p), ('OpenMode', ctypes.c_uint), ('OpenResult', ctypes.c_uint), ('_CmtBuf', ctypes.c_voidp), ('CmtBufSize', ctypes.c_uint), ('CmtSize', ctypes.c_uint), ('CmtState', ctypes.c_uint), ('Flags', ctypes.c_uint), ('Reserved', ctypes.c_uint*32), ] class RARHeaderDataEx(ctypes.Structure): def __init__(self): self.CmtBuf = ctypes.c_buffer(64*1024) ctypes.Structure.__init__(self, _CmtBuf=ctypes.addressof(self.CmtBuf), CmtBufSize=ctypes.sizeof(self.CmtBuf)) _fields_ = [ ('ArcName', ctypes.c_char*1024), ('ArcNameW', ctypes.c_wchar*1024), ('FileName', ctypes.c_char*1024), ('FileNameW', ctypes.c_wchar*1024), ('Flags', ctypes.c_uint), ('PackSize', ctypes.c_uint), ('PackSizeHigh', ctypes.c_uint), ('UnpSize', ctypes.c_uint), ('UnpSizeHigh', ctypes.c_uint), ('HostOS', ctypes.c_uint), ('FileCRC', ctypes.c_uint), ('FileTime', ctypes.c_uint), ('UnpVer', ctypes.c_uint), ('Method', ctypes.c_uint), ('FileAttr', ctypes.c_uint), ('_CmtBuf', ctypes.c_voidp), ('CmtBufSize', ctypes.c_uint), ('CmtSize', ctypes.c_uint), ('CmtState', ctypes.c_uint), ('Reserved', ctypes.c_uint*1024), ] def DosDateTimeToTimeTuple(dosDateTime): """Convert an MS-DOS format date time to a Python time tuple. """ dosDate = dosDateTime >> 16 dosTime = dosDateTime & 0xffff day = dosDate & 0x1f month = (dosDate >> 5) & 0xf year = 1980 + (dosDate >> 9) second = 2*(dosTime & 0x1f) minute = (dosTime >> 5) & 0x3f hour = dosTime >> 11 return time.localtime(time.mktime((year, month, day, hour, minute, second, 0, 1, -1))) def _wrap(restype, function, argtypes): result = function result.argtypes = argtypes result.restype = restype return result RARGetDllVersion = _wrap(ctypes.c_int, unrar.RARGetDllVersion, []) RAROpenArchiveEx = _wrap(ctypes.wintypes.HANDLE, unrar.RAROpenArchiveEx, [ctypes.POINTER(RAROpenArchiveDataEx)]) RARReadHeaderEx = _wrap(ctypes.c_int, unrar.RARReadHeaderEx, [ctypes.wintypes.HANDLE, ctypes.POINTER(RARHeaderDataEx)]) _RARSetPassword = _wrap(ctypes.c_int, unrar.RARSetPassword, [ctypes.wintypes.HANDLE, ctypes.c_char_p]) def RARSetPassword(*args, **kwargs): _RARSetPassword(*args, **kwargs) RARProcessFile = _wrap(ctypes.c_int, unrar.RARProcessFile, [ctypes.wintypes.HANDLE, ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p]) RARCloseArchive = _wrap(ctypes.c_int, unrar.RARCloseArchive, [ctypes.wintypes.HANDLE]) UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint, ctypes.c_long, ctypes.c_long, ctypes.c_long) RARSetCallback = _wrap(ctypes.c_int, unrar.RARSetCallback, [ctypes.wintypes.HANDLE, UNRARCALLBACK, ctypes.c_long]) RARExceptions = { ERAR_NO_MEMORY : MemoryError, ERAR_BAD_DATA : ArchiveHeaderBroken, ERAR_BAD_ARCHIVE : InvalidRARArchive, ERAR_EOPEN : FileOpenError, } class PassiveReader: """Used for reading files to memory""" def __init__(self, usercallback = None): self.buf = [] self.ucb = usercallback def _callback(self, msg, UserData, P1, P2): if msg == UCM_PROCESSDATA: data = (ctypes.c_char*P2).from_address(P1).raw if self.ucb!=None: self.ucb(data) else: self.buf.append(data) return 1 def get_result(self): return ''.join(self.buf) class RarInfoIterator(object): def __init__(self, arc): self.arc = arc self.index = 0 self.headerData = RARHeaderDataEx() self.res = RARReadHeaderEx(self.arc._handle, ctypes.byref(self.headerData)) if self.res in [ERAR_BAD_DATA, ERAR_MISSING_PASSWORD]: raise IncorrectRARPassword self.arc.lockStatus = "locked" self.arc.needskip = False def __iter__(self): return self def next(self): if self.index>0: if self.arc.needskip: RARProcessFile(self.arc._handle, RAR_SKIP, None, None) self.res = RARReadHeaderEx(self.arc._handle, ctypes.byref(self.headerData)) if self.res: raise StopIteration self.arc.needskip = True data = {} data['index'] = self.index data['filename'] = self.headerData.FileNameW data['datetime'] = DosDateTimeToTimeTuple(self.headerData.FileTime) data['isdir'] = ((self.headerData.Flags & 0xE0) == 0xE0) data['size'] = self.headerData.UnpSize + (self.headerData.UnpSizeHigh << 32) if self.headerData.CmtState == 1: data['comment'] = self.headerData.CmtBuf.value else: data['comment'] = None self.index += 1 return data def __del__(self): self.arc.lockStatus = "finished" def generate_password_provider(password): def password_provider_callback(msg, UserData, P1, P2): if msg == UCM_NEEDPASSWORD and password!=None: (ctypes.c_char*P2).from_address(P1).value = password return 1 return password_provider_callback class RarFileImplementation(object): def init(self, password=None, custom_path = None): self.password = password archiveData = RAROpenArchiveDataEx(ArcNameW=self.archiveName, OpenMode=RAR_OM_EXTRACT) self._handle = RAROpenArchiveEx(ctypes.byref(archiveData)) self.c_callback = UNRARCALLBACK(generate_password_provider(self.password)) RARSetCallback(self._handle, self.c_callback, 1) if archiveData.OpenResult != 0: raise RARExceptions[archiveData.OpenResult] if archiveData.CmtState == 1: self.comment = archiveData.CmtBuf.value else: self.comment = None if password: RARSetPassword(self._handle, password) self.lockStatus = "ready" self.isVolume = archiveData.Flags & 1 def destruct(self): if self._handle and RARCloseArchive: RARCloseArchive(self._handle) def make_sure_ready(self): if self.lockStatus == "locked": raise InvalidRARArchiveUsage("cannot execute infoiter() without finishing previous one") if self.lockStatus == "finished": self.destruct() self.init(self.password) def infoiter(self): self.make_sure_ready() return RarInfoIterator(self) def read_files(self, checker): res = [] for info in self.infoiter(): if checker(info) and not info.isdir: reader = PassiveReader() c_callback = UNRARCALLBACK(reader._callback) RARSetCallback(self._handle, c_callback, 1) tmpres = RARProcessFile(self._handle, RAR_TEST, None, None) if tmpres in [ERAR_BAD_DATA, ERAR_MISSING_PASSWORD]: raise IncorrectRARPassword self.needskip = False res.append((info, reader.get_result())) return res def extract(self, checker, path, withSubpath, overwrite): res = [] for info in self.infoiter(): checkres = checker(info) if checkres!=False and not info.isdir: if checkres==True: fn = info.filename if not withSubpath: fn = os.path.split(fn)[-1] target = os.path.join(path, fn) else: raise DeprecationWarning, "Condition callbacks returning strings are deprecated and only supported in Windows" target = checkres if overwrite or (not os.path.exists(target)): tmpres = RARProcessFile(self._handle, RAR_EXTRACT, None, target) if tmpres in [ERAR_BAD_DATA, ERAR_MISSING_PASSWORD]: raise IncorrectRARPassword self.needskip = False res.append(info) return res def get_volume(self): if not self.isVolume: return None headerData = RARHeaderDataEx() res = RARReadHeaderEx(self._handle, ctypes.byref(headerData)) arcName = headerData.ArcNameW match3 = volume_naming3.search(arcName) if match3 != None: return int(match3.group(1)) - 1 match2 = volume_naming3.search(arcName) if match2 != None: return int(match2.group(1)) match1 = volume_naming1.search(arcName) if match1 != None: return int(match1.group(1)) + 1 return 0
11,832
Python
.py
276
34.300725
172
0.632994
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,729
rar_exceptions.py
CouchPotato_CouchPotatoServer/libs/unrar2/rar_exceptions.py
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Low level interface - see UnRARDLL\UNRARDLL.TXT class ArchiveHeaderBroken(Exception): pass class InvalidRARArchive(Exception): pass class FileOpenError(Exception): pass class IncorrectRARPassword(Exception): pass class InvalidRARArchiveUsage(Exception): pass
1,391
Python
.py
27
50.407407
71
0.80676
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,730
unix.py
CouchPotato_CouchPotatoServer/libs/unrar2/unix.py
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Unix version uses unrar command line executable import platform import stat import subprocess import gc import os, os.path import time, re from rar_exceptions import * from dateutil.parser import parse from rar_exceptions import * class UnpackerNotInstalled(Exception): pass rar_executable_cached = None rar_executable_version = None osx_unrar = os.path.join(os.path.dirname(__file__), 'unrar') if os.path.isfile(osx_unrar) and 'darwin' in platform.platform().lower(): try: st = os.stat(osx_unrar) os.chmod(osx_unrar, st.st_mode | stat.S_IEXEC) except: pass def call_unrar(params, custom_path = None): "Calls rar/unrar command line executable, returns stdout pipe" global rar_executable_cached if rar_executable_cached is None: for command in (custom_path, 'unrar', 'rar', osx_unrar): if not command: continue try: subprocess.Popen([command], stdout=subprocess.PIPE) rar_executable_cached = command break except OSError: pass if rar_executable_cached is None: raise UnpackerNotInstalled("No suitable RAR unpacker installed") assert type(params) == list, "params must be list" args = [rar_executable_cached] + params try: gc.disable() # See http://bugs.python.org/issue1336 return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) finally: gc.enable() class RarFileImplementation(object): def init(self, password = None, custom_path = None): global rar_executable_version self.password = password self.custom_path = custom_path stdoutdata, stderrdata = self.call('v', []).communicate() for line in stderrdata.splitlines(): if line.strip().startswith("Cannot open"): raise FileOpenError if line.find("CRC failed")>=0: raise IncorrectRARPassword accum = [] source = iter(stdoutdata.splitlines()) line = '' while (line.find('RAR ') == -1): line = source.next() signature = line # The code below is mighty flaky # and will probably crash on localized versions of RAR # but I see no safe way to rewrite it using a CLI tool if signature.find("RAR 4") > -1: rar_executable_version = 4 while not (line.startswith('Comment:') or line.startswith('Pathname/Comment')): if line.strip().endswith('is not RAR archive'): raise InvalidRARArchive line = source.next() while not line.startswith('Pathname/Comment'): accum.append(line.rstrip('\n')) line = source.next() if len(accum): accum[0] = accum[0][9:] # strip out "Comment:" part self.comment = '\n'.join(accum[:-1]) else: self.comment = None elif signature.find("RAR 5") > -1: rar_executable_version = 5 line = source.next() while not line.startswith('Archive:'): if line.strip().endswith('is not RAR archive'): raise InvalidRARArchive accum.append(line.rstrip('\n')) line = source.next() if len(accum): self.comment = '\n'.join(accum[:-1]).strip() else: self.comment = None else: raise UnpackerNotInstalled("Unsupported RAR version, expected 4.x or 5.x, found: " + signature.split(" ")[1]) def escaped_password(self): return '-' if self.password == None else self.password def call(self, cmd, options=[], files=[]): options2 = options + ['p'+self.escaped_password()] soptions = ['-'+x for x in options2] return call_unrar([cmd] + soptions + ['--', self.archiveName] + files, self.custom_path) def infoiter(self): command = "v" if rar_executable_version == 4 else "l" stdoutdata, stderrdata = self.call(command, ['c-']).communicate() for line in stderrdata.splitlines(): if line.strip().startswith("Cannot open"): raise FileOpenError accum = [] source = iter(stdoutdata.splitlines()) line = '' while not line.startswith('-----------'): if line.strip().endswith('is not RAR archive'): raise InvalidRARArchive if line.startswith("CRC failed") or line.startswith("Checksum error"): raise IncorrectRARPassword line = source.next() line = source.next() i = 0 re_spaces = re.compile(r"\s+") if rar_executable_version == 4: while not line.startswith('-----------'): accum.append(line) if len(accum)==2: data = {} data['index'] = i # asterisks mark password-encrypted files data['filename'] = accum[0].strip().lstrip("*") # asterisks marks password-encrypted files fields = re_spaces.split(accum[1].strip()) data['size'] = int(fields[0]) attr = fields[5] data['isdir'] = 'd' in attr.lower() data['datetime'] = time.strptime(fields[3]+" "+fields[4], '%d-%m-%y %H:%M') data['comment'] = None data['volume'] = None yield data accum = [] i += 1 line = source.next() elif rar_executable_version == 5: while not line.startswith('-----------'): fields = line.strip().lstrip("*").split() data = {} data['index'] = i data['filename'] = " ".join(fields[4:]) data['size'] = int(fields[1]) attr = fields[0] data['isdir'] = 'd' in attr.lower() data['datetime'] = parse(fields[2] + " " + fields[3]).timetuple() data['comment'] = None data['volume'] = None yield data i += 1 line = source.next() def read_files(self, checker): res = [] for info in self.infoiter(): checkres = checker(info) if checkres==True and not info.isdir: pipe = self.call('p', ['inul'], [info.filename]).stdout res.append((info, pipe.read())) return res def extract(self, checker, path, withSubpath, overwrite): res = [] command = 'x' if not withSubpath: command = 'e' options = [] if overwrite: options.append('o+') else: options.append('o-') if not path.endswith(os.sep): path += os.sep names = [] for info in self.infoiter(): checkres = checker(info) if type(checkres) in [str, unicode]: raise NotImplementedError("Condition callbacks returning strings are deprecated and only supported in Windows") if checkres==True and not info.isdir: names.append(info.filename) res.append(info) names.append(path) proc = self.call(command, options, names) stdoutdata, stderrdata = proc.communicate() if stderrdata.find("CRC failed")>=0 or stderrdata.find("Checksum error")>=0: raise IncorrectRARPassword return res def destruct(self): pass def get_volume(self): command = "v" if rar_executable_version == 4 else "l" stdoutdata, stderrdata = self.call(command, ['c-']).communicate() for line in stderrdata.splitlines(): if line.strip().startswith("Cannot open"): raise FileOpenError source = iter(stdoutdata.splitlines()) line = '' while not line.startswith('-----------'): if line.strip().endswith('is not RAR archive'): raise InvalidRARArchive if line.startswith("CRC failed") or line.startswith("Checksum error"): raise IncorrectRARPassword line = source.next() line = source.next() if rar_executable_version == 4: while not line.startswith('-----------'): line = source.next() line = source.next() items = line.strip().split() if len(items)>4 and items[4]=="volume": return int(items[5]) - 1 else: return None elif rar_executable_version == 5: while not line.startswith('-----------'): line = source.next() line = source.next() items = line.strip().split() if items[1]=="volume": return int(items[2]) - 1 else: return None
10,224
Python
.py
238
32.004202
127
0.57018
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,731
__init__.py
CouchPotato_CouchPotatoServer/libs/unrar2/__init__.py
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ pyUnRAR2 is a ctypes based wrapper around the free UnRAR.dll. It is an modified version of Jimmy Retzlaff's pyUnRAR - more simple, stable and foolproof. Notice that it has INCOMPATIBLE interface. It enables reading and unpacking of archives created with the RAR/WinRAR archivers. There is a low-level interface which is very similar to the C interface provided by UnRAR. There is also a higher level interface which makes some common operations easier. """ __version__ = '0.99.6' try: WindowsError in_windows = True except NameError: in_windows = False if in_windows: from windows import RarFileImplementation else: from unix import RarFileImplementation import fnmatch, time, weakref class RarInfo(object): """Represents a file header in an archive. Don't instantiate directly. Use only to obtain information about file. YOU CANNOT EXTRACT FILE CONTENTS USING THIS OBJECT. USE METHODS OF RarFile CLASS INSTEAD. Properties: index - index of file within the archive filename - name of the file in the archive including path (if any) datetime - file date/time as a struct_time suitable for time.strftime isdir - True if the file is a directory size - size in bytes of the uncompressed file comment - comment associated with the file Note - this is not currently intended to be a Python file-like object. """ def __init__(self, rarfile, data): self.rarfile = weakref.proxy(rarfile) self.index = data['index'] self.filename = data['filename'] self.isdir = data['isdir'] self.size = data['size'] self.datetime = data['datetime'] self.comment = data['comment'] def __str__(self): try : arcName = self.rarfile.archiveName except ReferenceError: arcName = "[ARCHIVE_NO_LONGER_LOADED]" return '<RarInfo "%s" in "%s">' % (self.filename, arcName) class RarFile(RarFileImplementation): def __init__(self, archiveName, password=None, custom_path = None): """Instantiate the archive. archiveName is the name of the RAR file. password is used to decrypt the files in the archive. Properties: comment - comment associated with the archive >>> print RarFile('test.rar').comment This is a test. """ self.archiveName = archiveName RarFileImplementation.init(self, password, custom_path) def __del__(self): self.destruct() def infoiter(self): """Iterate over all the files in the archive, generating RarInfos. >>> import os >>> for fileInArchive in RarFile('test.rar').infoiter(): ... print os.path.split(fileInArchive.filename)[-1], ... print fileInArchive.isdir, ... print fileInArchive.size, ... print fileInArchive.comment, ... print tuple(fileInArchive.datetime)[0:5], ... print time.strftime('%a, %d %b %Y %H:%M', fileInArchive.datetime) test True 0 None (2003, 6, 30, 1, 59) Mon, 30 Jun 2003 01:59 test.txt False 20 None (2003, 6, 30, 2, 1) Mon, 30 Jun 2003 02:01 this.py False 1030 None (2002, 2, 8, 16, 47) Fri, 08 Feb 2002 16:47 """ for params in RarFileImplementation.infoiter(self): yield RarInfo(self, params) def infolist(self): """Return a list of RarInfos, descripting the contents of the archive.""" return list(self.infoiter()) def read_files(self, condition='*'): """Read specific files from archive into memory. If "condition" is a list of numbers, then return files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns boolean True (extract) or False (skip). If "condition" is omitted, all files are returned. Returns list of tuples (RarInfo info, str contents) """ checker = condition2checker(condition) return RarFileImplementation.read_files(self, checker) def extract(self, condition='*', path='.', withSubpath=True, overwrite=True): """Extract specific files from archive to disk. If "condition" is a list of numbers, then extract files which have those positions in infolist. If "condition" is a string, then it is treated as a wildcard for names of files to extract. If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object and returns either boolean True (extract) or boolean False (skip). DEPRECATED: If "condition" callback returns string (only supported for Windows) - that string will be used as a new name to save the file under. If "condition" is omitted, all files are extracted. "path" is a directory to extract to "withSubpath" flag denotes whether files are extracted with their full path in the archive. "overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true. Returns list of RarInfos for extracted files.""" checker = condition2checker(condition) return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite) def get_volume(self): """Determine which volume is it in a multi-volume archive. Returns None if it's not a multi-volume archive, 0-based volume number otherwise.""" return RarFileImplementation.get_volume(self) def condition2checker(condition): """Converts different condition types to callback""" if type(condition) in [str, unicode]: def smatcher(info): return fnmatch.fnmatch(info.filename, condition) return smatcher elif type(condition) in [list, tuple] and type(condition[0]) in [int, long]: def imatcher(info): return info.index in condition return imatcher elif callable(condition): return condition else: raise TypeError
7,329
Python
.py
147
43.251701
106
0.696194
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,732
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/__init__.py
import sys # http://www.python.org/dev/peps/pep-0396/ __version__ = '0.1.8' if sys.version_info[:2] < (2, 4): raise RuntimeError('PyASN1 requires Python 2.4 or later')
175
Python
.py
5
32.6
61
0.682635
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,733
debug.py
CouchPotato_CouchPotatoServer/libs/pyasn1/debug.py
import time import logging from pyasn1.compat.octets import octs2ints from pyasn1 import error from pyasn1 import __version__ flagNone = 0x0000 flagEncoder = 0x0001 flagDecoder = 0x0002 flagAll = 0xffff flagMap = { 'encoder': flagEncoder, 'decoder': flagDecoder, 'all': flagAll } class Printer: def __init__(self, logger=None, handler=None, formatter=None): if logger is None: logger = logging.getLogger('pyasn1') logger.setLevel(logging.DEBUG) if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter('%(asctime)s %(name)s: %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) logger.addHandler(handler) self.__logger = logger def __call__(self, msg): self.__logger.debug(msg) def __str__(self): return '<python built-in logging>' if hasattr(logging, 'NullHandler'): NullHandler = logging.NullHandler else: # Python 2.6 and older class NullHandler(logging.Handler): def emit(self, record): pass class Debug: defaultPrinter = None def __init__(self, *flags, **options): self._flags = flagNone if options.get('printer') is not None: self._printer = options.get('printer') elif self.defaultPrinter is not None: self._printer = self.defaultPrinter if 'loggerName' in options: # route our logs to parent logger self._printer = Printer( logger=logging.getLogger(options['loggerName']), handler=NullHandler() ) else: self._printer = Printer() self('running pyasn1 version %s' % __version__) for f in flags: inverse = f and f[0] in ('!', '~') if inverse: f = f[1:] try: if inverse: self._flags &= ~flagMap[f] else: self._flags |= flagMap[f] except KeyError: raise error.PyAsn1Error('bad debug flag %s' % f) self('debug category \'%s\' %s' % (f, inverse and 'disabled' or 'enabled')) def __str__(self): return 'logger %s, flags %x' % (self._printer, self._flags) def __call__(self, msg): self._printer(msg) def __and__(self, flag): return self._flags & flag def __rand__(self, flag): return flag & self._flags logger = 0 def setLogger(l): global logger logger = l def hexdump(octets): return ' '.join( [ '%s%.2X' % (n%16 == 0 and ('\n%.5d: ' % n) or '', x) for n,x in zip(range(len(octets)), octs2ints(octets)) ] ) class Scope: def __init__(self): self._list = [] def __str__(self): return '.'.join(self._list) def push(self, token): self._list.append(token) def pop(self): return self._list.pop() scope = Scope()
3,044
Python
.py
91
25.274725
87
0.572063
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,734
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/__init__.py
# This file is necessary to make this directory a package.
59
Python
.py
1
58
58
0.793103
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,735
decoder.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/der/decoder.py
# DER decoder from pyasn1.codec.cer import decoder tagMap = decoder.tagMap typeMap = decoder.typeMap class Decoder(decoder.Decoder): supportIndefLength = False decode = Decoder(tagMap, typeMap)
200
Python
.py
7
26.714286
36
0.816754
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,736
encoder.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/der/encoder.py
# DER encoder from pyasn1.type import univ from pyasn1.codec.cer import encoder from pyasn1 import error class SetOfEncoder(encoder.SetOfEncoder): def _cmpSetComponents(self, c1, c2): tagSet1 = isinstance(c1, univ.Choice) and \ c1.getEffectiveTagSet() or c1.getTagSet() tagSet2 = isinstance(c2, univ.Choice) and \ c2.getEffectiveTagSet() or c2.getTagSet() return cmp(tagSet1, tagSet2) tagMap = encoder.tagMap.copy() tagMap.update({ # Overload CER encoders with BER ones (a bit hackerish XXX) univ.BitString.tagSet: encoder.encoder.BitStringEncoder(), univ.OctetString.tagSet: encoder.encoder.OctetStringEncoder(), # Set & SetOf have same tags univ.SetOf().tagSet: SetOfEncoder() }) typeMap = encoder.typeMap class Encoder(encoder.Encoder): supportIndefLength = False def __call__(self, client, defMode=True, maxChunkSize=0): if not defMode: raise error.PyAsn1Error('DER forbids indefinite length mode') return encoder.Encoder.__call__(self, client, defMode, maxChunkSize) encode = Encoder(tagMap, typeMap)
1,139
Python
.py
27
36.259259
76
0.709124
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,737
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/der/__init__.py
# This file is necessary to make this directory a package.
59
Python
.py
1
58
58
0.793103
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,738
decoder.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/ber/decoder.py
# BER decoder from pyasn1.type import tag, univ, char, useful, tagmap from pyasn1.codec.ber import eoo from pyasn1.compat.octets import oct2int, isOctetsType from pyasn1 import debug, error class AbstractDecoder: protoComponent = None def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): raise error.PyAsn1Error('Decoder not implemented for %s' % (tagSet,)) def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): raise error.PyAsn1Error('Indefinite length mode decoder not implemented for %s' % (tagSet,)) class AbstractSimpleDecoder(AbstractDecoder): tagFormats = (tag.tagFormatSimple,) def _createComponent(self, asn1Spec, tagSet, value=None): if tagSet[0][1] not in self.tagFormats: raise error.PyAsn1Error('Invalid tag format %s for %s' % (tagSet[0], self.protoComponent.prettyPrintType())) if asn1Spec is None: return self.protoComponent.clone(value, tagSet) elif value is None: return asn1Spec else: return asn1Spec.clone(value) class AbstractConstructedDecoder(AbstractDecoder): tagFormats = (tag.tagFormatConstructed,) def _createComponent(self, asn1Spec, tagSet, value=None): if tagSet[0][1] not in self.tagFormats: raise error.PyAsn1Error('Invalid tag format %s for %s' % (tagSet[0], self.protoComponent.prettyPrintType())) if asn1Spec is None: return self.protoComponent.clone(tagSet) else: return asn1Spec.clone() class ExplicitTagDecoder(AbstractSimpleDecoder): protoComponent = univ.Any('') tagFormats = (tag.tagFormatConstructed,) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): if substrateFun: return substrateFun( self._createComponent(asn1Spec, tagSet, ''), substrate, length ) head, tail = substrate[:length], substrate[length:] value, _ = decodeFun(head, asn1Spec, tagSet, length) return value, tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): if substrateFun: return substrateFun( self._createComponent(asn1Spec, tagSet, ''), substrate, length ) value, substrate = decodeFun(substrate, asn1Spec, tagSet, length) terminator, substrate = decodeFun(substrate, allowEoo=True) if eoo.endOfOctets.isSameTypeWith(terminator) and \ terminator == eoo.endOfOctets: return value, substrate else: raise error.PyAsn1Error('Missing end-of-octets terminator') explicitTagDecoder = ExplicitTagDecoder() class IntegerDecoder(AbstractSimpleDecoder): protoComponent = univ.Integer(0) precomputedValues = { '\x00': 0, '\x01': 1, '\x02': 2, '\x03': 3, '\x04': 4, '\x05': 5, '\x06': 6, '\x07': 7, '\x08': 8, '\x09': 9, '\xff': -1, '\xfe': -2, '\xfd': -3, '\xfc': -4, '\xfb': -5 } def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] if not head: return self._createComponent(asn1Spec, tagSet, 0), tail if head in self.precomputedValues: value = self.precomputedValues[head] else: firstOctet = oct2int(head[0]) if firstOctet & 0x80: value = -1 else: value = 0 for octet in head: value = value << 8 | oct2int(octet) return self._createComponent(asn1Spec, tagSet, value), tail class BooleanDecoder(IntegerDecoder): protoComponent = univ.Boolean(0) def _createComponent(self, asn1Spec, tagSet, value=None): return IntegerDecoder._createComponent(self, asn1Spec, tagSet, value and 1 or 0) class BitStringDecoder(AbstractSimpleDecoder): protoComponent = univ.BitString(()) tagFormats = (tag.tagFormatSimple, tag.tagFormatConstructed) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] if tagSet[0][1] == tag.tagFormatSimple: # XXX what tag to check? if not head: raise error.PyAsn1Error('Empty substrate') trailingBits = oct2int(head[0]) if trailingBits > 7: raise error.PyAsn1Error( 'Trailing bits overflow %s' % trailingBits ) head = head[1:] lsb = p = 0; l = len(head)-1; b = [] while p <= l: if p == l: lsb = trailingBits j = 7 o = oct2int(head[p]) while j >= lsb: b.append((o>>j)&0x01) j = j - 1 p = p + 1 return self._createComponent(asn1Spec, tagSet, b), tail r = self._createComponent(asn1Spec, tagSet, ()) if substrateFun: return substrateFun(r, substrate, length) while head: component, head = decodeFun(head, self.protoComponent) r = r + component return r, tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): r = self._createComponent(asn1Spec, tagSet, '') if substrateFun: return substrateFun(r, substrate, length) while substrate: component, substrate = decodeFun(substrate, self.protoComponent, allowEoo=True) if eoo.endOfOctets.isSameTypeWith(component) and \ component == eoo.endOfOctets: break r = r + component else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) return r, substrate class OctetStringDecoder(AbstractSimpleDecoder): protoComponent = univ.OctetString('') tagFormats = (tag.tagFormatSimple, tag.tagFormatConstructed) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] if tagSet[0][1] == tag.tagFormatSimple: # XXX what tag to check? return self._createComponent(asn1Spec, tagSet, head), tail r = self._createComponent(asn1Spec, tagSet, '') if substrateFun: return substrateFun(r, substrate, length) while head: component, head = decodeFun(head, self.protoComponent) r = r + component return r, tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): r = self._createComponent(asn1Spec, tagSet, '') if substrateFun: return substrateFun(r, substrate, length) while substrate: component, substrate = decodeFun(substrate, self.protoComponent, allowEoo=True) if eoo.endOfOctets.isSameTypeWith(component) and \ component == eoo.endOfOctets: break r = r + component else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) return r, substrate class NullDecoder(AbstractSimpleDecoder): protoComponent = univ.Null('') def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] r = self._createComponent(asn1Spec, tagSet) if head: raise error.PyAsn1Error('Unexpected %d-octet substrate for Null' % length) return r, tail class ObjectIdentifierDecoder(AbstractSimpleDecoder): protoComponent = univ.ObjectIdentifier(()) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] if not head: raise error.PyAsn1Error('Empty substrate') oid = () index = 0 substrateLen = len(head) while index < substrateLen: subId = oct2int(head[index]) index += 1 if subId < 128: oid = oid + (subId,) elif subId > 128: # Construct subid from a number of octets nextSubId = subId subId = 0 while nextSubId >= 128: subId = (subId << 7) + (nextSubId & 0x7F) if index >= substrateLen: raise error.SubstrateUnderrunError( 'Short substrate for sub-OID past %s' % (oid,) ) nextSubId = oct2int(head[index]) index += 1 oid = oid + ((subId << 7) + nextSubId,) elif subId == 128: # ASN.1 spec forbids leading zeros (0x80) in OID # encoding, tolerating it opens a vulnerability. See # http://www.cosic.esat.kuleuven.be/publications/article-1432.pdf # page 7 raise error.PyAsn1Error('Invalid octet 0x80 in OID encoding') # Decode two leading arcs if 0 <= oid[0] <= 39: oid = (0,) + oid elif 40 <= oid[0] <= 79: oid = (1, oid[0]-40) + oid[1:] elif oid[0] >= 80: oid = (2, oid[0]-80) + oid[1:] else: raise error.PyAsn1Error('Malformed first OID octet: %s' % head[0]) return self._createComponent(asn1Spec, tagSet, oid), tail class RealDecoder(AbstractSimpleDecoder): protoComponent = univ.Real() def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] if not head: return self._createComponent(asn1Spec, tagSet, 0.0), tail fo = oct2int(head[0]); head = head[1:] if fo & 0x80: # binary encoding if not head: raise error.PyAsn1Error("Incomplete floating-point value") n = (fo & 0x03) + 1 if n == 4: n = oct2int(head[0]) head = head[1:] eo, head = head[:n], head[n:] if not eo or not head: raise error.PyAsn1Error('Real exponent screwed') e = oct2int(eo[0]) & 0x80 and -1 or 0 while eo: # exponent e <<= 8 e |= oct2int(eo[0]) eo = eo[1:] b = fo >> 4 & 0x03 # base bits if b > 2: raise error.PyAsn1Error('Illegal Real base') if b == 1: # encbase = 8 e *= 3 elif b == 2: # encbase = 16 e *= 4 p = 0 while head: # value p <<= 8 p |= oct2int(head[0]) head = head[1:] if fo & 0x40: # sign bit p = -p sf = fo >> 2 & 0x03 # scale bits p *= 2**sf value = (p, 2, e) elif fo & 0x40: # infinite value value = fo & 0x01 and '-inf' or 'inf' elif fo & 0xc0 == 0: # character encoding if not head: raise error.PyAsn1Error("Incomplete floating-point value") try: if fo & 0x3 == 0x1: # NR1 value = (int(head), 10, 0) elif fo & 0x3 == 0x2: # NR2 value = float(head) elif fo & 0x3 == 0x3: # NR3 value = float(head) else: raise error.SubstrateUnderrunError( 'Unknown NR (tag %s)' % fo ) except ValueError: raise error.SubstrateUnderrunError( 'Bad character Real syntax' ) else: raise error.SubstrateUnderrunError( 'Unknown encoding (tag %s)' % fo ) return self._createComponent(asn1Spec, tagSet, value), tail class SequenceDecoder(AbstractConstructedDecoder): protoComponent = univ.Sequence() def _getComponentTagMap(self, r, idx): try: return r.getComponentTagMapNearPosition(idx) except error.PyAsn1Error: return def _getComponentPositionByType(self, r, t, idx): return r.getComponentPositionNearType(t, idx) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] r = self._createComponent(asn1Spec, tagSet) idx = 0 if substrateFun: return substrateFun(r, substrate, length) while head: asn1Spec = self._getComponentTagMap(r, idx) component, head = decodeFun(head, asn1Spec) idx = self._getComponentPositionByType( r, component.getEffectiveTagSet(), idx ) r.setComponentByPosition(idx, component, asn1Spec is None) idx = idx + 1 r.setDefaultComponents() r.verifySizeSpec() return r, tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): r = self._createComponent(asn1Spec, tagSet) if substrateFun: return substrateFun(r, substrate, length) idx = 0 while substrate: asn1Spec = self._getComponentTagMap(r, idx) component, substrate = decodeFun(substrate, asn1Spec, allowEoo=True) if eoo.endOfOctets.isSameTypeWith(component) and \ component == eoo.endOfOctets: break idx = self._getComponentPositionByType( r, component.getEffectiveTagSet(), idx ) r.setComponentByPosition(idx, component, asn1Spec is None) idx = idx + 1 else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) r.setDefaultComponents() r.verifySizeSpec() return r, substrate class SequenceOfDecoder(AbstractConstructedDecoder): protoComponent = univ.SequenceOf() def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] r = self._createComponent(asn1Spec, tagSet) if substrateFun: return substrateFun(r, substrate, length) asn1Spec = r.getComponentType() idx = 0 while head: component, head = decodeFun(head, asn1Spec) r.setComponentByPosition(idx, component, asn1Spec is None) idx = idx + 1 r.verifySizeSpec() return r, tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): r = self._createComponent(asn1Spec, tagSet) if substrateFun: return substrateFun(r, substrate, length) asn1Spec = r.getComponentType() idx = 0 while substrate: component, substrate = decodeFun(substrate, asn1Spec, allowEoo=True) if eoo.endOfOctets.isSameTypeWith(component) and \ component == eoo.endOfOctets: break r.setComponentByPosition(idx, component, asn1Spec is None) idx = idx + 1 else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) r.verifySizeSpec() return r, substrate class SetDecoder(SequenceDecoder): protoComponent = univ.Set() def _getComponentTagMap(self, r, idx): return r.getComponentTagMap() def _getComponentPositionByType(self, r, t, idx): nextIdx = r.getComponentPositionByType(t) if nextIdx is None: return idx else: return nextIdx class SetOfDecoder(SequenceOfDecoder): protoComponent = univ.SetOf() class ChoiceDecoder(AbstractConstructedDecoder): protoComponent = univ.Choice() tagFormats = (tag.tagFormatSimple, tag.tagFormatConstructed) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] r = self._createComponent(asn1Spec, tagSet) if substrateFun: return substrateFun(r, substrate, length) if r.getTagSet() == tagSet: # explicitly tagged Choice component, head = decodeFun( head, r.getComponentTagMap() ) else: component, head = decodeFun( head, r.getComponentTagMap(), tagSet, length, state ) if isinstance(component, univ.Choice): effectiveTagSet = component.getEffectiveTagSet() else: effectiveTagSet = component.getTagSet() r.setComponentByType(effectiveTagSet, component, 0, asn1Spec is None) return r, tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): r = self._createComponent(asn1Spec, tagSet) if substrateFun: return substrateFun(r, substrate, length) if r.getTagSet() == tagSet: # explicitly tagged Choice component, substrate = decodeFun(substrate, r.getComponentTagMap()) # eat up EOO marker eooMarker, substrate = decodeFun(substrate, allowEoo=True) if not eoo.endOfOctets.isSameTypeWith(eooMarker) or \ eooMarker != eoo.endOfOctets: raise error.PyAsn1Error('No EOO seen before substrate ends') else: component, substrate= decodeFun( substrate, r.getComponentTagMap(), tagSet, length, state ) if isinstance(component, univ.Choice): effectiveTagSet = component.getEffectiveTagSet() else: effectiveTagSet = component.getTagSet() r.setComponentByType(effectiveTagSet, component, 0, asn1Spec is None) return r, substrate class AnyDecoder(AbstractSimpleDecoder): protoComponent = univ.Any() tagFormats = (tag.tagFormatSimple, tag.tagFormatConstructed) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): if asn1Spec is None or \ asn1Spec is not None and tagSet != asn1Spec.getTagSet(): # untagged Any container, recover inner header substrate length = length + len(fullSubstrate) - len(substrate) substrate = fullSubstrate if substrateFun: return substrateFun(self._createComponent(asn1Spec, tagSet), substrate, length) head, tail = substrate[:length], substrate[length:] return self._createComponent(asn1Spec, tagSet, value=head), tail def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): if asn1Spec is not None and tagSet == asn1Spec.getTagSet(): # tagged Any type -- consume header substrate header = '' else: # untagged Any, recover header substrate header = fullSubstrate[:-len(substrate)] r = self._createComponent(asn1Spec, tagSet, header) # Any components do not inherit initial tag asn1Spec = self.protoComponent if substrateFun: return substrateFun(r, substrate, length) while substrate: component, substrate = decodeFun(substrate, asn1Spec, allowEoo=True) if eoo.endOfOctets.isSameTypeWith(component) and \ component == eoo.endOfOctets: break r = r + component else: raise error.SubstrateUnderrunError( 'No EOO seen before substrate ends' ) return r, substrate # character string types class UTF8StringDecoder(OctetStringDecoder): protoComponent = char.UTF8String() class NumericStringDecoder(OctetStringDecoder): protoComponent = char.NumericString() class PrintableStringDecoder(OctetStringDecoder): protoComponent = char.PrintableString() class TeletexStringDecoder(OctetStringDecoder): protoComponent = char.TeletexString() class VideotexStringDecoder(OctetStringDecoder): protoComponent = char.VideotexString() class IA5StringDecoder(OctetStringDecoder): protoComponent = char.IA5String() class GraphicStringDecoder(OctetStringDecoder): protoComponent = char.GraphicString() class VisibleStringDecoder(OctetStringDecoder): protoComponent = char.VisibleString() class GeneralStringDecoder(OctetStringDecoder): protoComponent = char.GeneralString() class UniversalStringDecoder(OctetStringDecoder): protoComponent = char.UniversalString() class BMPStringDecoder(OctetStringDecoder): protoComponent = char.BMPString() # "useful" types class ObjectDescriptorDecoder(OctetStringDecoder): protoComponent = useful.ObjectDescriptor() class GeneralizedTimeDecoder(OctetStringDecoder): protoComponent = useful.GeneralizedTime() class UTCTimeDecoder(OctetStringDecoder): protoComponent = useful.UTCTime() tagMap = { univ.Integer.tagSet: IntegerDecoder(), univ.Boolean.tagSet: BooleanDecoder(), univ.BitString.tagSet: BitStringDecoder(), univ.OctetString.tagSet: OctetStringDecoder(), univ.Null.tagSet: NullDecoder(), univ.ObjectIdentifier.tagSet: ObjectIdentifierDecoder(), univ.Enumerated.tagSet: IntegerDecoder(), univ.Real.tagSet: RealDecoder(), univ.Sequence.tagSet: SequenceDecoder(), # conflicts with SequenceOf univ.Set.tagSet: SetDecoder(), # conflicts with SetOf univ.Choice.tagSet: ChoiceDecoder(), # conflicts with Any # character string types char.UTF8String.tagSet: UTF8StringDecoder(), char.NumericString.tagSet: NumericStringDecoder(), char.PrintableString.tagSet: PrintableStringDecoder(), char.TeletexString.tagSet: TeletexStringDecoder(), char.VideotexString.tagSet: VideotexStringDecoder(), char.IA5String.tagSet: IA5StringDecoder(), char.GraphicString.tagSet: GraphicStringDecoder(), char.VisibleString.tagSet: VisibleStringDecoder(), char.GeneralString.tagSet: GeneralStringDecoder(), char.UniversalString.tagSet: UniversalStringDecoder(), char.BMPString.tagSet: BMPStringDecoder(), # useful types useful.ObjectDescriptor.tagSet: ObjectDescriptorDecoder(), useful.GeneralizedTime.tagSet: GeneralizedTimeDecoder(), useful.UTCTime.tagSet: UTCTimeDecoder() } # Type-to-codec map for ambiguous ASN.1 types typeMap = { univ.Set.typeId: SetDecoder(), univ.SetOf.typeId: SetOfDecoder(), univ.Sequence.typeId: SequenceDecoder(), univ.SequenceOf.typeId: SequenceOfDecoder(), univ.Choice.typeId: ChoiceDecoder(), univ.Any.typeId: AnyDecoder() } ( stDecodeTag, stDecodeLength, stGetValueDecoder, stGetValueDecoderByAsn1Spec, stGetValueDecoderByTag, stTryAsExplicitTag, stDecodeValue, stDumpRawValue, stErrorCondition, stStop ) = [x for x in range(10)] class Decoder: defaultErrorState = stErrorCondition # defaultErrorState = stDumpRawValue defaultRawDecoder = AnyDecoder() supportIndefLength = True def __init__(self, tagMap, typeMap={}): self.__tagMap = tagMap self.__typeMap = typeMap # Tag & TagSet objects caches self.__tagCache = {} self.__tagSetCache = {} def __call__(self, substrate, asn1Spec=None, tagSet=None, length=None, state=stDecodeTag, recursiveFlag=1, substrateFun=None, allowEoo=False): if debug.logger & debug.flagDecoder: debug.logger('decoder called at scope %s with state %d, working with up to %d octets of substrate: %s' % (debug.scope, state, len(substrate), debug.hexdump(substrate))) fullSubstrate = substrate while state != stStop: if state == stDecodeTag: if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on tag decoding' ) if not isOctetsType(substrate) and \ not isinstance(substrate, univ.OctetString): raise error.PyAsn1Error('Bad octet stream type') # Decode tag firstOctet = substrate[0] substrate = substrate[1:] if firstOctet in self.__tagCache: lastTag = self.__tagCache[firstOctet] else: t = oct2int(firstOctet) # Look for end-of-octets sentinel if t == 0: if substrate and oct2int(substrate[0]) == 0: if allowEoo and self.supportIndefLength: debug.logger and debug.logger & debug.flagDecoder and debug.logger('end-of-octets sentinel found') value, substrate = eoo.endOfOctets, substrate[1:] state = stStop continue else: raise error.PyAsn1Error('Unexpected end-of-contents sentinel') else: raise error.PyAsn1Error('Zero tag encountered') tagClass = t&0xC0 tagFormat = t&0x20 tagId = t&0x1F if tagId == 0x1F: tagId = 0 while 1: if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on long tag decoding' ) t = oct2int(substrate[0]) tagId = tagId << 7 | (t&0x7F) substrate = substrate[1:] if not t&0x80: break lastTag = tag.Tag( tagClass=tagClass, tagFormat=tagFormat, tagId=tagId ) if tagId < 31: # cache short tags self.__tagCache[firstOctet] = lastTag if tagSet is None: if firstOctet in self.__tagSetCache: tagSet = self.__tagSetCache[firstOctet] else: # base tag not recovered tagSet = tag.TagSet((), lastTag) if firstOctet in self.__tagCache: self.__tagSetCache[firstOctet] = tagSet else: tagSet = lastTag + tagSet state = stDecodeLength debug.logger and debug.logger & debug.flagDecoder and debug.logger('tag decoded into %s, decoding length' % tagSet) if state == stDecodeLength: # Decode length if not substrate: raise error.SubstrateUnderrunError( 'Short octet stream on length decoding' ) firstOctet = oct2int(substrate[0]) if firstOctet == 128: size = 1 length = -1 elif firstOctet < 128: length, size = firstOctet, 1 else: size = firstOctet & 0x7F # encoded in size bytes length = 0 lengthString = substrate[1:size+1] # missing check on maximum size, which shouldn't be a # problem, we can handle more than is possible if len(lengthString) != size: raise error.SubstrateUnderrunError( '%s<%s at %s' % (size, len(lengthString), tagSet) ) for char in lengthString: length = (length << 8) | oct2int(char) size = size + 1 substrate = substrate[size:] if length != -1 and len(substrate) < length: raise error.SubstrateUnderrunError( '%d-octet short' % (length - len(substrate)) ) if length == -1 and not self.supportIndefLength: error.PyAsn1Error('Indefinite length encoding not supported by this codec') state = stGetValueDecoder debug.logger and debug.logger & debug.flagDecoder and debug.logger('value length decoded into %d, payload substrate is: %s' % (length, debug.hexdump(length == -1 and substrate or substrate[:length]))) if state == stGetValueDecoder: if asn1Spec is None: state = stGetValueDecoderByTag else: state = stGetValueDecoderByAsn1Spec # # There're two ways of creating subtypes in ASN.1 what influences # decoder operation. These methods are: # 1) Either base types used in or no IMPLICIT tagging has been # applied on subtyping. # 2) Subtype syntax drops base type information (by means of # IMPLICIT tagging. # The first case allows for complete tag recovery from substrate # while the second one requires original ASN.1 type spec for # decoding. # # In either case a set of tags (tagSet) is coming from substrate # in an incremental, tag-by-tag fashion (this is the case of # EXPLICIT tag which is most basic). Outermost tag comes first # from the wire. # if state == stGetValueDecoderByTag: if tagSet in self.__tagMap: concreteDecoder = self.__tagMap[tagSet] else: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: _k = tagSet[:1] if _k in self.__tagMap: concreteDecoder = self.__tagMap[_k] else: concreteDecoder = None if concreteDecoder: state = stDecodeValue else: state = stTryAsExplicitTag if debug.logger and debug.logger & debug.flagDecoder: debug.logger('codec %s chosen by a built-in type, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push(concreteDecoder is None and '?' or concreteDecoder.protoComponent.__class__.__name__) if state == stGetValueDecoderByAsn1Spec: if isinstance(asn1Spec, (dict, tagmap.TagMap)): if tagSet in asn1Spec: __chosenSpec = asn1Spec[tagSet] else: __chosenSpec = None if debug.logger and debug.logger & debug.flagDecoder: debug.logger('candidate ASN.1 spec is a map of:') for t, v in asn1Spec.getPosMap().items(): debug.logger(' %s -> %s' % (t, v.__class__.__name__)) if asn1Spec.getNegMap(): debug.logger('but neither of: ') for t, v in asn1Spec.getNegMap().items(): debug.logger(' %s -> %s' % (t, v.__class__.__name__)) debug.logger('new candidate ASN.1 spec is %s, chosen by %s' % (__chosenSpec is None and '<none>' or __chosenSpec.prettyPrintType(), tagSet)) else: __chosenSpec = asn1Spec debug.logger and debug.logger & debug.flagDecoder and debug.logger('candidate ASN.1 spec is %s' % asn1Spec.__class__.__name__) if __chosenSpec is not None and ( tagSet == __chosenSpec.getTagSet() or \ tagSet in __chosenSpec.getTagMap() ): # use base type for codec lookup to recover untagged types baseTagSet = __chosenSpec.baseTagSet if __chosenSpec.typeId is not None and \ __chosenSpec.typeId in self.__typeMap: # ambiguous type concreteDecoder = self.__typeMap[__chosenSpec.typeId] debug.logger and debug.logger & debug.flagDecoder and debug.logger('value decoder chosen for an ambiguous type by type ID %s' % (__chosenSpec.typeId,)) elif baseTagSet in self.__tagMap: # base type or tagged subtype concreteDecoder = self.__tagMap[baseTagSet] debug.logger and debug.logger & debug.flagDecoder and debug.logger('value decoder chosen by base %s' % (baseTagSet,)) else: concreteDecoder = None if concreteDecoder: asn1Spec = __chosenSpec state = stDecodeValue else: state = stTryAsExplicitTag else: concreteDecoder = None state = stTryAsExplicitTag if debug.logger and debug.logger & debug.flagDecoder: debug.logger('codec %s chosen by ASN.1 spec, decoding %s' % (state == stDecodeValue and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as explicit tag')) debug.scope.push(__chosenSpec is None and '?' or __chosenSpec.__class__.__name__) if state == stTryAsExplicitTag: if tagSet and \ tagSet[0][1] == tag.tagFormatConstructed and \ tagSet[0][0] != tag.tagClassUniversal: # Assume explicit tagging concreteDecoder = explicitTagDecoder state = stDecodeValue else: concreteDecoder = None state = self.defaultErrorState debug.logger and debug.logger & debug.flagDecoder and debug.logger('codec %s chosen, decoding %s' % (concreteDecoder and concreteDecoder.__class__.__name__ or "<none>", state == stDecodeValue and 'value' or 'as failure')) if state == stDumpRawValue: concreteDecoder = self.defaultRawDecoder debug.logger and debug.logger & debug.flagDecoder and debug.logger('codec %s chosen, decoding value' % concreteDecoder.__class__.__name__) state = stDecodeValue if state == stDecodeValue: if recursiveFlag == 0 and not substrateFun: # legacy substrateFun = lambda a,b,c: (a,b[:c]) if length == -1: # indef length value, substrate = concreteDecoder.indefLenValueDecoder( fullSubstrate, substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun ) else: value, substrate = concreteDecoder.valueDecoder( fullSubstrate, substrate, asn1Spec, tagSet, length, stGetValueDecoder, self, substrateFun ) state = stStop debug.logger and debug.logger & debug.flagDecoder and debug.logger('codec %s yields type %s, value:\n%s\n...remaining substrate is: %s' % (concreteDecoder.__class__.__name__, value.__class__.__name__, value.prettyPrint(), substrate and debug.hexdump(substrate) or '<none>')) if state == stErrorCondition: raise error.PyAsn1Error( '%s not in asn1Spec: %s' % (tagSet, asn1Spec) ) if debug.logger and debug.logger & debug.flagDecoder: debug.scope.pop() debug.logger('decoder left scope %s, call completed' % debug.scope) return value, substrate decode = Decoder(tagMap, typeMap) # XXX # non-recursive decoding; return position rather than substrate
38,266
Python
.py
796
34.015075
290
0.570943
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,739
eoo.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/ber/eoo.py
from pyasn1.type import base, tag class EndOfOctets(base.AbstractSimpleAsn1Item): defaultValue = 0 tagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x00) ) endOfOctets = EndOfOctets()
237
Python
.py
7
29.285714
65
0.746725
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,740
encoder.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/ber/encoder.py
# BER encoder from pyasn1.type import base, tag, univ, char, useful from pyasn1.codec.ber import eoo from pyasn1.compat.octets import int2oct, oct2int, ints2octs, null, str2octs from pyasn1 import debug, error class Error(Exception): pass class AbstractItemEncoder: supportIndefLenMode = 1 def encodeTag(self, t, isConstructed): tagClass, tagFormat, tagId = t.asTuple() # this is a hotspot v = tagClass | tagFormat if isConstructed: v = v|tag.tagFormatConstructed if tagId < 31: return int2oct(v|tagId) else: s = int2oct(tagId&0x7f) tagId = tagId >> 7 while tagId: s = int2oct(0x80|(tagId&0x7f)) + s tagId = tagId >> 7 return int2oct(v|0x1F) + s def encodeLength(self, length, defMode): if not defMode and self.supportIndefLenMode: return int2oct(0x80) if length < 0x80: return int2oct(length) else: substrate = null while length: substrate = int2oct(length&0xff) + substrate length = length >> 8 substrateLen = len(substrate) if substrateLen > 126: raise Error('Length octets overflow (%d)' % substrateLen) return int2oct(0x80 | substrateLen) + substrate def encodeValue(self, encodeFun, value, defMode, maxChunkSize): raise Error('Not implemented') def _encodeEndOfOctets(self, encodeFun, defMode): if defMode or not self.supportIndefLenMode: return null else: return encodeFun(eoo.endOfOctets, defMode) def encode(self, encodeFun, value, defMode, maxChunkSize): substrate, isConstructed = self.encodeValue( encodeFun, value, defMode, maxChunkSize ) tagSet = value.getTagSet() if tagSet: if not isConstructed: # primitive form implies definite mode defMode = 1 return self.encodeTag( tagSet[-1], isConstructed ) + self.encodeLength( len(substrate), defMode ) + substrate + self._encodeEndOfOctets(encodeFun, defMode) else: return substrate # untagged value class EndOfOctetsEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): return null, 0 class ExplicitlyTaggedItemEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if isinstance(value, base.AbstractConstructedAsn1Item): value = value.clone(tagSet=value.getTagSet()[:-1], cloneValueFlag=1) else: value = value.clone(tagSet=value.getTagSet()[:-1]) return encodeFun(value, defMode, maxChunkSize), 1 explicitlyTaggedItemEncoder = ExplicitlyTaggedItemEncoder() class BooleanEncoder(AbstractItemEncoder): supportIndefLenMode = 0 _true = ints2octs((1,)) _false = ints2octs((0,)) def encodeValue(self, encodeFun, value, defMode, maxChunkSize): return value and self._true or self._false, 0 class IntegerEncoder(AbstractItemEncoder): supportIndefLenMode = 0 supportCompactZero = False def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if value == 0: # shortcut for zero value if self.supportCompactZero: # this seems to be a correct way for encoding zeros return null, 0 else: # this seems to be a widespread way for encoding zeros return ints2octs((0,)), 0 octets = [] value = int(value) # to save on ops on asn1 type while 1: octets.insert(0, value & 0xff) if value == 0 or value == -1: break value = value >> 8 if value == 0 and octets[0] & 0x80: octets.insert(0, 0) while len(octets) > 1 and \ (octets[0] == 0 and octets[1] & 0x80 == 0 or \ octets[0] == 0xff and octets[1] & 0x80 != 0): del octets[0] return ints2octs(octets), 0 class BitStringEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if not maxChunkSize or len(value) <= maxChunkSize*8: out_len = (len(value) + 7) // 8 out_list = out_len * [0] j = 7 i = -1 for val in value: j += 1 if j == 8: i += 1 j = 0 out_list[i] = out_list[i] | val << (7-j) return int2oct(7-j) + ints2octs(out_list), 0 else: pos = 0; substrate = null while 1: # count in octets v = value.clone(value[pos*8:pos*8+maxChunkSize*8]) if not v: break substrate = substrate + encodeFun(v, defMode, maxChunkSize) pos = pos + maxChunkSize return substrate, 1 class OctetStringEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if not maxChunkSize or len(value) <= maxChunkSize: return value.asOctets(), 0 else: pos = 0; substrate = null while 1: v = value.clone(value[pos:pos+maxChunkSize]) if not v: break substrate = substrate + encodeFun(v, defMode, maxChunkSize) pos = pos + maxChunkSize return substrate, 1 class NullEncoder(AbstractItemEncoder): supportIndefLenMode = 0 def encodeValue(self, encodeFun, value, defMode, maxChunkSize): return null, 0 class ObjectIdentifierEncoder(AbstractItemEncoder): supportIndefLenMode = 0 precomputedValues = { (1, 3, 6, 1, 2): (43, 6, 1, 2), (1, 3, 6, 1, 4): (43, 6, 1, 4) } def encodeValue(self, encodeFun, value, defMode, maxChunkSize): oid = value.asTuple() if oid[:5] in self.precomputedValues: octets = self.precomputedValues[oid[:5]] oid = oid[5:] else: if len(oid) < 2: raise error.PyAsn1Error('Short OID %s' % (value,)) octets = () # Build the first twos if oid[0] == 0 and 0 <= oid[1] <= 39: oid = (oid[1],) + oid[2:] elif oid[0] == 1 and 0 <= oid[1] <= 39: oid = (oid[1] + 40,) + oid[2:] elif oid[0] == 2: oid = (oid[1] + 80,) + oid[2:] else: raise error.PyAsn1Error( 'Impossible initial arcs %s at %s' % (oid[:2], value) ) # Cycle through subIds for subId in oid: if subId > -1 and subId < 128: # Optimize for the common case octets = octets + (subId & 0x7f,) elif subId < 0: raise error.PyAsn1Error( 'Negative OID arc %s at %s' % (subId, value) ) else: # Pack large Sub-Object IDs res = (subId & 0x7f,) subId = subId >> 7 while subId > 0: res = (0x80 | (subId & 0x7f),) + res subId = subId >> 7 # Add packed Sub-Object ID to resulted Object ID octets += res return ints2octs(octets), 0 class RealEncoder(AbstractItemEncoder): supportIndefLenMode = 0 binEncBase = 2 # set to None to choose encoding base automatically def _dropFloatingPoint(self, m, encbase, e): ms, es = 1, 1 if m < 0: ms = -1 # mantissa sign if e < 0: es = -1 # exponenta sign m *= ms if encbase == 8: m = m*2**(abs(e) % 3 * es) e = abs(e) // 3 * es elif encbase == 16: m = m*2**(abs(e) % 4 * es) e = abs(e) // 4 * es while 1: if int(m) != m: m *= encbase e -= 1 continue break return ms, int(m), encbase, e def _chooseEncBase(self, value): m, b, e = value base = [2, 8, 16] if value.binEncBase in base: return self._dropFloatingPoint(m, value.binEncBase, e) elif self.binEncBase in base: return self._dropFloatingPoint(m, self.binEncBase, e) # auto choosing base 2/8/16 mantissa = [m, m, m] exponenta = [e, e, e] encbase = 2 e = float('inf') for i in range(3): sign, mantissa[i], base[i], exponenta[i] = \ self._dropFloatingPoint(mantissa[i], base[i], exponenta[i]) if abs(exponenta[i]) < abs(e) or \ (abs(exponenta[i]) == abs(e) and mantissa[i] < m): e = exponenta[i] m = int(mantissa[i]) encbase = base[i] return sign, m, encbase, e def encodeValue(self, encodeFun, value, defMode, maxChunkSize): if value.isPlusInfinity(): return int2oct(0x40), 0 if value.isMinusInfinity(): return int2oct(0x41), 0 m, b, e = value if not m: return null, 0 if b == 10: return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0 elif b == 2: fo = 0x80 # binary encoding ms, m, encbase, e = self._chooseEncBase(value) if ms < 0: # mantissa sign fo = fo | 0x40 # sign bit # exponenta & mantissa normalization if encbase == 2: while m & 0x1 == 0: m >>= 1 e += 1 elif encbase == 8: while m & 0x7 == 0: m >>= 3 e += 1 fo |= 0x10 else: # encbase = 16 while m & 0xf == 0: m >>= 4 e += 1 fo |= 0x20 sf = 0 # scale factor while m & 0x1 == 0: m >>= 1 sf += 1 if sf > 3: raise error.PyAsn1Error('Scale factor overflow') # bug if raised fo |= sf << 2 eo = null if e == 0 or e == -1: eo = int2oct(e&0xff) else: while e not in (0, -1): eo = int2oct(e&0xff) + eo e >>= 8 if e == 0 and eo and oct2int(eo[0]) & 0x80: eo = int2oct(0) + eo if e == -1 and eo and not (oct2int(eo[0]) & 0x80): eo = int2oct(0xff) + eo n = len(eo) if n > 0xff: raise error.PyAsn1Error('Real exponent overflow') if n == 1: pass elif n == 2: fo |= 1 elif n == 3: fo |= 2 else: fo |= 3 eo = int2oct(n&0xff) + eo po = null while m: po = int2oct(m&0xff) + po m >>= 8 substrate = int2oct(fo) + eo + po return substrate, 0 else: raise error.PyAsn1Error('Prohibited Real base %s' % b) class SequenceEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): value.setDefaultComponents() value.verifySizeSpec() substrate = null; idx = len(value) while idx > 0: idx = idx - 1 if value[idx] is None: # Optional component continue component = value.getDefaultComponentByPosition(idx) if component is not None and component == value[idx]: continue substrate = encodeFun( value[idx], defMode, maxChunkSize ) + substrate return substrate, 1 class SequenceOfEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): value.verifySizeSpec() substrate = null; idx = len(value) while idx > 0: idx = idx - 1 substrate = encodeFun( value[idx], defMode, maxChunkSize ) + substrate return substrate, 1 class ChoiceEncoder(AbstractItemEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): return encodeFun(value.getComponent(), defMode, maxChunkSize), 1 class AnyEncoder(OctetStringEncoder): def encodeValue(self, encodeFun, value, defMode, maxChunkSize): return value.asOctets(), defMode == 0 tagMap = { eoo.endOfOctets.tagSet: EndOfOctetsEncoder(), univ.Boolean.tagSet: BooleanEncoder(), univ.Integer.tagSet: IntegerEncoder(), univ.BitString.tagSet: BitStringEncoder(), univ.OctetString.tagSet: OctetStringEncoder(), univ.Null.tagSet: NullEncoder(), univ.ObjectIdentifier.tagSet: ObjectIdentifierEncoder(), univ.Enumerated.tagSet: IntegerEncoder(), univ.Real.tagSet: RealEncoder(), # Sequence & Set have same tags as SequenceOf & SetOf univ.SequenceOf.tagSet: SequenceOfEncoder(), univ.SetOf.tagSet: SequenceOfEncoder(), univ.Choice.tagSet: ChoiceEncoder(), # character string types char.UTF8String.tagSet: OctetStringEncoder(), char.NumericString.tagSet: OctetStringEncoder(), char.PrintableString.tagSet: OctetStringEncoder(), char.TeletexString.tagSet: OctetStringEncoder(), char.VideotexString.tagSet: OctetStringEncoder(), char.IA5String.tagSet: OctetStringEncoder(), char.GraphicString.tagSet: OctetStringEncoder(), char.VisibleString.tagSet: OctetStringEncoder(), char.GeneralString.tagSet: OctetStringEncoder(), char.UniversalString.tagSet: OctetStringEncoder(), char.BMPString.tagSet: OctetStringEncoder(), # useful types useful.ObjectDescriptor.tagSet: OctetStringEncoder(), useful.GeneralizedTime.tagSet: OctetStringEncoder(), useful.UTCTime.tagSet: OctetStringEncoder() } # Type-to-codec map for ambiguous ASN.1 types typeMap = { univ.Set.typeId: SequenceEncoder(), univ.SetOf.typeId: SequenceOfEncoder(), univ.Sequence.typeId: SequenceEncoder(), univ.SequenceOf.typeId: SequenceOfEncoder(), univ.Choice.typeId: ChoiceEncoder(), univ.Any.typeId: AnyEncoder() } class Encoder: supportIndefLength = True def __init__(self, tagMap, typeMap={}): self.__tagMap = tagMap self.__typeMap = typeMap def __call__(self, value, defMode=True, maxChunkSize=0): if not defMode and not self.supportIndefLength: raise error.PyAsn1Error('Indefinite length encoding not supported by this codec') debug.logger & debug.flagEncoder and debug.logger('encoder called in %sdef mode, chunk size %s for type %s, value:\n%s' % (not defMode and 'in' or '', maxChunkSize, value.prettyPrintType(), value.prettyPrint())) tagSet = value.getTagSet() if len(tagSet) > 1: concreteEncoder = explicitlyTaggedItemEncoder else: if value.typeId is not None and value.typeId in self.__typeMap: concreteEncoder = self.__typeMap[value.typeId] elif tagSet in self.__tagMap: concreteEncoder = self.__tagMap[tagSet] else: tagSet = value.baseTagSet if tagSet in self.__tagMap: concreteEncoder = self.__tagMap[tagSet] else: raise Error('No encoder for %s' % (value,)) debug.logger & debug.flagEncoder and debug.logger('using value codec %s chosen by %s' % (concreteEncoder.__class__.__name__, tagSet)) substrate = concreteEncoder.encode( self, value, defMode, maxChunkSize ) debug.logger & debug.flagEncoder and debug.logger('built %s octets of substrate: %s\nencoder completed' % (len(substrate), debug.hexdump(substrate))) return substrate encode = Encoder(tagMap, typeMap)
16,317
Python
.py
401
29.299252
219
0.556878
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,741
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/ber/__init__.py
# This file is necessary to make this directory a package.
59
Python
.py
1
58
58
0.793103
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,742
decoder.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/cer/decoder.py
# CER decoder from pyasn1.type import univ from pyasn1.codec.ber import decoder from pyasn1.compat.octets import oct2int from pyasn1 import error class BooleanDecoder(decoder.AbstractSimpleDecoder): protoComponent = univ.Boolean(0) def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length, state, decodeFun, substrateFun): head, tail = substrate[:length], substrate[length:] if not head: raise error.PyAsn1Error('Empty substrate') byte = oct2int(head[0]) # CER/DER specifies encoding of TRUE as 0xFF and FALSE as 0x0, while # BER allows any non-zero value as TRUE; cf. sections 8.2.2. and 11.1 # in http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf if byte == 0xff: value = 1 elif byte == 0x00: value = 0 else: raise error.PyAsn1Error('Boolean CER violation: %s' % byte) return self._createComponent(asn1Spec, tagSet, value), tail tagMap = decoder.tagMap.copy() tagMap.update({ univ.Boolean.tagSet: BooleanDecoder() }) typeMap = decoder.typeMap class Decoder(decoder.Decoder): pass decode = Decoder(tagMap, decoder.typeMap)
1,230
Python
.py
30
34.3
80
0.683682
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,743
encoder.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/cer/encoder.py
# CER encoder from pyasn1.type import univ from pyasn1.type import useful from pyasn1.codec.ber import encoder from pyasn1.compat.octets import int2oct, str2octs, null from pyasn1 import error class BooleanEncoder(encoder.IntegerEncoder): def encodeValue(self, encodeFun, client, defMode, maxChunkSize): if client == 0: substrate = int2oct(0) else: substrate = int2oct(255) return substrate, 0 class BitStringEncoder(encoder.BitStringEncoder): def encodeValue(self, encodeFun, client, defMode, maxChunkSize): return encoder.BitStringEncoder.encodeValue( self, encodeFun, client, defMode, 1000 ) class OctetStringEncoder(encoder.OctetStringEncoder): def encodeValue(self, encodeFun, client, defMode, maxChunkSize): return encoder.OctetStringEncoder.encodeValue( self, encodeFun, client, defMode, 1000 ) class RealEncoder(encoder.RealEncoder): def _chooseEncBase(self, value): m, b, e = value return self._dropFloatingPoint(m, b, e) # specialized GeneralStringEncoder here class GeneralizedTimeEncoder(OctetStringEncoder): zchar = str2octs('Z') pluschar = str2octs('+') minuschar = str2octs('-') zero = str2octs('0') def encodeValue(self, encodeFun, client, defMode, maxChunkSize): octets = client.asOctets() # This breaks too many existing data items # if '.' not in octets: # raise error.PyAsn1Error('Format must include fraction of second: %r' % octets) if len(octets) < 15: raise error.PyAsn1Error('Bad UTC time length: %r' % octets) if self.pluschar in octets or self.minuschar in octets: raise error.PyAsn1Error('Must be UTC time: %r' % octets) if octets[-1] != self.zchar[0]: raise error.PyAsn1Error('Missing timezone specifier: %r' % octets) return encoder.OctetStringEncoder.encodeValue( self, encodeFun, client, defMode, 1000 ) class UTCTimeEncoder(encoder.OctetStringEncoder): zchar = str2octs('Z') pluschar = str2octs('+') minuschar = str2octs('-') def encodeValue(self, encodeFun, client, defMode, maxChunkSize): octets = client.asOctets() if self.pluschar in octets or self.minuschar in octets: raise error.PyAsn1Error('Must be UTC time: %r' % octets) if octets and octets[-1] != self.zchar[0]: client = client.clone(octets + self.zchar) if len(client) != 13: raise error.PyAsn1Error('Bad UTC time length: %r' % client) return encoder.OctetStringEncoder.encodeValue( self, encodeFun, client, defMode, 1000 ) class SetOfEncoder(encoder.SequenceOfEncoder): def encodeValue(self, encodeFun, client, defMode, maxChunkSize): if isinstance(client, univ.SequenceAndSetBase): client.setDefaultComponents() client.verifySizeSpec() substrate = null; idx = len(client) # This is certainly a hack but how else do I distinguish SetOf # from Set if they have the same tags&constraints? if isinstance(client, univ.SequenceAndSetBase): # Set comps = [] while idx > 0: idx = idx - 1 if client[idx] is None: # Optional component continue if client.getDefaultComponentByPosition(idx) == client[idx]: continue comps.append(client[idx]) comps.sort(key=lambda x: isinstance(x, univ.Choice) and \ x.getMinTagSet() or x.getTagSet()) for c in comps: substrate += encodeFun(c, defMode, maxChunkSize) else: # SetOf compSubs = [] while idx > 0: idx = idx - 1 compSubs.append( encodeFun(client[idx], defMode, maxChunkSize) ) compSubs.sort() # perhaps padding's not needed substrate = null for compSub in compSubs: substrate += compSub return substrate, 1 tagMap = encoder.tagMap.copy() tagMap.update({ univ.Boolean.tagSet: BooleanEncoder(), univ.BitString.tagSet: BitStringEncoder(), univ.OctetString.tagSet: OctetStringEncoder(), univ.Real.tagSet: RealEncoder(), useful.GeneralizedTime.tagSet: GeneralizedTimeEncoder(), useful.UTCTime.tagSet: UTCTimeEncoder(), univ.SetOf().tagSet: SetOfEncoder() # conflcts with Set }) typeMap = encoder.typeMap.copy() typeMap.update({ univ.Set.typeId: SetOfEncoder(), univ.SetOf.typeId: SetOfEncoder() }) class Encoder(encoder.Encoder): def __call__(self, client, defMode=False, maxChunkSize=0): return encoder.Encoder.__call__(self, client, defMode, maxChunkSize) encode = Encoder(tagMap, typeMap) # EncoderFactory queries class instance and builds a map of tags -> encoders
4,998
Python
.py
117
34.179487
91
0.648932
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,744
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/codec/cer/__init__.py
# This file is necessary to make this directory a package.
59
Python
.py
1
58
58
0.793103
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,745
octets.py
CouchPotato_CouchPotatoServer/libs/pyasn1/compat/octets.py
from sys import version_info if version_info[0] <= 2: int2oct = chr ints2octs = lambda s: ''.join([ int2oct(x) for x in s ]) null = '' oct2int = ord octs2ints = lambda s: [ oct2int(x) for x in s ] str2octs = lambda x: x octs2str = lambda x: x isOctetsType = lambda s: isinstance(s, str) else: ints2octs = bytes int2oct = lambda x: ints2octs((x,)) null = ints2octs() oct2int = lambda x: x octs2ints = lambda s: [ x for x in s ] str2octs = lambda x: x.encode() octs2str = lambda x: x.decode() isOctetsType = lambda s: isinstance(s, bytes)
602
Python
.py
19
27.263158
60
0.630584
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,746
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/compat/__init__.py
# This file is necessary to make this directory a package.
59
Python
.py
1
58
58
0.793103
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,747
iterfunc.py
CouchPotato_CouchPotatoServer/libs/pyasn1/compat/iterfunc.py
from sys import version_info if version_info[0] <= 2 and version_info[1] <= 4: def all(iterable): for element in iterable: if not element: return False return True else: all = all
233
Python
.py
9
19
49
0.591928
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,748
binary.py
CouchPotato_CouchPotatoServer/libs/pyasn1/compat/binary.py
from sys import version_info if version_info[0:2] < (2, 6): def bin(x): if x <= 1: return '0b'+str(x) else: return bin(x>>1) + str(x&1) else: bin = bin
201
Python
.py
9
15.888889
39
0.492147
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,749
char.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/char.py
# ASN.1 "character string" types from pyasn1.type import univ, tag class NumericString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 18) ) class PrintableString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 19) ) class TeletexString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 20) ) class T61String(TeletexString): pass class VideotexString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 21) ) class IA5String(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 22) ) class GraphicString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 25) ) class VisibleString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 26) ) class ISO646String(VisibleString): pass class GeneralString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 27) ) class UniversalString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 28) ) encoding = "utf-32-be" class BMPString(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 30) ) encoding = "utf-16-be" class UTF8String(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 12) ) encoding = "utf-8"
2,043
Python
.py
51
34.254902
63
0.738252
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,750
namedtype.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/namedtype.py
# NamedType specification for constructed types import sys from pyasn1.type import tagmap from pyasn1 import error class NamedType: isOptional = 0 isDefaulted = 0 def __init__(self, name, t): self.__name = name; self.__type = t def __repr__(self): return '%s(%r, %r)' % ( self.__class__.__name__, self.__name, self.__type ) def __eq__(self, other): return tuple(self) == tuple(other) def __ne__(self, other): return tuple(self) != tuple(other) def __lt__(self, other): return tuple(self) < tuple(other) def __le__(self, other): return tuple(self) <= tuple(other) def __gt__(self, other): return tuple(self) > tuple(other) def __ge__(self, other): return tuple(self) >= tuple(other) def __hash__(self): return hash(tuple(self)) def getType(self): return self.__type def getName(self): return self.__name def __getitem__(self, idx): if idx == 0: return self.__name if idx == 1: return self.__type raise IndexError() class OptionalNamedType(NamedType): isOptional = 1 class DefaultedNamedType(NamedType): isDefaulted = 1 class NamedTypes: def __init__(self, *namedTypes): self.__namedTypes = namedTypes self.__namedTypesLen = len(self.__namedTypes) self.__minTagSet = None self.__tagToPosIdx = {}; self.__nameToPosIdx = {} self.__tagMap = { False: None, True: None } self.__ambigiousTypes = {} def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, ', '.join([ repr(x) for x in self.__namedTypes ]) ) def __eq__(self, other): return tuple(self) == tuple(other) def __ne__(self, other): return tuple(self) != tuple(other) def __lt__(self, other): return tuple(self) < tuple(other) def __le__(self, other): return tuple(self) <= tuple(other) def __gt__(self, other): return tuple(self) > tuple(other) def __ge__(self, other): return tuple(self) >= tuple(other) def __hash__(self): return hash(tuple(self)) def __getitem__(self, idx): return self.__namedTypes[idx] if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self.__namedTypesLen) else: def __bool__(self): return bool(self.__namedTypesLen) def __len__(self): return self.__namedTypesLen def clone(self): return self.__class__(*self.__namedTypes) def getTypeByPosition(self, idx): if idx < 0 or idx >= self.__namedTypesLen: raise error.PyAsn1Error('Type position out of range') else: return self.__namedTypes[idx].getType() def getPositionByType(self, tagSet): if not self.__tagToPosIdx: idx = self.__namedTypesLen while idx > 0: idx = idx - 1 tagMap = self.__namedTypes[idx].getType().getTagMap() for t in tagMap.getPosMap(): if t in self.__tagToPosIdx: raise error.PyAsn1Error('Duplicate type %s' % (t,)) self.__tagToPosIdx[t] = idx try: return self.__tagToPosIdx[tagSet] except KeyError: raise error.PyAsn1Error('Type %s not found' % (tagSet,)) def getNameByPosition(self, idx): try: return self.__namedTypes[idx].getName() except IndexError: raise error.PyAsn1Error('Type position out of range') def getPositionByName(self, name): if not self.__nameToPosIdx: idx = self.__namedTypesLen while idx > 0: idx = idx - 1 n = self.__namedTypes[idx].getName() if n in self.__nameToPosIdx: raise error.PyAsn1Error('Duplicate name %s' % (n,)) self.__nameToPosIdx[n] = idx try: return self.__nameToPosIdx[name] except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) def __buildAmbigiousTagMap(self): ambigiousTypes = () idx = self.__namedTypesLen while idx > 0: idx = idx - 1 t = self.__namedTypes[idx] if t.isOptional or t.isDefaulted: ambigiousTypes = (t, ) + ambigiousTypes else: ambigiousTypes = (t, ) self.__ambigiousTypes[idx] = NamedTypes(*ambigiousTypes) def getTagMapNearPosition(self, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return self.__ambigiousTypes[idx].getTagMap() except KeyError: raise error.PyAsn1Error('Type position out of range') def getPositionNearType(self, tagSet, idx): if not self.__ambigiousTypes: self.__buildAmbigiousTagMap() try: return idx+self.__ambigiousTypes[idx].getPositionByType(tagSet) except KeyError: raise error.PyAsn1Error('Type position out of range') def genMinTagSet(self): if self.__minTagSet is None: for t in self.__namedTypes: __type = t.getType() tagSet = getattr(__type,'getMinTagSet',__type.getTagSet)() if self.__minTagSet is None or tagSet < self.__minTagSet: self.__minTagSet = tagSet return self.__minTagSet def getTagMap(self, uniq=False): if self.__tagMap[uniq] is None: tagMap = tagmap.TagMap() for nt in self.__namedTypes: tagMap = tagMap.clone( nt.getType(), nt.getType().getTagMap(), uniq ) self.__tagMap[uniq] = tagMap return self.__tagMap[uniq]
5,725
Python
.py
133
33.022556
75
0.578215
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,751
namedval.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/namedval.py
# ASN.1 named integers from pyasn1 import error __all__ = [ 'NamedValues' ] class NamedValues: def __init__(self, *namedValues): self.nameToValIdx = {}; self.valToNameIdx = {} self.namedValues = () automaticVal = 1 for namedValue in namedValues: if isinstance(namedValue, tuple): name, val = namedValue else: name = namedValue val = automaticVal if name in self.nameToValIdx: raise error.PyAsn1Error('Duplicate name %s' % (name,)) self.nameToValIdx[name] = val if val in self.valToNameIdx: raise error.PyAsn1Error('Duplicate value %s=%s' % (name, val)) self.valToNameIdx[val] = name self.namedValues = self.namedValues + ((name, val),) automaticVal = automaticVal + 1 def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join([repr(x) for x in self.namedValues])) def __str__(self): return str(self.namedValues) def __eq__(self, other): return tuple(self) == tuple(other) def __ne__(self, other): return tuple(self) != tuple(other) def __lt__(self, other): return tuple(self) < tuple(other) def __le__(self, other): return tuple(self) <= tuple(other) def __gt__(self, other): return tuple(self) > tuple(other) def __ge__(self, other): return tuple(self) >= tuple(other) def __hash__(self): return hash(tuple(self)) def getName(self, value): if value in self.valToNameIdx: return self.valToNameIdx[value] def getValue(self, name): if name in self.nameToValIdx: return self.nameToValIdx[name] def __getitem__(self, i): return self.namedValues[i] def __len__(self): return len(self.namedValues) def __add__(self, namedValues): return self.__class__(*self.namedValues + namedValues) def __radd__(self, namedValues): return self.__class__(*namedValues + tuple(self)) def clone(self, *namedValues): return self.__class__(*tuple(self) + namedValues) # XXX clone/subtype?
2,163
Python
.py
47
36.87234
99
0.600287
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,752
univ.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/univ.py
# ASN.1 "universal" data types import operator, sys, math from pyasn1.type import base, tag, constraint, namedtype, namedval, tagmap from pyasn1.codec.ber import eoo from pyasn1.compat import octets from pyasn1 import error # "Simple" ASN.1 types (yet incomplete) class Integer(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02) ) namedValues = namedval.NamedValues() def __init__(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if namedValues is None: self.__namedValues = self.namedValues else: self.__namedValues = namedValues base.AbstractSimpleAsn1Item.__init__( self, value, tagSet, subtypeSpec ) def __repr__(self): if self.__namedValues is not self.namedValues: return '%s, %r)' % (base.AbstractSimpleAsn1Item.__repr__(self)[:-1], self.__namedValues) else: return base.AbstractSimpleAsn1Item.__repr__(self) def __and__(self, value): return self.clone(self._value & value) def __rand__(self, value): return self.clone(value & self._value) def __or__(self, value): return self.clone(self._value | value) def __ror__(self, value): return self.clone(value | self._value) def __xor__(self, value): return self.clone(self._value ^ value) def __rxor__(self, value): return self.clone(value ^ self._value) def __lshift__(self, value): return self.clone(self._value << value) def __rshift__(self, value): return self.clone(self._value >> value) def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __sub__(self, value): return self.clone(self._value - value) def __rsub__(self, value): return self.clone(value - self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self.clone(value * self._value) def __mod__(self, value): return self.clone(self._value % value) def __rmod__(self, value): return self.clone(value % self._value) def __pow__(self, value, modulo=None): return self.clone(pow(self._value, value, modulo)) def __rpow__(self, value): return self.clone(pow(value, self._value)) if sys.version_info[0] <= 2: def __div__(self, value): return self.clone(self._value // value) def __rdiv__(self, value): return self.clone(value // self._value) else: def __truediv__(self, value): return self.clone(self._value / value) def __rtruediv__(self, value): return self.clone(value / self._value) def __divmod__(self, value): return self.clone(self._value // value) def __rdivmod__(self, value): return self.clone(value // self._value) __hash__ = base.AbstractSimpleAsn1Item.__hash__ def __int__(self): return int(self._value) if sys.version_info[0] <= 2: def __long__(self): return long(self._value) def __float__(self): return float(self._value) def __abs__(self): return self.clone(abs(self._value)) def __index__(self): return int(self._value) def __pos__(self): return self.clone(+self._value) def __neg__(self): return self.clone(-self._value) def __invert__(self): return self.clone(~self._value) def __round__(self, n=0): r = round(self._value, n) if n: return self.clone(r) else: return r def __floor__(self): return math.floor(self._value) def __ceil__(self): return math.ceil(self._value) if sys.version_info[0:2] > (2, 5): def __trunc__(self): return self.clone(math.trunc(self._value)) def __lt__(self, value): return self._value < value def __le__(self, value): return self._value <= value def __eq__(self, value): return self._value == value def __ne__(self, value): return self._value != value def __gt__(self, value): return self._value > value def __ge__(self, value): return self._value >= value def prettyIn(self, value): if not isinstance(value, str): try: return int(value) except: raise error.PyAsn1Error( 'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1]) ) r = self.__namedValues.getValue(value) if r is not None: return r try: return int(value) except: raise error.PyAsn1Error( 'Can\'t coerce %r into integer: %s' % (value, sys.exc_info()[1]) ) def prettyOut(self, value): r = self.__namedValues.getName(value) return r is None and str(value) or repr(r) def getNamedValues(self): return self.__namedValues def clone(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if value is None and tagSet is None and subtypeSpec is None \ and namedValues is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def subtype(self, value=None, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None): if value is None: value = self._value if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec if namedValues is None: namedValues = self.__namedValues else: namedValues = namedValues + self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) class Boolean(Integer): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01), ) subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(0,1) namedValues = Integer.namedValues.clone(('False', 0), ('True', 1)) class BitString(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03) ) namedValues = namedval.NamedValues() def __init__(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if namedValues is None: self.__namedValues = self.namedValues else: self.__namedValues = namedValues base.AbstractSimpleAsn1Item.__init__( self, value, tagSet, subtypeSpec ) def clone(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if value is None and tagSet is None and subtypeSpec is None \ and namedValues is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if namedValues is None: namedValues = self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def subtype(self, value=None, implicitTag=None, explicitTag=None, subtypeSpec=None, namedValues=None): if value is None: value = self._value if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec if namedValues is None: namedValues = self.__namedValues else: namedValues = namedValues + self.__namedValues return self.__class__(value, tagSet, subtypeSpec, namedValues) def __str__(self): return str(tuple(self)) # Immutable sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + value) def __radd__(self, value): return self.clone(value + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value def prettyIn(self, value): r = [] if not value: return () elif isinstance(value, str): if value[0] == '\'': if value[-2:] == '\'B': for v in value[1:-2]: if v == '0': r.append(0) elif v == '1': r.append(1) else: raise error.PyAsn1Error( 'Non-binary BIT STRING initializer %s' % (v,) ) return tuple(r) elif value[-2:] == '\'H': for v in value[1:-2]: i = 4 v = int(v, 16) while i: i = i - 1 r.append((v>>i)&0x01) return tuple(r) else: raise error.PyAsn1Error( 'Bad BIT STRING value notation %s' % (value,) ) else: for i in value.split(','): j = self.__namedValues.getValue(i) if j is None: raise error.PyAsn1Error( 'Unknown bit identifier \'%s\'' % (i,) ) if j >= len(r): r.extend([0]*(j-len(r)+1)) r[j] = 1 return tuple(r) elif isinstance(value, (tuple, list)): r = tuple(value) for b in r: if b and b != 1: raise error.PyAsn1Error( 'Non-binary BitString initializer \'%s\'' % (r,) ) return r elif isinstance(value, BitString): return tuple(value) else: raise error.PyAsn1Error( 'Bad BitString initializer type \'%s\'' % (value,) ) def prettyOut(self, value): return '\"\'%s\'B\"' % ''.join([str(x) for x in value]) try: all except NameError: # Python 2.4 def all(iterable): for element in iterable: if not element: return False return True class OctetString(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04) ) defaultBinValue = defaultHexValue = base.noValue encoding = 'us-ascii' def __init__(self, value=None, tagSet=None, subtypeSpec=None, encoding=None, binValue=None, hexValue=None): if encoding is None: self._encoding = self.encoding else: self._encoding = encoding if binValue is not None: value = self.fromBinaryString(binValue) if hexValue is not None: value = self.fromHexString(hexValue) if value is None or value is base.noValue: value = self.defaultHexValue if value is None or value is base.noValue: value = self.defaultBinValue self.__asNumbersCache = None base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec) def clone(self, value=None, tagSet=None, subtypeSpec=None, encoding=None, binValue=None, hexValue=None): if value is None and tagSet is None and subtypeSpec is None and \ encoding is None and binValue is None and hexValue is None: return self if value is None and binValue is None and hexValue is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if encoding is None: encoding = self._encoding return self.__class__( value, tagSet, subtypeSpec, encoding, binValue, hexValue ) if sys.version_info[0] <= 2: def prettyIn(self, value): if isinstance(value, str): return value elif isinstance(value, unicode): try: return value.encode(self._encoding) except (LookupError, UnicodeEncodeError): raise error.PyAsn1Error( 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding) ) elif isinstance(value, (tuple, list)): try: return ''.join([ chr(x) for x in value ]) except ValueError: raise error.PyAsn1Error( 'Bad OctetString initializer \'%s\'' % (value,) ) else: return str(value) else: def prettyIn(self, value): if isinstance(value, bytes): return value elif isinstance(value, str): try: return value.encode(self._encoding) except UnicodeEncodeError: raise error.PyAsn1Error( 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding) ) elif isinstance(value, OctetString): return value.asOctets() elif isinstance(value, (tuple, list, map)): try: return bytes(value) except ValueError: raise error.PyAsn1Error( 'Bad OctetString initializer \'%s\'' % (value,) ) else: try: return str(value).encode(self._encoding) except UnicodeEncodeError: raise error.PyAsn1Error( 'Can\'t encode string \'%s\' with \'%s\' codec' % (value, self._encoding) ) def fromBinaryString(self, value): bitNo = 8; byte = 0; r = () for v in value: if bitNo: bitNo = bitNo - 1 else: bitNo = 7 r = r + (byte,) byte = 0 if v == '0': v = 0 elif v == '1': v = 1 else: raise error.PyAsn1Error( 'Non-binary OCTET STRING initializer %s' % (v,) ) byte = byte | (v << bitNo) return octets.ints2octs(r + (byte,)) def fromHexString(self, value): r = p = () for v in value: if p: r = r + (int(p+v, 16),) p = () else: p = v if p: r = r + (int(p+'0', 16),) return octets.ints2octs(r) def prettyOut(self, value): if sys.version_info[0] <= 2: numbers = tuple(( ord(x) for x in value )) else: numbers = tuple(value) if all(x >= 32 and x <= 126 for x in numbers): return str(value) else: return '0x' + ''.join(( '%.2x' % x for x in numbers )) def __repr__(self): r = [] doHex = False if self._value is not self.defaultValue: for x in self.asNumbers(): if x < 32 or x > 126: doHex = True break if not doHex: r.append('%r' % (self._value,)) if self._tagSet is not self.tagSet: r.append('tagSet=%r' % (self._tagSet,)) if self._subtypeSpec is not self.subtypeSpec: r.append('subtypeSpec=%r' % (self._subtypeSpec,)) if self.encoding is not self._encoding: r.append('encoding=%r' % (self._encoding,)) if doHex: r.append('hexValue=%r' % ''.join([ '%.2x' % x for x in self.asNumbers() ])) return '%s(%s)' % (self.__class__.__name__, ', '.join(r)) if sys.version_info[0] <= 2: def __str__(self): return str(self._value) def __unicode__(self): return self._value.decode(self._encoding, 'ignore') def asOctets(self): return self._value def asNumbers(self): if self.__asNumbersCache is None: self.__asNumbersCache = tuple([ ord(x) for x in self._value ]) return self.__asNumbersCache else: def __str__(self): return self._value.decode(self._encoding, 'ignore') def __bytes__(self): return self._value def asOctets(self): return self._value def asNumbers(self): if self.__asNumbersCache is None: self.__asNumbersCache = tuple(self._value) return self.__asNumbersCache # Immutable sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone(operator.getitem(self._value, i)) else: return self._value[i] def __add__(self, value): return self.clone(self._value + self.prettyIn(value)) def __radd__(self, value): return self.clone(self.prettyIn(value) + self._value) def __mul__(self, value): return self.clone(self._value * value) def __rmul__(self, value): return self * value def __int__(self): return int(self._value) def __float__(self): return float(self._value) class Null(OctetString): defaultValue = ''.encode() # This is tightly constrained tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05) ) subtypeSpec = OctetString.subtypeSpec+constraint.SingleValueConstraint(''.encode()) if sys.version_info[0] <= 2: intTypes = (int, long) else: intTypes = (int,) numericTypes = intTypes + (float,) class ObjectIdentifier(base.AbstractSimpleAsn1Item): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06) ) def __add__(self, other): return self.clone(self._value + other) def __radd__(self, other): return self.clone(other + self._value) def asTuple(self): return self._value # Sequence object protocol def __len__(self): if self._len is None: self._len = len(self._value) return self._len def __getitem__(self, i): if isinstance(i, slice): return self.clone( operator.getitem(self._value, i) ) else: return self._value[i] def __str__(self): return self.prettyPrint() def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.prettyPrint()) def index(self, suboid): return self._value.index(suboid) def isPrefixOf(self, value): """Returns true if argument OID resides deeper in the OID tree""" l = len(self) if l <= len(value): if self._value[:l] == value[:l]: return 1 return 0 def prettyIn(self, value): """Dotted -> tuple of numerics OID converter""" if isinstance(value, tuple): pass elif isinstance(value, ObjectIdentifier): return tuple(value) elif isinstance(value, str): r = [] for element in [ x for x in value.split('.') if x != '' ]: try: r.append(int(element, 0)) except ValueError: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__, sys.exc_info()[1]) ) value = tuple(r) else: try: value = tuple(value) except TypeError: raise error.PyAsn1Error( 'Malformed Object ID %s at %s: %s' % (str(value), self.__class__.__name__,sys.exc_info()[1]) ) for x in value: if not isinstance(x, intTypes) or x < 0: raise error.PyAsn1Error( 'Invalid sub-ID in %s at %s' % (value, self.__class__.__name__) ) return value def prettyOut(self, value): return '.'.join([ str(x) for x in value ]) class Real(base.AbstractSimpleAsn1Item): binEncBase = None # binEncBase = 16 is recommended for large numbers try: _plusInf = float('inf') _minusInf = float('-inf') _inf = (_plusInf, _minusInf) except ValueError: # Infinity support is platform and Python dependent _plusInf = _minusInf = None _inf = () tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09) ) def __normalizeBase10(self, value): m, b, e = value while m and m % 10 == 0: m = m / 10 e = e + 1 return m, b, e def prettyIn(self, value): if isinstance(value, tuple) and len(value) == 3: if not isinstance(value[0], numericTypes) or \ not isinstance(value[1], intTypes) or \ not isinstance(value[2], intTypes): raise error.PyAsn1Error('Lame Real value syntax: %s' % (value,)) if isinstance(value[0], float) and \ self._inf and value[0] in self._inf: return value[0] if value[1] not in (2, 10): raise error.PyAsn1Error( 'Prohibited base for Real value: %s' % (value[1],) ) if value[1] == 10: value = self.__normalizeBase10(value) return value elif isinstance(value, intTypes): return self.__normalizeBase10((value, 10, 0)) elif isinstance(value, (str, float)): if isinstance(value, str): try: value = float(value) except ValueError: raise error.PyAsn1Error( 'Bad real value syntax: %s' % (value,) ) if self._inf and value in self._inf: return value else: e = 0 while int(value) != value: value = value * 10 e = e - 1 return self.__normalizeBase10((int(value), 10, e)) elif isinstance(value, Real): return tuple(value) raise error.PyAsn1Error( 'Bad real value syntax: %s' % (value,) ) def prettyOut(self, value): if value in self._inf: return '\'%s\'' % value else: return str(value) def prettyPrint(self, scope=0): if self.isInfinity(): return self.prettyOut(self._value) else: return str(float(self)) def isPlusInfinity(self): return self._value == self._plusInf def isMinusInfinity(self): return self._value == self._minusInf def isInfinity(self): return self._value in self._inf def __str__(self): return str(float(self)) def __add__(self, value): return self.clone(float(self) + value) def __radd__(self, value): return self + value def __mul__(self, value): return self.clone(float(self) * value) def __rmul__(self, value): return self * value def __sub__(self, value): return self.clone(float(self) - value) def __rsub__(self, value): return self.clone(value - float(self)) def __mod__(self, value): return self.clone(float(self) % value) def __rmod__(self, value): return self.clone(value % float(self)) def __pow__(self, value, modulo=None): return self.clone(pow(float(self), value, modulo)) def __rpow__(self, value): return self.clone(pow(value, float(self))) if sys.version_info[0] <= 2: def __div__(self, value): return self.clone(float(self) / value) def __rdiv__(self, value): return self.clone(value / float(self)) else: def __truediv__(self, value): return self.clone(float(self) / value) def __rtruediv__(self, value): return self.clone(value / float(self)) def __divmod__(self, value): return self.clone(float(self) // value) def __rdivmod__(self, value): return self.clone(value // float(self)) def __int__(self): return int(float(self)) if sys.version_info[0] <= 2: def __long__(self): return long(float(self)) def __float__(self): if self._value in self._inf: return self._value else: return float( self._value[0] * pow(self._value[1], self._value[2]) ) def __abs__(self): return self.clone(abs(float(self))) def __pos__(self): return self.clone(+float(self)) def __neg__(self): return self.clone(-float(self)) def __round__(self, n=0): r = round(float(self), n) if n: return self.clone(r) else: return r def __floor__(self): return self.clone(math.floor(float(self))) def __ceil__(self): return self.clone(math.ceil(float(self))) if sys.version_info[0:2] > (2, 5): def __trunc__(self): return self.clone(math.trunc(float(self))) def __lt__(self, value): return float(self) < value def __le__(self, value): return float(self) <= value def __eq__(self, value): return float(self) == value def __ne__(self, value): return float(self) != value def __gt__(self, value): return float(self) > value def __ge__(self, value): return float(self) >= value if sys.version_info[0] <= 2: def __nonzero__(self): return bool(float(self)) else: def __bool__(self): return bool(float(self)) __hash__ = base.AbstractSimpleAsn1Item.__hash__ def __getitem__(self, idx): if self._value in self._inf: raise error.PyAsn1Error('Invalid infinite value operation') else: return self._value[idx] class Enumerated(Integer): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A) ) # "Structured" ASN.1 types class SetOf(base.AbstractConstructedAsn1Item): componentType = None tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) typeId = 1 strictConstraints = False def _cloneComponentValues(self, myClone, cloneValueFlag): idx = 0; l = len(self._componentValues) while idx < l: c = self._componentValues[idx] if c is not None: if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByPosition( idx, c.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByPosition(idx, c.clone()) idx = idx + 1 def _verifyComponent(self, idx, value): t = self._componentType if t is None: return if not t.isSameTypeWith(value,matchConstraints=self.strictConstraints): raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, t)) if self.strictConstraints and \ not t.isSuperTypeOf(value, matchTags=False): raise error.PyAsn1Error('Component value is constraints-incompatible: %r vs %r' % (value, t)) def getComponentByPosition(self, idx): return self._componentValues[idx] def setComponentByPosition(self, idx, value=None, verifyConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx-l+1)*[None] if value is None: if self._componentValues[idx] is None: if self._componentType is None: raise error.PyAsn1Error('Component type not defined') self._componentValues[idx] = self._componentType.clone() self._componentValuesSet = self._componentValuesSet + 1 return self elif not isinstance(value, base.Asn1Item): if self._componentType is None: raise error.PyAsn1Error('Component type not defined') if isinstance(self._componentType, base.AbstractSimpleAsn1Item): value = self._componentType.clone(value=value) else: raise error.PyAsn1Error('Instance value required') if verifyConstraints: if self._componentType is not None: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) if self._componentValues[idx] is None: self._componentValuesSet = self._componentValuesSet + 1 self._componentValues[idx] = value return self def getComponentTagMap(self): if self._componentType is not None: return self._componentType.getTagMap() def prettyPrint(self, scope=0): scope = scope + 1 r = self.__class__.__name__ + ':\n' for idx in range(len(self._componentValues)): r = r + ' '*scope if self._componentValues[idx] is None: r = r + '<empty>' else: r = r + self._componentValues[idx].prettyPrint(scope) return r def prettyPrintType(self, scope=0): scope = scope + 1 r = '%s -> %s {\n' % (self.getTagSet(), self.__class__.__name__) if self._componentType is not None: r = r + ' '*scope r = r + self._componentType.prettyPrintType(scope) return r + '\n' + ' '*(scope-1) + '}' class SequenceOf(SetOf): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10) ) typeId = 2 class SequenceAndSetBase(base.AbstractConstructedAsn1Item): componentType = namedtype.NamedTypes() strictConstraints = False def __init__(self, componentType=None, tagSet=None, subtypeSpec=None, sizeSpec=None): if componentType is None: componentType = self.componentType base.AbstractConstructedAsn1Item.__init__( self, componentType.clone(), tagSet, subtypeSpec, sizeSpec ) self._componentTypeLen = len(self._componentType) def __getitem__(self, idx): if isinstance(idx, str): return self.getComponentByName(idx) else: return base.AbstractConstructedAsn1Item.__getitem__(self, idx) def __setitem__(self, idx, value): if isinstance(idx, str): self.setComponentByName(idx, value) else: base.AbstractConstructedAsn1Item.__setitem__(self, idx, value) def _cloneComponentValues(self, myClone, cloneValueFlag): idx = 0; l = len(self._componentValues) while idx < l: c = self._componentValues[idx] if c is not None: if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByPosition( idx, c.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByPosition(idx, c.clone()) idx = idx + 1 def _verifyComponent(self, idx, value): if idx >= self._componentTypeLen: raise error.PyAsn1Error( 'Component type error out of range' ) t = self._componentType[idx].getType() if not t.isSameTypeWith(value,matchConstraints=self.strictConstraints): raise error.PyAsn1Error('Component value is tag-incompatible: %r vs %r' % (value, t)) if self.strictConstraints and \ not t.isSuperTypeOf(value, matchTags=False): raise error.PyAsn1Error('Component value is constraints-incompatible: %r vs %r' % (value, t)) def getComponentByName(self, name): return self.getComponentByPosition( self._componentType.getPositionByName(name) ) def setComponentByName(self, name, value=None, verifyConstraints=True): return self.setComponentByPosition( self._componentType.getPositionByName(name),value,verifyConstraints ) def getComponentByPosition(self, idx): try: return self._componentValues[idx] except IndexError: if idx < self._componentTypeLen: return raise def setComponentByPosition(self, idx, value=None, verifyConstraints=True, exactTypes=False, matchTags=True, matchConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx-l+1)*[None] if value is None: if self._componentValues[idx] is None: self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone() self._componentValuesSet = self._componentValuesSet + 1 return self elif not isinstance(value, base.Asn1Item): t = self._componentType.getTypeByPosition(idx) if isinstance(t, base.AbstractSimpleAsn1Item): value = t.clone(value=value) else: raise error.PyAsn1Error('Instance value required') if verifyConstraints: if self._componentTypeLen: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) if self._componentValues[idx] is None: self._componentValuesSet = self._componentValuesSet + 1 self._componentValues[idx] = value return self def getNameByPosition(self, idx): if self._componentTypeLen: return self._componentType.getNameByPosition(idx) def getDefaultComponentByPosition(self, idx): if self._componentTypeLen and self._componentType[idx].isDefaulted: return self._componentType[idx].getType() def getComponentType(self): if self._componentTypeLen: return self._componentType def setDefaultComponents(self): if self._componentTypeLen == self._componentValuesSet: return idx = self._componentTypeLen while idx: idx = idx - 1 if self._componentType[idx].isDefaulted: if self.getComponentByPosition(idx) is None: self.setComponentByPosition(idx) elif not self._componentType[idx].isOptional: if self.getComponentByPosition(idx) is None: raise error.PyAsn1Error( 'Uninitialized component #%s at %r' % (idx, self) ) def prettyPrint(self, scope=0): scope = scope + 1 r = self.__class__.__name__ + ':\n' for idx in range(len(self._componentValues)): if self._componentValues[idx] is not None: r = r + ' '*scope componentType = self.getComponentType() if componentType is None: r = r + '<no-name>' else: r = r + componentType.getNameByPosition(idx) r = '%s=%s\n' % ( r, self._componentValues[idx].prettyPrint(scope) ) return r def prettyPrintType(self, scope=0): scope = scope + 1 r = '%s -> %s {\n' % (self.getTagSet(), self.__class__.__name__) for idx in range(len(self.componentType)): r = r + ' '*scope r = r + '"%s"' % self.componentType.getNameByPosition(idx) r = '%s = %s\n' % ( r, self._componentType.getTypeByPosition(idx).prettyPrintType(scope) ) return r + '\n' + ' '*(scope-1) + '}' class Sequence(SequenceAndSetBase): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x10) ) typeId = 3 def getComponentTagMapNearPosition(self, idx): if self._componentType: return self._componentType.getTagMapNearPosition(idx) def getComponentPositionNearType(self, tagSet, idx): if self._componentType: return self._componentType.getPositionNearType(tagSet, idx) else: return idx class Set(SequenceAndSetBase): tagSet = baseTagSet = tag.initTagSet( tag.Tag(tag.tagClassUniversal, tag.tagFormatConstructed, 0x11) ) typeId = 4 def getComponent(self, innerFlag=0): return self def getComponentByType(self, tagSet, innerFlag=0): c = self.getComponentByPosition( self._componentType.getPositionByType(tagSet) ) if innerFlag and isinstance(c, Set): # get inner component by inner tagSet return c.getComponent(1) else: # get outer component by inner tagSet return c def setComponentByType(self, tagSet, value=None, innerFlag=0, verifyConstraints=True): idx = self._componentType.getPositionByType(tagSet) t = self._componentType.getTypeByPosition(idx) if innerFlag: # set inner component by inner tagSet if t.getTagSet(): return self.setComponentByPosition( idx, value, verifyConstraints ) else: t = self.setComponentByPosition(idx).getComponentByPosition(idx) return t.setComponentByType( tagSet, value, innerFlag, verifyConstraints ) else: # set outer component by inner tagSet return self.setComponentByPosition( idx, value, verifyConstraints ) def getComponentTagMap(self): if self._componentType: return self._componentType.getTagMap(True) def getComponentPositionByType(self, tagSet): if self._componentType: return self._componentType.getPositionByType(tagSet) class Choice(Set): tagSet = baseTagSet = tag.TagSet() # untagged sizeSpec = constraint.ConstraintsIntersection( constraint.ValueSizeConstraint(1, 1) ) typeId = 5 _currentIdx = None def __eq__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] == other return NotImplemented def __ne__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] != other return NotImplemented def __lt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] < other return NotImplemented def __le__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] <= other return NotImplemented def __gt__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] > other return NotImplemented def __ge__(self, other): if self._componentValues: return self._componentValues[self._currentIdx] >= other return NotImplemented if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._componentValues) else: def __bool__(self): return bool(self._componentValues) def __len__(self): return self._currentIdx is not None and 1 or 0 def verifySizeSpec(self): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: self._sizeSpec(' ') def _cloneComponentValues(self, myClone, cloneValueFlag): try: c = self.getComponent() except error.PyAsn1Error: pass else: if isinstance(c, Choice): tagSet = c.getEffectiveTagSet() else: tagSet = c.getTagSet() if isinstance(c, base.AbstractConstructedAsn1Item): myClone.setComponentByType( tagSet, c.clone(cloneValueFlag=cloneValueFlag) ) else: myClone.setComponentByType(tagSet, c.clone()) def setComponentByPosition(self, idx, value=None, verifyConstraints=True): l = len(self._componentValues) if idx >= l: self._componentValues = self._componentValues + (idx-l+1)*[None] if self._currentIdx is not None: self._componentValues[self._currentIdx] = None if value is None: if self._componentValues[idx] is None: self._componentValues[idx] = self._componentType.getTypeByPosition(idx).clone() self._componentValuesSet = 1 self._currentIdx = idx return self elif not isinstance(value, base.Asn1Item): value = self._componentType.getTypeByPosition(idx).clone( value=value ) if verifyConstraints: if self._componentTypeLen: self._verifyComponent(idx, value) self._verifySubtypeSpec(value, idx) self._componentValues[idx] = value self._currentIdx = idx self._componentValuesSet = 1 return self def getMinTagSet(self): if self._tagSet: return self._tagSet else: return self._componentType.genMinTagSet() def getEffectiveTagSet(self): if self._tagSet: return self._tagSet else: c = self.getComponent() if isinstance(c, Choice): return c.getEffectiveTagSet() else: return c.getTagSet() def getTagMap(self): if self._tagSet: return Set.getTagMap(self) else: return Set.getComponentTagMap(self) def getComponent(self, innerFlag=0): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if innerFlag and isinstance(c, Choice): return c.getComponent(innerFlag) else: return c def getName(self, innerFlag=0): if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) return self._componentType.getNameByPosition(self._currentIdx) def setDefaultComponents(self): pass class Any(OctetString): tagSet = baseTagSet = tag.TagSet() # untagged typeId = 6 def getTagMap(self): return tagmap.TagMap( { self.getTagSet(): self }, { eoo.endOfOctets.getTagSet(): eoo.endOfOctets }, self ) # XXX # coercion rules?
44,619
Python
.py
1,044
31.054598
105
0.565776
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,753
constraint.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/constraint.py
# # ASN.1 subtype constraints classes. # # Constraints are relatively rare, but every ASN1 object # is doing checks all the time for whether they have any # constraints and whether they are applicable to the object. # # What we're going to do is define objects/functions that # can be called unconditionally if they are present, and that # are simply not present if there are no constraints. # # Original concept and code by Mike C. Fletcher. # import sys from pyasn1.type import error class AbstractConstraint: """Abstract base-class for constraint objects Constraints should be stored in a simple sequence in the namespace of their client Asn1Item sub-classes. """ def __init__(self, *values): self._valueMap = {} self._setValues(values) self.__hashedValues = None def __call__(self, value, idx=None): try: self._testValue(value, idx) except error.ValueConstraintError: raise error.ValueConstraintError( '%s failed at: \"%s\"' % (self, sys.exc_info()[1]) ) def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, ', '.join([repr(x) for x in self._values]) ) def __eq__(self, other): return self is other and True or self._values == other def __ne__(self, other): return self._values != other def __lt__(self, other): return self._values < other def __le__(self, other): return self._values <= other def __gt__(self, other): return self._values > other def __ge__(self, other): return self._values >= other if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._values) else: def __bool__(self): return bool(self._values) def __hash__(self): if self.__hashedValues is None: self.__hashedValues = hash((self.__class__.__name__, self._values)) return self.__hashedValues def _setValues(self, values): self._values = values def _testValue(self, value, idx): raise error.ValueConstraintError(value) # Constraints derivation logic def getValueMap(self): return self._valueMap def isSuperTypeOf(self, otherConstraint): return self in otherConstraint.getValueMap() or \ otherConstraint is self or otherConstraint == self def isSubTypeOf(self, otherConstraint): return otherConstraint in self._valueMap or \ otherConstraint is self or otherConstraint == self class SingleValueConstraint(AbstractConstraint): """Value must be part of defined values constraint""" def _testValue(self, value, idx): # XXX index vals for performance? if value not in self._values: raise error.ValueConstraintError(value) class ContainedSubtypeConstraint(AbstractConstraint): """Value must satisfy all of defined set of constraints""" def _testValue(self, value, idx): for c in self._values: c(value, idx) class ValueRangeConstraint(AbstractConstraint): """Value must be within start and stop values (inclusive)""" def _testValue(self, value, idx): if value < self.start or value > self.stop: raise error.ValueConstraintError(value) def _setValues(self, values): if len(values) != 2: raise error.PyAsn1Error( '%s: bad constraint values' % (self.__class__.__name__,) ) self.start, self.stop = values if self.start > self.stop: raise error.PyAsn1Error( '%s: screwed constraint values (start > stop): %s > %s' % ( self.__class__.__name__, self.start, self.stop ) ) AbstractConstraint._setValues(self, values) class ValueSizeConstraint(ValueRangeConstraint): """len(value) must be within start and stop values (inclusive)""" def _testValue(self, value, idx): l = len(value) if l < self.start or l > self.stop: raise error.ValueConstraintError(value) class PermittedAlphabetConstraint(SingleValueConstraint): def _setValues(self, values): self._values = () for v in values: self._values = self._values + tuple(v) def _testValue(self, value, idx): for v in value: if v not in self._values: raise error.ValueConstraintError(value) # This is a bit kludgy, meaning two op modes within a single constraing class InnerTypeConstraint(AbstractConstraint): """Value must satisfy type and presense constraints""" def _testValue(self, value, idx): if self.__singleTypeConstraint: self.__singleTypeConstraint(value) elif self.__multipleTypeConstraint: if idx not in self.__multipleTypeConstraint: raise error.ValueConstraintError(value) constraint, status = self.__multipleTypeConstraint[idx] if status == 'ABSENT': # XXX presense is not checked! raise error.ValueConstraintError(value) constraint(value) def _setValues(self, values): self.__multipleTypeConstraint = {} self.__singleTypeConstraint = None for v in values: if isinstance(v, tuple): self.__multipleTypeConstraint[v[0]] = v[1], v[2] else: self.__singleTypeConstraint = v AbstractConstraint._setValues(self, values) # Boolean ops on constraints class ConstraintsExclusion(AbstractConstraint): """Value must not fit the single constraint""" def _testValue(self, value, idx): try: self._values[0](value, idx) except error.ValueConstraintError: return else: raise error.ValueConstraintError(value) def _setValues(self, values): if len(values) != 1: raise error.PyAsn1Error('Single constraint expected') AbstractConstraint._setValues(self, values) class AbstractConstraintSet(AbstractConstraint): """Value must not satisfy the single constraint""" def __getitem__(self, idx): return self._values[idx] def __add__(self, value): return self.__class__(self, value) def __radd__(self, value): return self.__class__(self, value) def __len__(self): return len(self._values) # Constraints inclusion in sets def _setValues(self, values): self._values = values for v in values: self._valueMap[v] = 1 self._valueMap.update(v.getValueMap()) class ConstraintsIntersection(AbstractConstraintSet): """Value must satisfy all constraints""" def _testValue(self, value, idx): for v in self._values: v(value, idx) class ConstraintsUnion(AbstractConstraintSet): """Value must satisfy at least one constraint""" def _testValue(self, value, idx): for v in self._values: try: v(value, idx) except error.ValueConstraintError: pass else: return raise error.ValueConstraintError( 'all of %s failed for \"%s\"' % (self._values, value) ) # XXX # add tests for type check
7,279
Python
.py
175
33.274286
79
0.632234
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,754
__init__.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/__init__.py
# This file is necessary to make this directory a package.
59
Python
.py
1
58
58
0.793103
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,755
base.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/base.py
# Base classes for ASN.1 types import sys from pyasn1.type import constraint, tagmap, tag from pyasn1 import error class Asn1Item: pass class Asn1ItemBase(Asn1Item): # Set of tags for this ASN.1 type tagSet = tag.TagSet() # A list of constraint.Constraint instances for checking values subtypeSpec = constraint.ConstraintsIntersection() # Used for ambiguous ASN.1 types identification typeId = None def __init__(self, tagSet=None, subtypeSpec=None): if tagSet is None: self._tagSet = self.tagSet else: self._tagSet = tagSet if subtypeSpec is None: self._subtypeSpec = self.subtypeSpec else: self._subtypeSpec = subtypeSpec def _verifySubtypeSpec(self, value, idx=None): try: self._subtypeSpec(value, idx) except error.PyAsn1Error: c, i, t = sys.exc_info() raise c('%s at %s' % (i, self.__class__.__name__)) def getSubtypeSpec(self): return self._subtypeSpec def getTagSet(self): return self._tagSet def getEffectiveTagSet(self): return self._tagSet # used by untagged types def getTagMap(self): return tagmap.TagMap({self._tagSet: self}) def isSameTypeWith(self, other, matchTags=True, matchConstraints=True): return self is other or \ (not matchTags or \ self._tagSet == other.getTagSet()) and \ (not matchConstraints or \ self._subtypeSpec==other.getSubtypeSpec()) def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True): """Returns true if argument is a ASN1 subtype of ourselves""" return (not matchTags or \ self._tagSet.isSuperTagSetOf(other.getTagSet())) and \ (not matchConstraints or \ (self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec()))) class NoValue: def __getattr__(self, attr): raise error.PyAsn1Error('No value for %s()' % attr) def __getitem__(self, i): raise error.PyAsn1Error('No value') def __repr__(self): return '%s()' % self.__class__.__name__ noValue = NoValue() # Base class for "simple" ASN.1 objects. These are immutable. class AbstractSimpleAsn1Item(Asn1ItemBase): defaultValue = noValue def __init__(self, value=None, tagSet=None, subtypeSpec=None): Asn1ItemBase.__init__(self, tagSet, subtypeSpec) if value is None or value is noValue: value = self.defaultValue if value is None or value is noValue: self.__hashedValue = value = noValue else: value = self.prettyIn(value) self._verifySubtypeSpec(value) self.__hashedValue = hash(value) self._value = value self._len = None def __repr__(self): r = [] if self._value is not self.defaultValue: r.append(self.prettyOut(self._value)) if self._tagSet is not self.tagSet: r.append('tagSet=%r' % (self._tagSet,)) if self._subtypeSpec is not self.subtypeSpec: r.append('subtypeSpec=%r' % (self._subtypeSpec,)) return '%s(%s)' % (self.__class__.__name__, ', '.join(r)) def __str__(self): return str(self._value) def __eq__(self, other): return self is other and True or self._value == other def __ne__(self, other): return self._value != other def __lt__(self, other): return self._value < other def __le__(self, other): return self._value <= other def __gt__(self, other): return self._value > other def __ge__(self, other): return self._value >= other if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._value) else: def __bool__(self): return bool(self._value) def __hash__(self): return self.__hashedValue def hasValue(self): return not isinstance(self._value, NoValue) def clone(self, value=None, tagSet=None, subtypeSpec=None): if value is None and tagSet is None and subtypeSpec is None: return self if value is None: value = self._value if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec return self.__class__(value, tagSet, subtypeSpec) def subtype(self, value=None, implicitTag=None, explicitTag=None, subtypeSpec=None): if value is None: value = self._value if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec return self.__class__(value, tagSet, subtypeSpec) def prettyIn(self, value): return value def prettyOut(self, value): return str(value) def prettyPrint(self, scope=0): if self.hasValue(): return self.prettyOut(self._value) else: return '<no value>' # XXX Compatibility stub def prettyPrinter(self, scope=0): return self.prettyPrint(scope) def prettyPrintType(self, scope=0): return '%s -> %s' % (self.getTagSet(), self.__class__.__name__) # # Constructed types: # * There are five of them: Sequence, SequenceOf/SetOf, Set and Choice # * ASN1 types and values are represened by Python class instances # * Value initialization is made for defaulted components only # * Primary method of component addressing is by-position. Data model for base # type is Python sequence. Additional type-specific addressing methods # may be implemented for particular types. # * SequenceOf and SetOf types do not implement any additional methods # * Sequence, Set and Choice types also implement by-identifier addressing # * Sequence, Set and Choice types also implement by-asn1-type (tag) addressing # * Sequence and Set types may include optional and defaulted # components # * Constructed types hold a reference to component types used for value # verification and ordering. # * Component type is a scalar type for SequenceOf/SetOf types and a list # of types for Sequence/Set/Choice. # class AbstractConstructedAsn1Item(Asn1ItemBase): componentType = None sizeSpec = constraint.ConstraintsIntersection() def __init__(self, componentType=None, tagSet=None, subtypeSpec=None, sizeSpec=None): Asn1ItemBase.__init__(self, tagSet, subtypeSpec) if componentType is None: self._componentType = self.componentType else: self._componentType = componentType if sizeSpec is None: self._sizeSpec = self.sizeSpec else: self._sizeSpec = sizeSpec self._componentValues = [] self._componentValuesSet = 0 def __repr__(self): r = [] if self._componentType is not self.componentType: r.append('componentType=%r' % (self._componentType,)) if self._tagSet is not self.tagSet: r.append('tagSet=%r' % (self._tagSet,)) if self._subtypeSpec is not self.subtypeSpec: r.append('subtypeSpec=%r' % (self._subtypeSpec,)) r = '%s(%s)' % (self.__class__.__name__, ', '.join(r)) if self._componentValues: r += '.setComponents(%s)' % ', '.join([repr(x) for x in self._componentValues]) return r def __eq__(self, other): return self is other and True or self._componentValues == other def __ne__(self, other): return self._componentValues != other def __lt__(self, other): return self._componentValues < other def __le__(self, other): return self._componentValues <= other def __gt__(self, other): return self._componentValues > other def __ge__(self, other): return self._componentValues >= other if sys.version_info[0] <= 2: def __nonzero__(self): return bool(self._componentValues) else: def __bool__(self): return bool(self._componentValues) def getComponentTagMap(self): raise error.PyAsn1Error('Method not implemented') def _cloneComponentValues(self, myClone, cloneValueFlag): pass def clone(self, tagSet=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): if tagSet is None: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec if sizeSpec is None: sizeSpec = self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def subtype(self, implicitTag=None, explicitTag=None, subtypeSpec=None, sizeSpec=None, cloneValueFlag=None): if implicitTag is not None: tagSet = self._tagSet.tagImplicitly(implicitTag) elif explicitTag is not None: tagSet = self._tagSet.tagExplicitly(explicitTag) else: tagSet = self._tagSet if subtypeSpec is None: subtypeSpec = self._subtypeSpec else: subtypeSpec = subtypeSpec + self._subtypeSpec if sizeSpec is None: sizeSpec = self._sizeSpec else: sizeSpec = sizeSpec + self._sizeSpec r = self.__class__(self._componentType, tagSet, subtypeSpec, sizeSpec) if cloneValueFlag: self._cloneComponentValues(r, cloneValueFlag) return r def _verifyComponent(self, idx, value): pass def verifySizeSpec(self): self._sizeSpec(self) def getComponentByPosition(self, idx): raise error.PyAsn1Error('Method not implemented') def setComponentByPosition(self, idx, value, verifyConstraints=True): raise error.PyAsn1Error('Method not implemented') def setComponents(self, *args, **kwargs): for idx in range(len(args)): self[idx] = args[idx] for k in kwargs: self[k] = kwargs[k] return self def getComponentType(self): return self._componentType def setDefaultComponents(self): pass def __getitem__(self, idx): return self.getComponentByPosition(idx) def __setitem__(self, idx, value): self.setComponentByPosition(idx, value) def __len__(self): return len(self._componentValues) def clear(self): self._componentValues = [] self._componentValuesSet = 0
10,647
Python
.py
237
36.459916
91
0.64265
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,756
tag.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/tag.py
# ASN.1 types tags from operator import getitem from pyasn1 import error tagClassUniversal = 0x00 tagClassApplication = 0x40 tagClassContext = 0x80 tagClassPrivate = 0xC0 tagFormatSimple = 0x00 tagFormatConstructed = 0x20 tagCategoryImplicit = 0x01 tagCategoryExplicit = 0x02 tagCategoryUntagged = 0x04 class Tag: def __init__(self, tagClass, tagFormat, tagId): if tagId < 0: raise error.PyAsn1Error( 'Negative tag ID (%s) not allowed' % (tagId,) ) self.__tag = (tagClass, tagFormat, tagId) self.uniq = (tagClass, tagId) self.__hashedUniqTag = hash(self.uniq) def __str__(self): return '[%s:%s:%s]' % self.__tag def __repr__(self): return '%s(tagClass=%s, tagFormat=%s, tagId=%s)' % ( (self.__class__.__name__,) + self.__tag ) # These is really a hotspot -- expose public "uniq" attribute to save on # function calls def __eq__(self, other): return self.uniq == other.uniq def __ne__(self, other): return self.uniq != other.uniq def __lt__(self, other): return self.uniq < other.uniq def __le__(self, other): return self.uniq <= other.uniq def __gt__(self, other): return self.uniq > other.uniq def __ge__(self, other): return self.uniq >= other.uniq def __hash__(self): return self.__hashedUniqTag def __getitem__(self, idx): return self.__tag[idx] def __and__(self, otherTag): (tagClass, tagFormat, tagId) = otherTag return self.__class__( self.__tag&tagClass, self.__tag&tagFormat, self.__tag&tagId ) def __or__(self, otherTag): (tagClass, tagFormat, tagId) = otherTag return self.__class__( self.__tag[0]|tagClass, self.__tag[1]|tagFormat, self.__tag[2]|tagId ) def asTuple(self): return self.__tag # __getitem__() is slow class TagSet: def __init__(self, baseTag=(), *superTags): self.__baseTag = baseTag self.__superTags = superTags self.__hashedSuperTags = hash(superTags) _uniq = () for t in superTags: _uniq = _uniq + t.uniq self.uniq = _uniq self.__lenOfSuperTags = len(superTags) def __str__(self): return self.__superTags and '+'.join([str(x) for x in self.__superTags]) or '[untagged]' def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, '(), ' + ', '.join([repr(x) for x in self.__superTags]) ) def __add__(self, superTag): return self.__class__( self.__baseTag, *self.__superTags + (superTag,) ) def __radd__(self, superTag): return self.__class__( self.__baseTag, *(superTag,) + self.__superTags ) def tagExplicitly(self, superTag): tagClass, tagFormat, tagId = superTag if tagClass == tagClassUniversal: raise error.PyAsn1Error( 'Can\'t tag with UNIVERSAL-class tag' ) if tagFormat != tagFormatConstructed: superTag = Tag(tagClass, tagFormatConstructed, tagId) return self + superTag def tagImplicitly(self, superTag): tagClass, tagFormat, tagId = superTag if self.__superTags: superTag = Tag(tagClass, self.__superTags[-1][1], tagId) return self[:-1] + superTag def getBaseTag(self): return self.__baseTag def __getitem__(self, idx): if isinstance(idx, slice): return self.__class__( self.__baseTag, *getitem(self.__superTags, idx) ) return self.__superTags[idx] def __eq__(self, other): return self.uniq == other.uniq def __ne__(self, other): return self.uniq != other.uniq def __lt__(self, other): return self.uniq < other.uniq def __le__(self, other): return self.uniq <= other.uniq def __gt__(self, other): return self.uniq > other.uniq def __ge__(self, other): return self.uniq >= other.uniq def __hash__(self): return self.__hashedSuperTags def __len__(self): return self.__lenOfSuperTags def isSuperTagSetOf(self, tagSet): if len(tagSet) < self.__lenOfSuperTags: return idx = self.__lenOfSuperTags - 1 while idx >= 0: if self.__superTags[idx] != tagSet[idx]: return idx = idx - 1 return 1 def initTagSet(tag): return TagSet(tag, tag)
4,499
Python
.py
114
31.219298
96
0.582531
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,757
useful.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/useful.py
# ASN.1 "useful" types from pyasn1.type import char, tag class ObjectDescriptor(char.GraphicString): tagSet = char.GraphicString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7) ) class GeneralizedTime(char.VisibleString): tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24) ) class UTCTime(char.VisibleString): tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23) )
565
Python
.py
14
34.857143
63
0.74635
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,758
tagmap.py
CouchPotato_CouchPotatoServer/libs/pyasn1/type/tagmap.py
from pyasn1 import error class TagMap: def __init__(self, posMap={}, negMap={}, defType=None): self.__posMap = posMap.copy() self.__negMap = negMap.copy() self.__defType = defType def __contains__(self, tagSet): return tagSet in self.__posMap or \ self.__defType is not None and tagSet not in self.__negMap def __getitem__(self, tagSet): if tagSet in self.__posMap: return self.__posMap[tagSet] elif tagSet in self.__negMap: raise error.PyAsn1Error('Key in negative map') elif self.__defType is not None: return self.__defType else: raise KeyError() def __repr__(self): s = self.__class__.__name__ + '(' if self.__posMap: s = s + 'posMap=%r, ' % (self.__posMap,) if self.__negMap: s = s + 'negMap=%r, ' % (self.__negMap,) if self.__defType is not None: s = s + 'defType=%r' % (self.__defType,) return s + ')' def __str__(self): s = self.__class__.__name__ + ':\n' if self.__posMap: s = s + 'posMap:\n%s, ' % ',\n '.join([ x.prettyPrintType() for x in self.__posMap.values()]) if self.__negMap: s = s + 'negMap:\n%s, ' % ',\n '.join([ x.prettyPrintType() for x in self.__negMap.values()]) if self.__defType is not None: s = s + 'defType:\n%s, ' % self.__defType.prettyPrintType() return s def clone(self, parentType, tagMap, uniq=False): if self.__defType is not None and tagMap.getDef() is not None: raise error.PyAsn1Error('Duplicate default value at %s' % (self,)) if tagMap.getDef() is not None: defType = tagMap.getDef() else: defType = self.__defType posMap = self.__posMap.copy() for k in tagMap.getPosMap(): if uniq and k in posMap: raise error.PyAsn1Error('Duplicate positive key %s' % (k,)) posMap[k] = parentType negMap = self.__negMap.copy() negMap.update(tagMap.getNegMap()) return self.__class__( posMap, negMap, defType, ) def getPosMap(self): return self.__posMap.copy() def getNegMap(self): return self.__negMap.copy() def getDef(self): return self.__defType
2,392
Python
.py
56
32.482143
105
0.543951
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,759
_version.py
CouchPotato_CouchPotatoServer/libs/oauth2/_version.py
# This is the version of this source code. manual_verstr = "1.5" auto_build_num = "211" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as distutils_Version __version__ = distutils_Version(verstr)
438
Python
.py
11
36.363636
67
0.740476
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,760
__init__.py
CouchPotato_CouchPotatoServer/libs/oauth2/__init__.py
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import base64 import urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs parse_qs # placate pyflakes except ImportError: # fall back for Python 2.5 from cgi import parse_qs try: from hashlib import sha1 sha = sha1 except ImportError: # hashlib was added in Python 2.5 import sha import _version __version__ = _version.__version__ OAUTH_VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occurred.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def build_xoauth_string(url, consumer, token=None): """Build an XOAUTH string for use in SMTP/IMPA authentication.""" request = Request.from_consumer_and_token(consumer, token, "GET", url) signing_method = SignatureMethod_HMAC_SHA1() request.sign_request(signing_method, consumer, token) params = [] for k, v in sorted(request.iteritems()): if v is not None: params.append('%s="%s"' % (k, escape(v))) return "%s %s %s" % ("GET", url, ','.join(params)) def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, unicode): if not isinstance(s, str): raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s)) try: s = s.decode('utf-8') except UnicodeDecodeError, le: raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,)) return s def to_utf8(s): return to_unicode(s).encode('utf-8') def to_unicode_if_string(s): if isinstance(s, basestring): return to_unicode(s) else: return s def to_utf8_if_string(s): if isinstance(s, basestring): return to_utf8(s) else: return s def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, basestring): return to_unicode(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_unicode(e) for e in l ] def to_utf8_optional_iterator(x): """ Raise TypeError if x is a str or if x is an iterable which contains a str. """ if isinstance(x, basestring): return to_utf8(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_utf8_if_string(e) for e in l ] def escape(s): """Escape a URL including any /.""" return urllib.quote(s.encode('utf-8'), safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ version = OAUTH_VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None, body='', is_form_encoded=False): if url is not None: self.url = to_unicode(url) self.method = method if parameters is not None: for k, v in parameters.iteritems(): k = to_unicode(k) v = to_unicode_optional_iterator(v) self[k] = v self.body = body self.is_form_encoded = is_form_encoded @setter def url(self, value): self.__dict__['url'] = value if value is not None: scheme, netloc, path, params, query, fragment = urlparse.urlparse(value) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme not in ('http', 'https'): raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) # Normalized URL excludes params, query, and fragment. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None)) else: self.normalized_url = None self.__dict__['url'] = None @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" d = {} for k, v in self.iteritems(): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(d, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: # must be python <2.5 query = base_url[4] query = parse_qs(query) for k, v in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc path = base_url.path params = base_url.params fragment = base_url.fragment except AttributeError: # must be python <2.5 scheme = base_url[0] netloc = base_url[1] path = base_url[2] params = base_url[3] fragment = base_url[5] url = (scheme, netloc, path, params, urllib.urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.iteritems(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if isinstance(value, basestring): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeError, e: assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value) # Include any query string parameters from the provided URL query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() encoded_str = urllib.urlencode(items) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None, body='', is_form_encoded=False): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier return Request(http_method, http_url, parameters, body=body, is_form_encoded=is_form_encoded) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body='', headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded' if not isinstance(headers, dict): headers = {} if method == "POST": headers['Content-Type'] = headers.get('Content-Type', DEFAULT_POST_CONTENT_TYPE) is_form_encoded = \ headers.get('Content-Type') == 'application/x-www-form-urlencoded' if is_form_encoded and body: parameters = parse_qs(body) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=is_form_encoded) req.sign_request(self.method, self.consumer, self.token) schema, rest = urllib.splittype(uri) if rest.startswith('//'): hierpart = '//' else: hierpart = '' host, rest = urllib.splithost(rest) realm = schema + ':' + hierpart + host if is_form_encoded: body = req.to_postdata() elif method == "GET": uri = req.to_url() else: headers.update(req.to_header(realm=realm)) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = OAUTH_VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _check_version(self, request): """Verify the correct version of the request for this server.""" version = self._get_version(request) if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) def _get_version(self, request): """Return the version of the request for this server.""" try: version = request.get_parameter('oauth_version') except: version = OAUTH_VERSION return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
29,044
Python
.py
667
34.547226
265
0.629476
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,761
imap.py
CouchPotato_CouchPotatoServer/libs/oauth2/clients/imap.py
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import imaplib class IMAP4_SSL(imaplib.IMAP4_SSL): """IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', lambda x: oauth2.build_xoauth_string(url, consumer, token))
1,685
Python
.py
30
52.566667
78
0.776292
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,762
smtp.py
CouchPotato_CouchPotatoServer/libs/oauth2/clients/smtp.py
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
1,680
Python
.py
31
50.677419
79
0.773642
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,763
remotes.py
CouchPotato_CouchPotatoServer/libs/git/remotes.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from . import branch from . import ref_container class Remote(ref_container.RefContainer): def __init__(self, repo, name, url): super(Remote, self).__init__() self.repo = repo self.name = name self.url = url def fetch(self): self.repo._executeGitCommandAssertSuccess("fetch %s" % self.name) def prune(self): self.repo._executeGitCommandAssertSuccess("remote prune %s" % self.name) def __eq__(self, other): return (type(self) is type(other)) and (self.name == other.name) ###################### For compatibility with RefContainer ##################### def getBranches(self): prefix = "%s/" % self.name returned = [] for line in self.repo._getOutputAssertSuccess("branch -r").splitlines(): if self.repo.getGitVersion() >= '1.6.3' and ' -> ' in line: continue line = line.strip() if line.startswith(prefix): returned.append(branch.RegisteredRemoteBranch(self.repo, self, line[len(prefix):])) return returned
2,614
Python
.py
49
48.632653
99
0.702302
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,764
repository.py
CouchPotato_CouchPotatoServer/libs/git/repository.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import Sequence import re import os import subprocess import sys from . import branch from . import tag from . import commit from . import config from .files import ModifiedFile from . import ref from . import ref_container from . import remotes from .utils import quote_for_shell from .utils import CommandString as CMD #exceptions from .exceptions import CannotFindRepository from .exceptions import GitException from .exceptions import GitCommandFailedException from .exceptions import MergeConflict from .exceptions import NonexistentRefException BRANCH_ALIAS_MARKER = ' -> ' class Repository(ref_container.RefContainer): _git_command = None def setCommand(self, command): self._git_command = command ############################# internal methods ############################# _loggingEnabled = False def _getWorkingDirectory(self): return '.' def _logGitCommand(self, command, cwd): if self._loggingEnabled: print >> sys.stderr, ">>", command def enableLogging(self): self._loggingEnabled = True def disableLogging(self): self._loggingEnabled = False def _executeGitCommand(self, command, cwd = None): if cwd is None: cwd = self._getWorkingDirectory() command = '%s %s' % (self._git_command, str(command)) self._logGitCommand(command, cwd) returned = subprocess.Popen(command, shell = True, cwd = cwd, stdout = subprocess.PIPE, stderr = subprocess.PIPE) returned.wait() return returned def _executeGitCommandAssertSuccess(self, command, **kwargs): returned = self._executeGitCommand(command, **kwargs) assert returned.returncode is not None if returned.returncode != 0: raise GitCommandFailedException(kwargs.get('cwd', self._getWorkingDirectory()), command, returned) return returned def _getOutputAssertSuccess(self, command, **kwargs): return self._executeGitCommandAssertSuccess(command, **kwargs).stdout.read() def _getMergeBase(self, a, b): raise NotImplementedError() def getMergeBase(self, a, b): repo = self if isinstance(b, commit.Commit) and isinstance(b.repo, LocalRepository): repo = b.repo elif isinstance(a, commit.Commit) and isinstance(a.repo, LocalRepository): repo = a.repo return repo._getMergeBase(a, b) ############################## remote repositories ############################# class RemoteRepository(Repository): def __init__(self, url, command = 'git'): self.setCommand(command) super(RemoteRepository, self).__init__() self.url = url def _getRefs(self, prefix = ''): output = self._executeGitCommandAssertSuccess("ls-remote %s" % (self.url,)) for output_line in output.stdout: commit, refname = output_line.split() if refname.startswith(prefix): yield refname[len(prefix):], commit.strip() def _getRefsAsClass(self, prefix, cls): return [cls(self, ref) for ref, _ in self._getRefs(prefix)] def _getCommitByRefName(self, refname): sha_by_ref = dict(self._getRefs()) for prefix in 'refs/tags/', 'refs/heads/': sha = sha_by_ref.get(prefix + refname, None) if sha is not None: return commit.Commit(self, sha) raise NonexistentRefException("Cannot find ref name %r in %s" % (refname, self)) def getBranches(self): return self._getRefsAsClass('refs/heads/', branch.RemoteBranch) def getTags(self): return self._getRefsAsClass('refs/tags/', tag.RemoteTag) ############################## local repositories ############################## class LocalRepository(Repository): def __init__(self, path, command = 'git'): self.setCommand(command) super(LocalRepository, self).__init__() self.path = path self.config = config.GitConfiguration(self) self._version = None def __repr__(self): return "<Git Repository at %s>" % (self.path,) def _getWorkingDirectory(self): return self.path def _getCommitByHash(self, sha): return commit.Commit(self, sha) def _getCommitByRefName(self, name): return commit.Commit(self, self._getOutputAssertSuccess("rev-parse %s" % name).strip()) def _getCommitByPartialHash(self, sha): return self._getCommitByRefName(sha) def getGitVersion(self): if self._version is None: version_output = self._getOutputAssertSuccess("version") version_match = re.match(r"git\s+version\s+(\S+)[\s\(]?", version_output, re.I) if version_match is None: raise GitException("Cannot extract git version (unfamiliar output format %r?)" % version_output) self._version = version_match.group(1) return self._version ########################### Initializing a repository ########################## def init(self, bare = False): if not os.path.exists(self.path): os.mkdir(self.path) if not os.path.isdir(self.path): raise GitException("Cannot create repository in %s - " "not a directory" % self.path) self._executeGitCommandAssertSuccess("init %s" % ("--bare" if bare else "")) def _asURL(self, repo): if isinstance(repo, LocalRepository): repo = repo.path elif isinstance(repo, RemoteRepository): repo = repo.url elif not isinstance(repo, basestring): raise TypeError("Cannot clone from %r" % (repo,)) return repo def clone(self, repo): self._executeGitCommandAssertSuccess("clone %s %s" % (self._asURL(repo), self.path), cwd = ".") ########################### Querying repository refs ########################### def getBranches(self): returned = [] for git_branch_line in self._executeGitCommandAssertSuccess("branch").stdout: if git_branch_line.startswith("*"): git_branch_line = git_branch_line[1:] git_branch_line = git_branch_line.strip() if BRANCH_ALIAS_MARKER in git_branch_line: alias_name, aliased = git_branch_line.split(BRANCH_ALIAS_MARKER) returned.append(branch.LocalBranchAlias(self, alias_name, aliased)) else: returned.append(branch.LocalBranch(self, git_branch_line)) return returned def getTags(self): returned = [] for git_tag_line in self._executeGitCommandAssertSuccess("tag").stdout: returned.append(tag.LocalTag(self, git_tag_line.strip())) return returned def _getCommits(self, specs, includeMerges): command = "log --pretty=format:%%H %s" % specs if not includeMerges: command += " --no-merges" for c in self._executeGitCommandAssertSuccess(command).stdout: yield commit.Commit(self, c.strip()) def getCommits(self, start = None, end = "HEAD", includeMerges = True): spec = self._normalizeRefName(start or "") spec += ".." spec += self._normalizeRefName(end) return list(self._getCommits(spec, includeMerges = includeMerges)) def getCurrentBranch(self): #todo: improve this method of obtaining current branch for branch_name in self._executeGitCommandAssertSuccess("branch").stdout: branch_name = branch_name.strip() if not branch_name.startswith("*"): continue branch_name = branch_name[1:].strip() if branch_name == '(no branch)': return None return self.getBranchByName(branch_name) def getRemotes(self): config_dict = self.config.getDict() returned = [] for line in self._getOutputAssertSuccess("remote show -n").splitlines(): line = line.strip() returned.append(remotes.Remote(self, line, config_dict.get('remote.%s.url' % line.strip()))) return returned def getRemoteByName(self, name): return self._getByName(self.getRemotes, name) def _getMergeBase(self, a, b): if isinstance(a, ref.Ref): a = a.getHead() if isinstance(b, ref.Ref): b = b.getHead() returned = self._executeGitCommand("merge-base %s %s" % (a, b)) if returned.returncode == 0: return commit.Commit(self, returned.stdout.read().strip()) # make sure this is not a misc. error with git unused = self.getHead() return None ################################ Querying Status ############################### def containsCommit(self, commit): try: self._executeGitCommandAssertSuccess("log -1 %s" % (commit,)) except GitException: return False return True def getHead(self): return self._getCommitByRefName("HEAD") def _getFiles(self, *flags): flags = ["--exclude-standard"] + list(flags) return [f.strip() for f in self._getOutputAssertSuccess("ls-files %s" % (" ".join(flags))).splitlines()] def _getRawDiff(self, *flags, **options): match_statuses = options.pop('fileStatuses', None) if match_statuses is not None and not isinstance(match_statuses, Sequence): raise ValueError("matchedStatuses must be a sequence") if options: raise TypeError("Unknown arguments specified: %s" % ", ".join(options)) flags = " ".join(str(f) for f in flags) modified_files = [] for line in self._getOutputAssertSuccess("diff --raw %s" % flags).splitlines(): file_status = line.split()[-2] file_name = line.split()[-1] if match_statuses is None or file_status in match_statuses: modified_files.append(ModifiedFile(file_name)) return modified_files def getStagedFiles(self): if self.isInitialized(): return self._getRawDiff('--cached') return self._getFiles() def getUnchangedFiles(self): return self._getFiles() def getChangedFiles(self): return self._getRawDiff() def getDeletedFiles(self): return self._getRawDiff(fileStatuses = ['D']) def getUntrackedFiles(self): return self._getFiles("--others") def isInitialized(self): try: self.getHead() return True except GitException: return False def isValid(self): return os.path.isdir(os.path.join(self.path, ".git")) or \ (os.path.isfile(os.path.join(self.path, "HEAD")) and os.path.isdir(os.path.join(self.path, "objects"))) def isWorkingDirectoryClean(self): return not (self.getUntrackedFiles() or self.getChangedFiles() or self.getStagedFiles()) def __contains__(self, thing): if isinstance(thing, basestring) or isinstance(thing, commit.Commit): return self.containsCommit(thing) raise NotImplementedError() ################################ Staging content ############################### def add(self, path): self._executeGitCommandAssertSuccess("add %s" % quote_for_shell(path)) def delete(self, path, recursive = False, force = False): flags = "" if recursive: flags += "-r " if force: flags += "-f " self._executeGitCommandAssertSuccess("rm %s%s" % (flags, quote_for_shell(path))) def addAll(self): return self.add('.') ################################## Committing ################################## def _normalizeRefName(self, thing): if isinstance(thing, ref.Ref): thing = thing.getNormalizedName() return str(thing) def _deduceNewCommitFromCommitOutput(self, output): for pattern in [ # new-style commit pattern r"^\[\S+\s+(?:\(root-commit\)\s+)?(\S+)\]", ]: match = re.search(pattern, output) if match: return commit.Commit(self, match.group(1)) return None def commit(self, message, allowEmpty = False, commitAll = False): args = '' if commitAll: args = args + '--all' command = "commit %s -m %s" % (args, quote_for_shell(message)) if allowEmpty: command += " --allow-empty" output = self._getOutputAssertSuccess(command) return self._deduceNewCommitFromCommitOutput(output) ################################ Changing state ################################ def _createBranchOrTag(self, objname, name, startingPoint, returned_class): command = "%s %s " % (objname, name) if startingPoint is not None: command += self._normalizeRefName(startingPoint) self._executeGitCommandAssertSuccess(command) return returned_class(self, name) def createBranch(self, name, startingPoint = None): return self._createBranchOrTag('branch', name, startingPoint, branch.LocalBranch) def createTag(self, name, startingPoint = None): return self._createBranchOrTag('tag', name, startingPoint, tag.LocalTag) def checkout(self, thing = None, targetBranch = None, files = ()): if thing is None: thing = "" command = "checkout %s" % (self._normalizeRefName(thing),) if targetBranch is not None: command += " -b %s" % (targetBranch,) if files: command += " -- %s" % " ".join(files) self._executeGitCommandAssertSuccess(command) def mergeMultiple(self, srcs, allowFastForward = True, log = False, message = None): try: self._executeGitCommandAssertSuccess(CMD("merge", " ".join(self._normalizeRefName(src) for src in srcs), "--no-ff" if not allowFastForward else None, "--log" if log else None, ("-m \"%s\"" % message) if message is not None else None)) except GitCommandFailedException, e: # git-merge tends to ignore the stderr rule... output = e.stdout + e.stderr if 'conflict' in output.lower(): raise MergeConflict() raise def merge(self, src, *args, **kwargs): return self.mergeMultiple([src], *args, **kwargs) def _reset(self, flag, thing): command = "reset %s %s" % ( flag, self._normalizeRefName(thing)) self._executeGitCommandAssertSuccess(command) def resetSoft(self, thing = "HEAD"): return self._reset("--soft", thing) def resetHard(self, thing = "HEAD"): return self._reset("--hard", thing) def resetMixed(self, thing = "HEAD"): return self._reset("--mixed", thing) def _clean(self, flags): self._executeGitCommandAssertSuccess("clean -q " + flags) def cleanIgnoredFiles(self): """Cleans files that match the patterns in .gitignore""" return self._clean("-f -X") def cleanUntrackedFiles(self): return self._clean("-f -d") ################################# collaboration ################################ def addRemote(self, name, url): self._executeGitCommandAssertSuccess("remote add %s %s" % (name, url)) return remotes.Remote(self, name, url) def fetch(self, repo = None): command = "fetch" if repo is not None: command += " " command += self._asURL(repo) self._executeGitCommandAssertSuccess(command) def pull(self, repo = None): command = "pull" if repo is not None: command += " " command += self._asURL(repo) self._executeGitCommandAssertSuccess(command) def _getRefspec(self, fromBranch = None, toBranch = None, force = False): returned = "" if fromBranch is not None: returned += self._normalizeRefName(fromBranch) if returned or toBranch is not None: returned += ":" if toBranch is not None: if isinstance(toBranch, branch.RegisteredRemoteBranch): toBranch = toBranch.name returned += self._normalizeRefName(toBranch) if returned and force: returned = "+%s" % returned return returned def push(self, remote = None, fromBranch = None, toBranch = None, force = False): command = "push" #build push arguments refspec = self._getRefspec(toBranch = toBranch, fromBranch = fromBranch, force = force) if refspec and not remote: remote = "origin" if isinstance(remote, remotes.Remote): remote = remote.name elif isinstance(remote, RemoteRepository): remote = remote.url elif isinstance(remote, LocalRepository): remote = remote.path if remote is not None and not isinstance(remote, basestring): raise TypeError("Invalid type for 'remote' parameter: %s" % (type(remote),)) command = "push %s %s" % (remote if remote is not None else "", refspec) self._executeGitCommandAssertSuccess(command) def rebase(self, src): self._executeGitCommandAssertSuccess("rebase %s" % self._normalizeRefName(src)) #################################### Stashes ################################### def saveStash(self, name = None): command = "stash save" if name is not None: command += " %s" % name self._executeGitCommandAssertSuccess(command) def popStash(self, arg = None): command = "stash pop" if arg is not None: command += " %s" % arg self._executeGitCommandAssertSuccess(command) ################################# Configuration ################################ ################################### Shortcuts ################################## def clone(source, location): returned = LocalRepository(location) returned.clone(source) return returned def find_repository(): orig_path = path = os.path.realpath('.') drive, path = os.path.splitdrive(path) while path: current_path = os.path.join(drive, path) current_repo = LocalRepository(current_path) if current_repo.isValid(): return current_repo path, path_tail = os.path.split(current_path) if not path_tail: raise CannotFindRepository("Cannot find repository for %s" % (orig_path,))
20,401
Python
.py
435
37.882759
118
0.604592
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,765
config.py
CouchPotato_CouchPotatoServer/libs/git/config.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .exceptions import GitCommandFailedException class GitConfiguration(object): def __init__(self, repo): super(GitConfiguration, self).__init__() self.repo = repo def setParameter(self, path, value, local = True): self.repo._executeGitCommandAssertSuccess("config %s \"%s\" \"%s\"" % ("" if local else "--global", path, value)) def unsetParameter(self, path, local = True): try: self.repo._executeGitCommandAssertSuccess("config --unset %s \"%s\"" % ("" if local else "--global", path)) except GitCommandFailedException: if self.getParameter(path) is not None: raise def getParameter(self, path): return self.getDict().get(path, None) def getDict(self): return dict(line.strip().split("=", 1) for line in self.repo._getOutputAssertSuccess("config -l").splitlines())
2,432
Python
.py
42
53.642857
121
0.724571
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,766
ref_container.py
CouchPotato_CouchPotatoServer/libs/git/ref_container.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from . import exceptions class RefContainer(object): def getBranches(self): raise NotImplementedError() def getTags(self): raise NotImplementedError() ########################### Looking for specific refs ########################## def _getByName(self, func, name): for ref in func(): if ref.name == name: return ref raise exceptions.NonexistentRefException(name) def getBranchByName(self, name): return self._getByName(self.getBranches, name) def hasBranch(self, name): try: self.getBranchByName(name) return True except exceptions.NonexistentRefException: return False
2,242
Python
.py
44
46.659091
84
0.721893
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,767
branch.py
CouchPotato_CouchPotatoServer/libs/git/branch.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import re from ref import Ref class Branch(Ref): def delete(self): raise NotImplementedError() def __repr__(self): return "<branch %s>" % (self.name,) class LocalBranch(Branch): def delete(self, force = True): self.repo._executeGitCommandAssertSuccess("branch -%s %s" % ("D" if force else "d", self.name,)) def setRemoteBranch(self, branch): if branch is None: self.repo.config.unsetParameter('branch.%s.remote' % self.name) self.repo.config.unsetParameter('branch.%s.merge' % self.name) return elif not isinstance(branch, RegisteredRemoteBranch): raise ValueError("Remote branch must be a remote branch object (got %r)" % (branch,)) self.repo.config.setParameter('branch.%s.remote' % self.name, branch.remote.name) self.repo.config.setParameter('branch.%s.merge' % self.name, 'refs/heads/%s' % branch.name) def getRemoteBranch(self): remote = self.repo.config.getParameter('branch.%s.remote' % self.name) if remote is None: return None remote = self.repo.getRemoteByName(remote) merge = self.repo.config.getParameter('branch.%s.merge' % self.name) merge = re.sub('^refs/heads/', '', merge) remote_branch = remote.getBranchByName(merge) return remote_branch class LocalBranchAlias(LocalBranch): def __init__(self, repository, name, dest): super(LocalBranchAlias, self).__init__(repository, name) self.dest = dest class RemoteBranch(Branch): pass class RegisteredRemoteBranch(RemoteBranch): def __init__(self, repo, remote, name): super(RegisteredRemoteBranch, self).__init__(repo, name) self.remote = remote def getHead(self): return self.repo._getCommitByRefName("%s/%s" % (self.remote.name, self.name)) def delete(self): """ Deletes the actual branch on the remote repository! """ self.repo.push(self.remote, fromBranch = "", toBranch = self, force = True) def getNormalizedName(self): return "%s/%s" % (self.remote.name, self.name) def __repr__(self): return "<branch %s on remote %r>" % (self.name, self.remote.name)
3,758
Python
.py
73
46.219178
104
0.70315
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,768
utils.py
CouchPotato_CouchPotatoServer/libs/git/utils.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class CommandString(object): """ >>> CommandString('a', 'b', 'c') a b c >>> CommandString('a', 'b', None, 'c') a b c """ def __init__(self, *args): self.command = "" for arg in args: if not arg: continue if self.command: self.command += " " self.command += str(arg) def __repr__(self): return self.command def quote_for_shell(s): """ >>> print quote_for_shell('this is a " string') "this is a \\" string" >>> print quote_for_shell('this is a $shell variable') "this is a \\$shell variable" >>> print quote_for_shell(r'an escaped \\$') "an escaped \\\\\\$" """ returned = s.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$") if " " in returned: returned = '"%s"' % returned return returned if __name__ == '__main__': import doctest doctest.testmod()
2,472
Python
.py
57
39.105263
79
0.67385
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,769
__init__.py
CouchPotato_CouchPotatoServer/libs/git/__init__.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from repository import RemoteRepository from repository import LocalRepository from repository import clone from repository import find_repository
1,673
Python
.py
28
58.75
79
0.790881
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,770
tag.py
CouchPotato_CouchPotatoServer/libs/git/tag.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from ref import Ref class Tag(Ref): def __repr__(self): return "<tag %s>" % (self.name,) class LocalTag(Tag): pass class RemoteTag(Tag): pass
1,689
Python
.py
32
51.125
79
0.7657
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,771
commit.py
CouchPotato_CouchPotatoServer/libs/git/commit.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .ref import Ref from .files import ModifiedFile SHA1_LENGTH = 40 class Commit(Ref): def __init__(self, repo, sha): sha = str(sha).lower() if len(sha) < SHA1_LENGTH: sha = repo._getCommitByPartialHash(sha).hash super(Commit, self).__init__(repo, sha) self.hash = sha def __repr__(self): return self.hash def __eq__(self, other): if not isinstance(other, Commit): if isinstance(other, Ref): other = other.getHead().hash else: other = other.hash if other is None: return False if not isinstance(other, basestring): raise TypeError("Comparing %s and %s" % (type(self), type(other))) return (self.hash == other.lower()) def getParents(self): output = self.repo._getOutputAssertSuccess("rev-list %s --parents -1" % self) return [Commit(self.repo, sha.strip()) for sha in output.split()[1:]] def getChange(self): returned = [] for line in self.repo._getOutputAssertSuccess("show --pretty=format: --raw %s" % self).splitlines(): line = line.strip() if not line: continue filename = line.split()[-1] returned.append(ModifiedFile(filename)) return returned getChangedFiles = getChange ############################ Misc. Commit attributes ########################### def _getCommitField(self, field): return self.repo._executeGitCommandAssertSuccess("log -1 --pretty=format:%s %s" % (field, self)).stdout.read().strip() def getAuthorName(self): return self._getCommitField("%an") def getAuthorEmail(self): return self._getCommitField("%ae") def getDate(self): return int(self._getCommitField("%at")) def getSubject(self): return self._getCommitField("%s") def getMessageBody(self): return self._getCommitField("%b")
3,498
Python
.py
73
41.958904
126
0.673094
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,772
ref.py
CouchPotato_CouchPotatoServer/libs/git/ref.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class Ref(object): def __init__(self, repo, name): super(Ref, self).__init__() self.repo = repo self.name = name def getHead(self): return self.repo._getCommitByRefName(self.name) def getNormalizedName(self): return self.name def getNewCommits(self, comparedTo, limit = ""): returned = [] command = "cherry %s %s %s" % (self.repo._normalizeRefName(comparedTo), self.getNormalizedName(), self.repo._normalizeRefName(limit)) for line in self.repo._getOutputAssertSuccess(command).splitlines(): symbol, sha = line.split() if symbol == '-': #already has an equivalent commit continue returned.append(self.repo._getCommitByHash(sha.strip())) return returned def __eq__(self, ref): return (type(ref) is type(self) and ref.name == self.name) def __ne__(self, ref): return not (self == ref) def __repr__(self): return "<%s %s>" % (type(self).__name__, self.getNormalizedName()) ################################## Containment ################################# def getMergeBase(self, other): return self.repo.getMergeBase(self, other) __and__ = getMergeBase def contains(self, other): return self.getMergeBase(other) == other __contains__ = contains
2,981
Python
.py
58
44.965517
84
0.664613
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,773
exceptions.py
CouchPotato_CouchPotatoServer/libs/git/exceptions.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os class GitException(Exception): def __init__(self, msg): super(GitException, self).__init__() self.msg = msg def __repr__(self): return "%s: %s" % (type(self).__name__, self.msg) __str__ = __repr__ class CannotFindRepository(GitException): pass class MergeConflict(GitException): def __init__(self, msg='Merge Conflict'): super(MergeConflict, self).__init__(msg=msg) class GitCommandFailedException(GitException): def __init__(self, directory, command, popen): super(GitCommandFailedException, self).__init__(None) self.command = command self.directory = os.path.abspath(directory) self.stderr = popen.stderr.read() self.stdout = popen.stdout.read() self.popen = popen self.msg = "Command %r failed in %s (%s):\n%s\n%s" % (command, self.directory, popen.returncode, self.stderr, self.stdout) class NonexistentRefException(GitException): pass
2,527
Python
.py
49
47.510204
104
0.723525
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,774
files.py
CouchPotato_CouchPotatoServer/libs/git/files.py
# Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of organization nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Rotem Yaari BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class ModifiedFile(object): def __init__(self, filename): super(ModifiedFile, self).__init__() self.filename = filename def __repr__(self): return self.filename def __eq__(self, other): return isinstance(other, ModifiedFile) and other.filename == self.filename
1,831
Python
.py
32
54.84375
82
0.757087
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,775
environment.py
CouchPotato_CouchPotatoServer/couchpotato/environment.py
import os from couchpotato.core.database import Database from couchpotato.core.event import fireEvent, addEvent from couchpotato.core.helpers.encoding import toUnicode from couchpotato.core.loader import Loader from couchpotato.core.settings import Settings from couchpotato.core.softchroot import SoftChroot class Env(object): _appname = 'CouchPotato' ''' Environment variables ''' _app = None _encoding = 'UTF-8' _debug = False _dev = False _settings = Settings() _database = Database() _loader = Loader() _softchroot = SoftChroot() _cache = None _options = None _args = None _quiet = False _daemonized = False _desktop = None _http_opener = None ''' Data paths and directories ''' _app_dir = "" _data_dir = "" _cache_dir = "" _db = "" _log_path = "" @staticmethod def doDebug(): return Env._debug @staticmethod def get(attr, unicode = False): if unicode: return toUnicode(getattr(Env, '_' + attr)) else: return getattr(Env, '_' + attr) @staticmethod def all(): ret = '' for attr in ['encoding', 'debug', 'args', 'app_dir', 'data_dir', 'desktop', 'options']: ret += '%s=%s ' % (attr, Env.get(attr)) return ret @staticmethod def set(attr, value): return setattr(Env, '_' + attr, value) @staticmethod def setting(attr, section = 'core', value = None, default = '', type = None): s = Env.get('settings') # Return setting if value is None: return s.get(attr, default = default, section = section, type = type) # Set setting s.addSection(section) s.set(section, attr, value) s.save() return s @staticmethod def prop(identifier, value = None, default = None): s = Env.get('settings') if value is None: v = s.getProperty(identifier) return v if v else default s.setProperty(identifier, value) @staticmethod def getPermission(setting_type): perm = Env.get('settings').get('permission_%s' % setting_type, default = '0777') if perm[0] == '0': return int(perm, 8) else: return int(perm) @staticmethod def fireEvent(*args, **kwargs): return fireEvent(*args, **kwargs) @staticmethod def addEvent(*args, **kwargs): return addEvent(*args, **kwargs) @staticmethod def getPid(): try: try: parent = os.getppid() except: parent = None return '%d %s' % (os.getpid(), '(%d)' % parent if parent and parent > 1 else '') except: return 0 @staticmethod def getIdentifier(): return '%s %s' % (Env.get('appname'), fireEvent('app.version', single = True))
2,917
Python
.py
93
24.053763
95
0.585505
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,776
api.py
CouchPotato_CouchPotatoServer/couchpotato/api.py
from functools import wraps from threading import Thread import json import threading import traceback import urllib from couchpotato.core.helpers.request import getParams from couchpotato.core.logger import CPLog from tornado.ioloop import IOLoop from tornado.web import RequestHandler, asynchronous log = CPLog(__name__) api = {} api_locks = {} api_nonblock = {} api_docs = {} api_docs_missing = [] def run_async(func): @wraps(func) def async_func(*args, **kwargs): func_hl = Thread(target = func, args = args, kwargs = kwargs) func_hl.start() return async_func @run_async def run_handler(route, kwargs, callback = None): try: res = api[route](**kwargs) callback(res, route) except: log.error('Failed doing api request "%s": %s', (route, traceback.format_exc())) callback({'success': False, 'error': 'Failed returning results'}, route) # NonBlock API handler class NonBlockHandler(RequestHandler): stopper = None @asynchronous def get(self, route, *args, **kwargs): route = route.strip('/') start, stop = api_nonblock[route] self.stopper = stop start(self.sendData, last_id = self.get_argument('last_id', None)) def sendData(self, response): if not self.request.connection.stream.closed(): try: self.finish(response) except: log.debug('Failed doing nonblock request, probably already closed: %s', (traceback.format_exc())) try: self.finish({'success': False, 'error': 'Failed returning results'}) except: pass self.removeStopper() def removeStopper(self): if self.stopper: self.stopper(self.sendData) self.stopper = None def addNonBlockApiView(route, func_tuple, docs = None, **kwargs): api_nonblock[route] = func_tuple if docs: api_docs[route[4:] if route[0:4] == 'api.' else route] = docs else: api_docs_missing.append(route) # Blocking API handler class ApiHandler(RequestHandler): route = None @asynchronous def get(self, route, *args, **kwargs): self.route = route = route.strip('/') if not api.get(route): self.write('API call doesn\'t seem to exist') self.finish() return # Create lock if it doesn't exist if route in api_locks and not api_locks.get(route): api_locks[route] = threading.Lock() api_locks[route].acquire() try: kwargs = {} for x in self.request.arguments: kwargs[x] = urllib.unquote(self.get_argument(x)) # Split array arguments kwargs = getParams(kwargs) kwargs['_request'] = self # Remove t random string try: del kwargs['t'] except: pass # Add async callback handler run_handler(route, kwargs, callback = self.taskFinished) except: log.error('Failed doing api request "%s": %s', (route, traceback.format_exc())) try: self.write({'success': False, 'error': 'Failed returning results'}) self.finish() except: log.error('Failed write error "%s": %s', (route, traceback.format_exc())) self.unlock() post = get def taskFinished(self, result, route): IOLoop.current().add_callback(self.sendData, result, route) self.unlock() def sendData(self, result, route): if not self.request.connection.stream.closed(): try: # Check JSONP callback jsonp_callback = self.get_argument('callback_func', default = None) if jsonp_callback: self.set_header('Content-Type', 'text/javascript') self.finish(str(jsonp_callback) + '(' + json.dumps(result) + ')') elif isinstance(result, tuple) and result[0] == 'redirect': self.redirect(result[1]) else: self.finish(result) except UnicodeDecodeError: log.error('Failed proper encode: %s', traceback.format_exc()) except: log.debug('Failed doing request, probably already closed: %s', (traceback.format_exc())) try: self.finish({'success': False, 'error': 'Failed returning results'}) except: pass def unlock(self): try: api_locks[self.route].release() except: pass def addApiView(route, func, static = False, docs = None, **kwargs): if static: func(route) else: api[route] = func api_locks[route] = threading.Lock() if docs: api_docs[route[4:] if route[0:4] == 'api.' else route] = docs else: api_docs_missing.append(route)
4,908
Python
.py
126
29.730159
113
0.598776
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,777
runner.py
CouchPotato_CouchPotatoServer/couchpotato/runner.py
from logging import handlers from uuid import uuid4 import locale import logging import os.path import sys import time import traceback import warnings import re import tarfile import shutil from CodernityDB.database_super_thread_safe import SuperThreadSafeDatabase from argparse import ArgumentParser from cache import FileSystemCache from couchpotato import KeyHandler, LoginHandler, LogoutHandler from couchpotato.api import NonBlockHandler, ApiHandler from couchpotato.core.event import fireEventAsync, fireEvent from couchpotato.core.helpers.encoding import sp from couchpotato.core.helpers.variable import getDataDir, tryInt, getFreeSpace import requests from requests.packages.urllib3 import disable_warnings from tornado.httpserver import HTTPServer from tornado.web import Application, StaticFileHandler, RedirectHandler from couchpotato.core.softchroot import SoftChrootInitError try: from tornado.netutil import bind_unix_socket except: pass def getOptions(args): # Options parser = ArgumentParser(prog = 'CouchPotato.py') parser.add_argument('--data_dir', dest = 'data_dir', help = 'Absolute or ~/ path of the data dir') parser.add_argument('--config_file', dest = 'config_file', help = 'Absolute or ~/ path of the settings file (default DATA_DIR/settings.conf)') parser.add_argument('--debug', action = 'store_true', dest = 'debug', help = 'Debug mode') parser.add_argument('--console_log', action = 'store_true', dest = 'console_log', help = "Log to console") parser.add_argument('--quiet', action = 'store_true', dest = 'quiet', help = 'No console logging') parser.add_argument('--daemon', action = 'store_true', dest = 'daemon', help = 'Daemonize the app') parser.add_argument('--pid_file', dest = 'pid_file', help = 'Path to pidfile needed for daemon') options = parser.parse_args(args) data_dir = os.path.expanduser(options.data_dir if options.data_dir else getDataDir()) if not options.config_file: options.config_file = os.path.join(data_dir, 'settings.conf') if not options.pid_file: options.pid_file = os.path.join(data_dir, 'couchpotato.pid') options.config_file = os.path.expanduser(options.config_file) options.pid_file = os.path.expanduser(options.pid_file) return options # Tornado monkey patch logging.. def _log(status_code, request): if status_code < 400: return else: log_method = logging.debug request_time = 1000.0 * request.request_time() summary = request.method + " " + request.uri + " (" + \ request.remote_ip + ")" log_method("%d %s %.2fms", status_code, summary, request_time) def runCouchPotato(options, base_path, args, data_dir = None, log_dir = None, Env = None, desktop = None): try: locale.setlocale(locale.LC_ALL, "") encoding = locale.getpreferredencoding() except (locale.Error, IOError): encoding = None # for OSes that are poorly configured I'll just force UTF-8 if not encoding or encoding in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): encoding = 'UTF-8' Env.set('encoding', encoding) # Do db stuff db_path = sp(os.path.join(data_dir, 'database')) old_db_path = os.path.join(data_dir, 'couchpotato.db') # Remove database folder if both exists if os.path.isdir(db_path) and os.path.isfile(old_db_path): db = SuperThreadSafeDatabase(db_path) db.open() db.destroy() # Check if database exists db = SuperThreadSafeDatabase(db_path) db_exists = db.exists() if db_exists: # Backup before start and cleanup old backups backup_path = sp(os.path.join(data_dir, 'db_backup')) backup_count = 5 existing_backups = [] if not os.path.isdir(backup_path): os.makedirs(backup_path) for root, dirs, files in os.walk(backup_path): # Only consider files being a direct child of the backup_path if root == backup_path: for backup_file in sorted(files): ints = re.findall('\d+', backup_file) # Delete non zip files if len(ints) != 1: try: os.remove(os.path.join(root, backup_file)) except: pass else: existing_backups.append((int(ints[0]), backup_file)) else: # Delete stray directories. shutil.rmtree(root) # Remove all but the last 5 for eb in existing_backups[:-backup_count]: os.remove(os.path.join(backup_path, eb[1])) # Create new backup new_backup = sp(os.path.join(backup_path, '%s.tar.gz' % int(time.time()))) zipf = tarfile.open(new_backup, 'w:gz') for root, dirs, files in os.walk(db_path): for zfilename in files: zipf.add(os.path.join(root, zfilename), arcname = 'database/%s' % os.path.join(root[len(db_path) + 1:], zfilename)) zipf.close() # Open last db.open() else: db.create() # Force creation of cachedir log_dir = sp(log_dir) cache_dir = sp(os.path.join(data_dir, 'cache')) python_cache = sp(os.path.join(cache_dir, 'python')) if not os.path.exists(cache_dir): os.mkdir(cache_dir) if not os.path.exists(python_cache): os.mkdir(python_cache) session = requests.Session() session.max_redirects = 5 # Register environment settings Env.set('app_dir', sp(base_path)) Env.set('data_dir', sp(data_dir)) Env.set('log_path', sp(os.path.join(log_dir, 'CouchPotato.log'))) Env.set('db', db) Env.set('http_opener', session) Env.set('cache_dir', cache_dir) Env.set('cache', FileSystemCache(python_cache)) Env.set('console_log', options.console_log) Env.set('quiet', options.quiet) Env.set('desktop', desktop) Env.set('daemonized', options.daemon) Env.set('args', args) Env.set('options', options) # Determine debug debug = options.debug or Env.setting('debug', default = False, type = 'bool') Env.set('debug', debug) # Development development = Env.setting('development', default = False, type = 'bool') Env.set('dev', development) # Disable logging for some modules for logger_name in ['enzyme', 'guessit', 'subliminal', 'apscheduler', 'tornado', 'requests']: logging.getLogger(logger_name).setLevel(logging.ERROR) for logger_name in ['gntp']: logging.getLogger(logger_name).setLevel(logging.WARNING) # Disable SSL warning disable_warnings() # Use reloader reloader = debug is True and development and not Env.get('desktop') and not options.daemon # Logger logger = logging.getLogger() formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', '%m-%d %H:%M:%S') level = logging.DEBUG if debug else logging.INFO logger.setLevel(level) logging.addLevelName(19, 'INFO') # To screen if (debug or options.console_log) and not options.quiet and not options.daemon: hdlr = logging.StreamHandler(sys.stderr) hdlr.setFormatter(formatter) logger.addHandler(hdlr) # To file hdlr2 = handlers.RotatingFileHandler(Env.get('log_path'), 'a', 500000, 10, encoding = Env.get('encoding')) hdlr2.setFormatter(formatter) logger.addHandler(hdlr2) # Start logging & enable colors # noinspection PyUnresolvedReferences import color_logs from couchpotato.core.logger import CPLog log = CPLog(__name__) log.debug('Started with options %s', options) # Check soft-chroot dir exists: try: # Load Soft-Chroot soft_chroot = Env.get('softchroot') soft_chroot_dir = Env.setting('soft_chroot', section = 'core', default = None, type='unicode' ) soft_chroot.initialize(soft_chroot_dir) except SoftChrootInitError as exc: log.error(exc) return except: log.error('Unable to check whether SOFT-CHROOT is defined') return # Check available space try: total_space, available_space = getFreeSpace(data_dir) if available_space < 100: log.error('Shutting down as CP needs some space to work. You\'ll get corrupted data otherwise. Only %sMB left', available_space) return except: log.error('Failed getting diskspace: %s', traceback.format_exc()) def customwarn(message, category, filename, lineno, file = None, line = None): log.warning('%s %s %s line:%s', (category, message, filename, lineno)) warnings.showwarning = customwarn # Create app from couchpotato import WebHandler web_base = ('/' + Env.setting('url_base').lstrip('/') + '/') if Env.setting('url_base') else '/' Env.set('web_base', web_base) api_key = Env.setting('api_key') if not api_key: api_key = uuid4().hex Env.setting('api_key', value = api_key) api_base = r'%sapi/%s/' % (web_base, api_key) Env.set('api_base', api_base) # Basic config host = Env.setting('host', default = '0.0.0.0') host6 = Env.setting('host6', default = '::') config = { 'use_reloader': reloader, 'port': tryInt(Env.setting('port', default = 5050)), 'host': host if host and len(host) > 0 else '0.0.0.0', 'host6': host6 if host6 and len(host6) > 0 else '::', 'ssl_cert': Env.setting('ssl_cert', default = None), 'ssl_key': Env.setting('ssl_key', default = None), } # Load the app application = Application( [], log_function = lambda x: None, debug = config['use_reloader'], gzip = True, cookie_secret = api_key, login_url = '%slogin/' % web_base, ) Env.set('app', application) # Request handlers application.add_handlers(".*$", [ (r'%snonblock/(.*)(/?)' % api_base, NonBlockHandler), # API handlers (r'%s(.*)(/?)' % api_base, ApiHandler), # Main API handler (r'%sgetkey(/?)' % web_base, KeyHandler), # Get API key (r'%s' % api_base, RedirectHandler, {"url": web_base + 'docs/'}), # API docs # Login handlers (r'%slogin(/?)' % web_base, LoginHandler), (r'%slogout(/?)' % web_base, LogoutHandler), # Catch all webhandlers (r'%s(.*)(/?)' % web_base, WebHandler), (r'(.*)', WebHandler), ]) # Static paths static_path = '%sstatic/' % web_base for dir_name in ['fonts', 'images', 'scripts', 'style']: application.add_handlers(".*$", [ ('%s%s/(.*)' % (static_path, dir_name), StaticFileHandler, {'path': sp(os.path.join(base_path, 'couchpotato', 'static', dir_name))}) ]) Env.set('static_path', static_path) # Load configs & plugins loader = Env.get('loader') loader.preload(root = sp(base_path)) loader.run() # Fill database with needed stuff fireEvent('database.setup') if not db_exists: fireEvent('app.initialize', in_order = True) fireEvent('app.migrate') # Go go go! from tornado.ioloop import IOLoop from tornado.autoreload import add_reload_hook loop = IOLoop.current() # Reload hook def reload_hook(): fireEvent('app.shutdown') add_reload_hook(reload_hook) # Some logging and fire load event try: log.info('Starting server on port %(port)s', config) except: pass fireEventAsync('app.load') ssl_options = None if config['ssl_cert'] and config['ssl_key']: ssl_options = { 'certfile': config['ssl_cert'], 'keyfile': config['ssl_key'], } server = HTTPServer(application, no_keep_alive = True, ssl_options = ssl_options) try_restart = True restart_tries = 5 while try_restart: try: if config['host'].startswith('unix:'): server.add_socket(bind_unix_socket(config['host'][5:])) else: server.listen(config['port'], config['host']) if Env.setting('ipv6', default = False): try: server.listen(config['port'], config['host6']) except: log.info2('Tried to bind to IPV6 but failed') loop.start() server.close_all_connections() server.stop() loop.close(all_fds = True) except Exception as e: log.error('Failed starting: %s', traceback.format_exc()) try: nr, msg = e if nr == 48: log.info('Port (%s) needed for CouchPotato is already in use, try %s more time after few seconds', (config.get('port'), restart_tries)) time.sleep(1) restart_tries -= 1 if restart_tries > 0: continue else: return except ValueError: return except: pass raise try_restart = False
13,233
Python
.py
314
34.006369
155
0.619611
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,778
__init__.py
CouchPotato_CouchPotatoServer/couchpotato/__init__.py
import os import time import traceback from couchpotato.api import api_docs, api_docs_missing, api from couchpotato.core.event import fireEvent from couchpotato.core.helpers.encoding import sp from couchpotato.core.helpers.variable import md5, tryInt from couchpotato.core.logger import CPLog from couchpotato.environment import Env from tornado import template from tornado.web import RequestHandler, authenticated log = CPLog(__name__) views = {} template_loader = template.Loader(os.path.join(os.path.dirname(__file__), 'templates')) class BaseHandler(RequestHandler): def get_current_user(self): username = Env.setting('username') password = Env.setting('password') if username and password: return self.get_secure_cookie('user') else: # Login when no username or password are set return True # Main web handler class WebHandler(BaseHandler): @authenticated def get(self, route, *args, **kwargs): route = route.strip('/') if not views.get(route): page_not_found(self) return try: self.write(views[route](self)) except: log.error("Failed doing web request '%s': %s", (route, traceback.format_exc())) self.write({'success': False, 'error': 'Failed returning results'}) def addView(route, func): views[route] = func def get_db(): return Env.get('db') # Web view def index(*args): return template_loader.load('index.html').generate(sep = os.sep, fireEvent = fireEvent, Env = Env) addView('', index) # Web view def robots(handler): handler.set_header('Content-Type', 'text/plain') return 'User-agent: * \n' \ 'Disallow: /' addView('robots.txt', robots) # Manifest def manifest(handler): web_base = Env.get('web_base') static_base = Env.get('static_path') lines = [ 'CACHE MANIFEST', '# %s theme' % ('dark' if Env.setting('dark_theme') else 'light'), '', 'CACHE:', '' ] if not Env.get('dev'): # CSS for url in fireEvent('clientscript.get_styles', single = True): lines.append(web_base + url) # Scripts for url in fireEvent('clientscript.get_scripts', single = True): lines.append(web_base + url) # Favicon lines.append(static_base + 'images/favicon.ico') # Fonts font_folder = sp(os.path.join(Env.get('app_dir'), 'couchpotato', 'static', 'fonts')) for subfolder, dirs, files in os.walk(font_folder, topdown = False): for file in files: if '.woff' in file: lines.append(static_base + 'fonts/' + file + ('?%s' % os.path.getmtime(os.path.join(font_folder, file)))) else: lines.append('# Not caching anything in dev mode') # End lines lines.extend(['', 'NETWORK: ', '*']) handler.set_header('Content-Type', 'text/cache-manifest') return '\n'.join(lines) addView('couchpotato.appcache', manifest) # API docs def apiDocs(*args): routes = list(api.keys()) if api_docs.get(''): del api_docs[''] del api_docs_missing[''] return template_loader.load('api.html').generate(fireEvent = fireEvent, routes = sorted(routes), api_docs = api_docs, api_docs_missing = sorted(api_docs_missing), Env = Env) addView('docs', apiDocs) # Database debug manager def databaseManage(*args): return template_loader.load('database.html').generate(fireEvent = fireEvent, Env = Env) addView('database', databaseManage) # Make non basic auth option to get api key class KeyHandler(RequestHandler): def get(self, *args, **kwargs): api_key = None try: username = Env.setting('username') password = Env.setting('password') if (self.get_argument('u') == md5(username) or not username) and (self.get_argument('p') == password or not password): api_key = Env.setting('api_key') self.write({ 'success': api_key is not None, 'api_key': api_key }) except: log.error('Failed doing key request: %s', (traceback.format_exc())) self.write({'success': False, 'error': 'Failed returning results'}) class LoginHandler(BaseHandler): def get(self, *args, **kwargs): if self.get_current_user(): self.redirect(Env.get('web_base')) else: self.write(template_loader.load('login.html').generate(sep = os.sep, fireEvent = fireEvent, Env = Env)) def post(self, *args, **kwargs): api_key = None username = Env.setting('username') password = Env.setting('password') if (self.get_argument('username') == username or not username) and (md5(self.get_argument('password')) == password or not password): api_key = Env.setting('api_key') if api_key: remember_me = tryInt(self.get_argument('remember_me', default = 0)) self.set_secure_cookie('user', api_key, expires_days = 30 if remember_me > 0 else None) self.redirect(Env.get('web_base')) class LogoutHandler(BaseHandler): def get(self, *args, **kwargs): self.clear_cookie('user') self.redirect('%slogin/' % Env.get('web_base')) def page_not_found(rh): index_url = Env.get('web_base') url = rh.request.uri[len(index_url):] if url[:3] != 'api': r = index_url + '#' + url.lstrip('/') rh.redirect(r) else: if not Env.get('dev'): time.sleep(0.1) rh.set_status(404) rh.write('Wrong API key used')
5,682
Python
.py
143
32.405594
177
0.624795
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,779
environment_test.py
CouchPotato_CouchPotatoServer/couchpotato/environment_test.py
import unittest from unittest import TestCase import mock from couchpotato.environment import Env class EnvironmentBaseTest(TestCase): def test_appname(self): self.assertEqual('CouchPotato', Env.get('appname')) def test_set_get_appname(self): x = 'NEWVALUE' Env.set('appname', x) self.assertEqual(x, Env.get('appname')) def test_get_softchroot(self): from couchpotato.core.softchroot import SoftChroot sc = Env.get('softchroot') self.assertIsInstance(sc, SoftChroot)
539
Python
.py
15
30.133333
59
0.709615
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,780
settings.py
CouchPotato_CouchPotatoServer/couchpotato/core/settings.py
from __future__ import with_statement import ConfigParser import traceback from hashlib import md5 from CodernityDB.hash_index import HashIndex from couchpotato.api import addApiView from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.encoding import toUnicode from couchpotato.core.helpers.variable import mergeDicts, tryInt, tryFloat class Settings(object): options = {} types = {} def __init__(self): addApiView('settings', self.view, docs = { 'desc': 'Return the options and its values of settings.conf. Including the default values and group ordering used on the settings page.', 'return': {'type': 'object', 'example': """{ // objects like in __init__.py of plugin "options": { "moovee" : { "groups" : [{ "description" : "SD movies only", "name" : "#alt.binaries.moovee", "options" : [{ "default" : false, "name" : "enabled", "type" : "enabler" }], "tab" : "providers" }], "name" : "moovee" } }, // object structured like settings.conf "values": { "moovee": { "enabled": false } } }"""} }) addApiView('settings.save', self.saveView, docs = { 'desc': 'Save setting to config file (settings.conf)', 'params': { 'section': {'desc': 'The section name in settings.conf'}, 'name': {'desc': 'The option name'}, 'value': {'desc': 'The value you want to save'}, } }) addEvent('database.setup', self.databaseSetup) self.file = None self.p = None self.log = None self.directories_delimiter = "::" def setFile(self, config_file): self.file = config_file self.p = ConfigParser.RawConfigParser() self.p.read(config_file) from couchpotato.core.logger import CPLog self.log = CPLog(__name__) self.connectEvents() def databaseSetup(self): fireEvent('database.setup_index', 'property', PropertyIndex) def parser(self): return self.p def sections(self): res = filter( self.isSectionReadable, self.p.sections()) return res def connectEvents(self): addEvent('settings.options', self.addOptions) addEvent('settings.register', self.registerDefaults) addEvent('settings.save', self.save) def registerDefaults(self, section_name, options = None, save = True): if not options: options = {} self.addSection(section_name) for option_name, option in options.items(): self.setDefault(section_name, option_name, option.get('default', '')) # Set UI-meta for option (hidden/ro/rw) if option.get('ui-meta'): value = option.get('ui-meta') if value: value = value.lower() if value in ['hidden', 'rw', 'ro']: meta_option_name = option_name + self.optionMetaSuffix() self.setDefault(section_name, meta_option_name, value) else: self.log.warning('Wrong value for option %s.%s : ui-meta can not be equal to "%s"', (section_name, option_name, value)) # Migrate old settings from old location to the new location if option.get('migrate_from'): if self.p.has_option(option.get('migrate_from'), option_name): previous_value = self.p.get(option.get('migrate_from'), option_name) self.p.set(section_name, option_name, previous_value) self.p.remove_option(option.get('migrate_from'), option_name) if option.get('type'): self.setType(section_name, option_name, option.get('type')) if save: self.save() def set(self, section, option, value): if not self.isOptionWritable(section, option): self.log.warning('set::option "%s.%s" isn\'t writable', (section, option)) return None if self.isOptionMeta(section, option): self.log.warning('set::option "%s.%s" cancelled, since it is a META option', (section, option)) return None return self.p.set(section, option, value) def get(self, option = '', section = 'core', default = None, type = None): if self.isOptionMeta(section, option): self.log.warning('get::option "%s.%s" cancelled, since it is a META option', (section, option)) return None tp = type try: tp = self.getType(section, option) if not tp else tp if hasattr(self, 'get%s' % tp.capitalize()): return getattr(self, 'get%s' % tp.capitalize())(section, option) else: return self.getUnicode(section, option) except: return default def delete(self, option = '', section = 'core'): if not self.isOptionWritable(section, option): self.log.warning('delete::option "%s.%s" isn\'t writable', (section, option)) return None if self.isOptionMeta(section, option): self.log.warning('set::option "%s.%s" cancelled, since it is a META option', (section, option)) return None self.p.remove_option(section, option) self.save() def getEnabler(self, section, option): return self.getBool(section, option) def getBool(self, section, option): try: return self.p.getboolean(section, option) except: return self.p.get(section, option) == 1 def getInt(self, section, option): try: return self.p.getint(section, option) except: return tryInt(self.p.get(section, option)) def getFloat(self, section, option): try: return self.p.getfloat(section, option) except: return tryFloat(self.p.get(section, option)) def getDirectories(self, section, option): value = self.p.get(section, option) if value: return map(str.strip, str.split(value, self.directories_delimiter)) return [] def getUnicode(self, section, option): value = self.p.get(section, option).decode('unicode_escape') return toUnicode(value).strip() def getValues(self): from couchpotato.environment import Env values = {} soft_chroot = Env.get('softchroot') # TODO : There is two commented "continue" blocks (# COMMENTED_SKIPPING). They both are good... # ... but, they omit output of values of hidden and non-readable options # Currently, such behaviour could break the Web UI of CP... # So, currently this two blocks are commented (but they are required to # provide secure hidding of options. for section in self.sections(): # COMMENTED_SKIPPING #if not self.isSectionReadable(section): # continue values[section] = {} for option in self.p.items(section): (option_name, option_value) = option #skip meta options: if self.isOptionMeta(section, option_name): continue # COMMENTED_SKIPPING #if not self.isOptionReadable(section, option_name): # continue value = self.get(option_name, section) is_password = self.getType(section, option_name) == 'password' if is_password and value: value = len(value) * '*' # chrootify directory before sending to UI: if (self.getType(section, option_name) == 'directory') and value: try: value = soft_chroot.abs2chroot(value) except: value = "" # chrootify directories before sending to UI: if (self.getType(section, option_name) == 'directories'): if (not value): value = [] try : value = map(soft_chroot.abs2chroot, value) except : value = [] values[section][option_name] = value return values def save(self): with open(self.file, 'wb') as configfile: self.p.write(configfile) def addSection(self, section): if not self.p.has_section(section): self.p.add_section(section) def setDefault(self, section, option, value): if not self.p.has_option(section, option): self.p.set(section, option, value) def setType(self, section, option, type): if not self.types.get(section): self.types[section] = {} self.types[section][option] = type def getType(self, section, option): tp = None try: tp = self.types[section][option] except: tp = 'unicode' if not tp else tp return tp def addOptions(self, section_name, options): # no additional actions (related to ro-rw options) are required here if not self.options.get(section_name): self.options[section_name] = options else: self.options[section_name] = mergeDicts(self.options[section_name], options) def getOptions(self): """Returns dict of UI-readable options To check, whether the option is readable self.isOptionReadable() is used """ res = {} # it is required to filter invisible options for UI, but also we should # preserve original tree for server's purposes. # So, next loops do one thing: copy options to res and in the process # 1. omit NON-READABLE (for UI) options, and # 2. put flags on READONLY options for section_key in self.options.keys(): section_orig = self.options[section_key] section_name = section_orig.get('name') if 'name' in section_orig else section_key if self.isSectionReadable(section_name): section_copy = {} section_copy_groups = [] for section_field in section_orig: if section_field.lower() != 'groups': section_copy[section_field] = section_orig[section_field] else: for group_orig in section_orig['groups']: group_copy = {} group_copy_options = [] for group_field in group_orig: if group_field.lower() != 'options': group_copy[group_field] = group_orig[group_field] else: for option in group_orig[group_field]: option_name = option.get('name') # You should keep in mind, that READONLY = !IS_WRITABLE # and IS_READABLE is a different thing if self.isOptionReadable(section_name, option_name): group_copy_options.append(option) if not self.isOptionWritable(section_name, option_name): option['readonly'] = True if len(group_copy_options)>0: group_copy['options'] = group_copy_options section_copy_groups.append(group_copy) if len(section_copy_groups)>0: section_copy['groups'] = section_copy_groups res[section_key] = section_copy return res def view(self, **kwargs): return { 'options': self.getOptions(), 'values': self.getValues() } def saveView(self, **kwargs): section = kwargs.get('section') option = kwargs.get('name') value = kwargs.get('value') if not self.isOptionWritable(section, option): self.log.warning('Option "%s.%s" isn\'t writable', (section, option)) return { 'success' : False, } from couchpotato.environment import Env soft_chroot = Env.get('softchroot') if self.getType(section, option) == 'directory': value = soft_chroot.chroot2abs(value) if self.getType(section, option) == 'directories': import json value = json.loads(value) if not (value and isinstance(value, list)): value = [] value = map(soft_chroot.chroot2abs, value) value = self.directories_delimiter.join(value) # See if a value handler is attached, use that as value new_value = fireEvent('setting.save.%s.%s' % (section, option), value, single = True) self.set(section, option, (new_value if new_value else value).encode('unicode_escape')) self.save() # After save (for re-interval etc) fireEvent('setting.save.%s.%s.after' % (section, option), single = True) fireEvent('setting.save.%s.*.after' % section, single = True) return { 'success': True } def isSectionReadable(self, section): meta = 'section_hidden' + self.optionMetaSuffix() try: return not self.p.getboolean(section, meta) except: pass # by default - every section is readable: return True def isOptionReadable(self, section, option): meta = option + self.optionMetaSuffix() if self.p.has_option(section, meta): meta_v = self.p.get(section, meta).lower() return (meta_v == 'rw') or (meta_v == 'ro') # by default - all is writable: return True def optionReadableCheckAndWarn(self, section, option): x = self.isOptionReadable(section, option) if not x: self.log.warning('Option "%s.%s" isn\'t readable', (section, option)) return x def isOptionWritable(self, section, option): meta = option + self.optionMetaSuffix() if self.p.has_option(section, meta): return self.p.get(section, meta).lower() == 'rw' # by default - all is writable: return True def optionMetaSuffix(self): return '_internal_meta' def isOptionMeta(self, section, option): """ A helper method for detecting internal-meta options in the ini-file For a meta options used following names: * section_hidden_internal_meta = (True | False) - for section visibility * <OPTION>_internal_meta = (ro|rw|hidden) - for section visibility """ suffix = self.optionMetaSuffix() return option.endswith(suffix) def getProperty(self, identifier): from couchpotato import get_db db = get_db() prop = None try: propert = db.get('property', identifier, with_doc = True) prop = propert['doc']['value'] except ValueError: propert = db.get('property', identifier) fireEvent('database.delete_corrupted', propert.get('_id')) except: self.log.debug('Property "%s" doesn\'t exist: %s', (identifier, traceback.format_exc(0))) return prop def setProperty(self, identifier, value = ''): from couchpotato import get_db db = get_db() try: p = db.get('property', identifier, with_doc = True) p['doc'].update({ 'identifier': identifier, 'value': toUnicode(value), }) db.update(p['doc']) except: db.insert({ '_t': 'property', 'identifier': identifier, 'value': toUnicode(value), }) class PropertyIndex(HashIndex): _version = 1 def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(PropertyIndex, self).__init__(*args, **kwargs) def make_key(self, key): return md5(key).hexdigest() def make_key_value(self, data): if data.get('_t') == 'property': return md5(data['identifier']).hexdigest(), None
16,637
Python
.py
364
33.252747
149
0.562191
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,781
event.py
CouchPotato_CouchPotatoServer/couchpotato/core/event.py
import threading import traceback from axl.axel import Event from couchpotato.core.helpers.variable import mergeDicts, natsortKey from couchpotato.core.logger import CPLog log = CPLog(__name__) events = {} def runHandler(name, handler, *args, **kwargs): try: return handler(*args, **kwargs) except: from couchpotato.environment import Env log.error('Error in event "%s", that wasn\'t caught: %s%s', (name, traceback.format_exc(), Env.all() if not Env.get('dev') else '')) def addEvent(name, handler, priority = 100): if not events.get(name): events[name] = [] def createHandle(*args, **kwargs): h = None try: # Open handler has_parent = hasattr(handler, 'im_self') parent = None if has_parent: parent = handler.__self__ bc = hasattr(parent, 'beforeCall') if bc: parent.beforeCall(handler) # Main event h = runHandler(name, handler, *args, **kwargs) # Close handler if parent and has_parent: ac = hasattr(parent, 'afterCall') if ac: parent.afterCall(handler) except: log.error('Failed creating handler %s %s: %s', (name, handler, traceback.format_exc())) return h events[name].append({ 'handler': createHandle, 'priority': priority, }) def fireEvent(name, *args, **kwargs): if name not in events: return #log.debug('Firing event %s', name) try: options = { 'is_after_event': False, # Fire after event 'on_complete': False, # onComplete event 'single': False, # Return single handler 'merge': False, # Merge items 'in_order': False, # Fire them in specific order, waits for the other to finish } # Do options for x in options: try: val = kwargs[x] del kwargs[x] options[x] = val except: pass if len(events[name]) == 1: single = None try: single = events[name][0]['handler'](*args, **kwargs) except: log.error('Failed running single event: %s', traceback.format_exc()) # Don't load thread for single event result = { 'single': (single is not None, single), } else: e = Event(name = name, threads = 10, exc_info = True, traceback = True) for event in events[name]: e.handle(event['handler'], priority = event['priority']) # Make sure only 1 event is fired at a time when order is wanted kwargs['event_order_lock'] = threading.RLock() if options['in_order'] or options['single'] else None kwargs['event_return_on_result'] = options['single'] # Fire result = e(*args, **kwargs) result_keys = result.keys() result_keys.sort(key = natsortKey) if options['single'] and not options['merge']: results = None # Loop over results, stop when first not None result is found. for r_key in result_keys: r = result[r_key] if r[0] is True and r[1] is not None: results = r[1] break elif r[1]: errorHandler(r[1]) else: log.debug('Assume disabled eventhandler for: %s', name) else: results = [] for r_key in result_keys: r = result[r_key] if r[0] == True and r[1]: results.append(r[1]) elif r[1]: errorHandler(r[1]) # Merge if options['merge'] and len(results) > 0: # Dict if isinstance(results[0], dict): results.reverse() merged = {} for result in results: merged = mergeDicts(merged, result, prepend_list = True) results = merged # Lists elif isinstance(results[0], list): merged = [] for result in results: if result not in merged: merged += result results = merged modified_results = fireEvent('result.modify.%s' % name, results, single = True) if modified_results: log.debug('Return modified results for %s', name) results = modified_results if not options['is_after_event']: fireEvent('%s.after' % name, is_after_event = True) if options['on_complete']: options['on_complete']() return results except Exception: log.error('%s: %s', (name, traceback.format_exc())) def fireEventAsync(*args, **kwargs): try: t = threading.Thread(target = fireEvent, args = args, kwargs = kwargs) t.setDaemon(True) t.start() return True except Exception as e: log.error('%s: %s', (args[0], e)) def errorHandler(error): etype, value, tb = error log.error(''.join(traceback.format_exception(etype, value, tb))) def getEvent(name): return events[name]
5,458
Python
.py
138
27.405797
140
0.527304
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,782
loader.py
CouchPotato_CouchPotatoServer/couchpotato/core/loader.py
import os import sys import traceback from couchpotato.core.event import fireEvent from couchpotato.core.logger import CPLog from importhelper import import_module import six log = CPLog(__name__) class Loader(object): def __init__(self): self.plugins = {} self.providers = {} self.modules = {} self.paths = {} def preload(self, root = ''): core = os.path.join(root, 'couchpotato', 'core') self.paths.update({ 'core': (0, 'couchpotato.core._base', os.path.join(core, '_base')), 'plugin': (1, 'couchpotato.core.plugins', os.path.join(core, 'plugins')), 'notifications': (20, 'couchpotato.core.notifications', os.path.join(core, 'notifications')), 'downloaders': (20, 'couchpotato.core.downloaders', os.path.join(core, 'downloaders')), }) # Add media to loader self.addPath(root, ['couchpotato', 'core', 'media'], 25, recursive = True) # Add custom plugin folder from couchpotato.environment import Env custom_plugin_dir = os.path.join(Env.get('data_dir'), 'custom_plugins') if os.path.isdir(custom_plugin_dir): sys.path.insert(0, custom_plugin_dir) self.paths['custom_plugins'] = (30, '', custom_plugin_dir) # Loop over all paths and add to module list for plugin_type, plugin_tuple in self.paths.items(): priority, module, dir_name = plugin_tuple self.addFromDir(plugin_type, priority, module, dir_name) def run(self): did_save = 0 for priority in sorted(self.modules): for module_name, plugin in sorted(self.modules[priority].items()): # Load module try: if plugin.get('name')[:2] == '__': continue m = self.loadModule(module_name) if m is None: continue # Save default settings for plugin/provider did_save += self.loadSettings(m, module_name, save = False) self.loadPlugins(m, plugin.get('type'), plugin.get('name')) except ImportError as e: # todo:: subclass ImportError for missing requirements. if e.message.lower().startswith("missing"): log.error(e.message) pass # todo:: this needs to be more descriptive. log.error('Import error, remove the empty folder: %s', plugin.get('module')) log.debug('Can\'t import %s: %s', (module_name, traceback.format_exc())) except: log.error('Can\'t import %s: %s', (module_name, traceback.format_exc())) if did_save: fireEvent('settings.save') def addPath(self, root, base_path, priority, recursive = False): root_path = os.path.join(root, *base_path) for filename in os.listdir(root_path): path = os.path.join(root_path, filename) if os.path.isdir(path) and filename[:2] != '__': if six.u('__init__.py') in os.listdir(path): new_base_path = ''.join(s + '.' for s in base_path) + filename self.paths[new_base_path.replace('.', '_')] = (priority, new_base_path, path) if recursive: self.addPath(root, base_path + [filename], priority, recursive = True) def addFromDir(self, plugin_type, priority, module, dir_name): # Load dir module if module and len(module) > 0: self.addModule(priority, plugin_type, module, os.path.basename(dir_name)) for name in os.listdir(dir_name): path = os.path.join(dir_name, name) ext = os.path.splitext(path)[1] ext_length = len(ext) # SKIP test files: if path.endswith('_test.py'): continue if name != 'static' and ((os.path.isdir(path) and os.path.isfile(os.path.join(path, '__init__.py'))) or (os.path.isfile(path) and ext == '.py')): name = name[:-ext_length] if ext_length > 0 else name module_name = '%s.%s' % (module, name) self.addModule(priority, plugin_type, module_name, name) def loadSettings(self, module, name, save = True): if not hasattr(module, 'config'): #log.debug('Skip loading settings for plugin %s as it has no config section' % module.__file__) return False try: for section in module.config: fireEvent('settings.options', section['name'], section) options = {} for group in section['groups']: for option in group['options']: options[option['name']] = option fireEvent('settings.register', section_name = section['name'], options = options, save = save) return True except: log.debug('Failed loading settings for "%s": %s', (name, traceback.format_exc())) return False def loadPlugins(self, module, type, name): if not hasattr(module, 'autoload'): #log.debug('Skip startup for plugin %s as it has no start section' % module.__file__) return False try: # Load single file plugin if isinstance(module.autoload, (str, unicode)): getattr(module, module.autoload)() # Load folder plugin else: module.autoload() log.info('Loaded %s: %s', (type, name)) return True except: log.error('Failed loading plugin "%s": %s', (module.__file__, traceback.format_exc())) return False def addModule(self, priority, plugin_type, module, name): if not self.modules.get(priority): self.modules[priority] = {} module = module.lstrip('.') if plugin_type.startswith('couchpotato_core'): plugin_type = plugin_type[17:] self.modules[priority][module] = { 'priority': priority, 'module': module, 'type': plugin_type, 'name': name, } def loadModule(self, name): try: return import_module(name) except ImportError: log.debug('Skip loading module plugin %s: %s', (name, traceback.format_exc())) return None except: raise
6,625
Python
.py
138
35.115942
112
0.552472
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,783
settings_test.py
CouchPotato_CouchPotatoServer/couchpotato/core/settings_test.py
import mock from mock import patch, Mock, MagicMock import unittest from unittest import TestCase from couchpotato.core.settings import Settings class DoNotUseMe: """ Do not use this class, it is just for storing Mock ' s of Settings-class Usage: Select appropriate Mocks and copy-paste them to your test-method """ def __do_not_call(self): # s = Settings s = Mock() # methods: s.isOptionWritable = Mock(return_value=True) s.set = Mock(return_value=None) s.save = Mock() # props: s.log = Mock() # subobjects s.p = Mock() s.p.getboolean = Mock(return_value=True) s.p.has_option = Mock class SettingsCommon(TestCase): def setUp(self): self.s = Settings() def test_get_directories(self): s = self.s raw = ' /some/directory ::/another/dir ' exp = ['/some/directory', '/another/dir'] sec = 'sec' opt = 'opt' s.types[sec] = {} s.types[sec][opt] = 'directories' s.p = MagicMock() s.p.get.return_value = raw act = s.get(option = opt, section = sec) self.assertEqual(act, exp) class SettingsSaveWritableNonWritable(TestCase): def setUp(self): self.s = Settings() def test_save_writable(self): s = self.s # set up Settings-mocks : # lets assume, that option is writable: mock_isOptionWritable = s.isOptionWritable = Mock(return_value=True) mock_set = s.set = Mock(return_value=None) mock_p_save = s.save = Mock() section = 'core' option = 'option_non_exist_be_sure' value = "1000" params = {'section': section, 'name': option, 'value': value} # call method: env_mock = Mock() # HERE is an example of mocking LOCAL 'import' with patch.dict('sys.modules', {'couchpotato.environment.Env': env_mock}): result = s.saveView(**params) self.assertIsInstance(s, Settings) self.assertIsInstance(result, dict) self.assertTrue(result['success']) # ----------------------------------------- # check mock # ----------------------------------------- mock_isOptionWritable.assert_called_with(section, option) # check, that Settings tried to save my value: mock_set.assert_called_with(section, option, value) def test_save_non_writable(self): s = self.s # set up Settings-mocks : # lets assume, that option is not writable: mock_is_w = s.isOptionWritable = Mock(return_value=False) mock_set = s.set = Mock(return_value=None) mock_p_save = s.save = Mock() mock_log_s = s.log = Mock() section = 'core' option = 'option_non_exist_be_sure' value = "1000" params = {'section': section, 'name': option, 'value': value} # call method: env_mock = Mock() # HERE is an example of mocking LOCAL 'import' with patch.dict('sys.modules', {'couchpotato.environment.Env': env_mock}): result = s.saveView(**params) self.assertIsInstance(s, Settings) self.assertIsInstance(result, dict) self.assertFalse(result['success']) # ----------------------------------------- # check mock # ----------------------------------------- # lets check, that 'set'-method was not called: self.assertFalse(mock_set.called, 'Method `set` was called') mock_is_w.assert_called_with(section, option) class OptionMetaSuite(TestCase): """ tests for ro rw hidden options """ def setUp(self): self.s = Settings() self.meta = self.s.optionMetaSuffix() # hide real config-parser: self.s.p = Mock() def test_no_meta_option(self): s = self.s section = 'core' option = 'url' option_meta = option + self.meta # setup mock s.p.getboolean = Mock(return_value=True) # there is no META-record for our option: s.p.has_option = Mock(side_effect=lambda s, o: not (s == section and o == option_meta)) # by default all options are writable and readable self.assertTrue(s.isOptionWritable(section, option)) self.assertTrue(s.isOptionReadable(section, option)) def test_non_writable(self): s = self.s section = 'core' option = 'url' def mock_get_meta_ro(s, o): if (s == section and o == option_meta): return 'ro' return 11 option_meta = option + self.meta # setup mock s.p.has_option = Mock(return_value=True) s.p.get = Mock(side_effect=mock_get_meta_ro) # by default all options are writable and readable self.assertFalse(s.isOptionWritable(section, option)) self.assertTrue(s.isOptionReadable(section, option))
4,990
Python
.py
126
31.02381
95
0.580444
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,784
softchroot.py
CouchPotato_CouchPotatoServer/couchpotato/core/softchroot.py
import os import sys class SoftChrootInitError(IOError): """Error during soft-chroot initialization""" pass class SoftChroot: """Soft Chroot module Provides chroot feature for interation with Web-UI. Since it is not real chroot, so the name is SOFT CHROOT. The module prevents access to entire file-system, allowing access only to subdirs of SOFT-CHROOT directory. """ def __init__(self): self.enabled = None self.chdir = None def initialize(self, chdir): """ initialize module, by setting soft-chroot-directory Sets soft-chroot directory and 'enabled'-flag Args: self (SoftChroot) : self chdir (string) : absolute path to soft-chroot Raises: SoftChrootInitError: when chdir doesn't exist """ orig_chdir = chdir if chdir: chdir = chdir.strip() if (chdir): # enabling soft-chroot: if not os.path.isdir(chdir): raise SoftChrootInitError(2, 'SOFT-CHROOT is requested, but the folder doesn\'t exist', orig_chdir) self.enabled = True self.chdir = chdir.rstrip(os.path.sep) + os.path.sep else: self.enabled = False def get_chroot(self): """Returns root in chrooted environment Raises: RuntimeError: when `SoftChroot` is not initialized OR enabled """ if None == self.enabled: raise RuntimeError('SoftChroot is not initialized') if not self.enabled: raise RuntimeError('SoftChroot is not enabled') return self.chdir def is_root_abs(self, abspath): """ Checks whether absolute path @abspath is the root in the soft-chrooted environment""" if None == self.enabled: raise RuntimeError('SoftChroot is not initialized') if None == abspath: raise ValueError('abspath can not be None') if not self.enabled: # if not chroot environment : check, whether parent is the same dir: parent = os.path.dirname(abspath.rstrip(os.path.sep)) return parent==abspath # in soft-chrooted env: check, that path == chroot path = abspath.rstrip(os.path.sep) + os.path.sep return self.chdir == path def is_subdir(self, abspath): """ Checks whether @abspath is subdir (on any level) of soft-chroot""" if None == self.enabled: raise RuntimeError('SoftChroot is not initialized') if None == abspath: return False if not self.enabled: return True if not abspath.endswith(os.path.sep): abspath += os.path.sep return abspath.startswith(self.chdir) def chroot2abs(self, path): """ Converts chrooted path to absolute path""" if None == self.enabled: raise RuntimeError('SoftChroot is not initialized') if not self.enabled: return path if None == path or len(path)==0: return self.chdir if not path.startswith(os.path.sep): path = os.path.sep + path return self.chdir[:-1] + path def abs2chroot(self, path, force = False): """ Converts absolute path to chrooted path""" if None == self.enabled: raise RuntimeError('SoftChroot is not initialized') if None == path: raise ValueError('path is empty') if not self.enabled: return path if path == self.chdir.rstrip(os.path.sep): return '/' resulst = None if not path.startswith(self.chdir): if (force): result = self.get_chroot() else: raise ValueError("path must starts with 'chdir': %s" % path) else: l = len(self.chdir)-1 result = path[l:] return result
3,963
Python
.py
98
30.214286
115
0.602043
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,785
logger.py
CouchPotato_CouchPotatoServer/couchpotato/core/logger.py
import logging import re class CPLog(object): context = '' replace_private = ['api', 'apikey', 'api_key', 'password', 'username', 'h', 'uid', 'key', 'passkey'] Env = None is_develop = False def __init__(self, context = ''): if context.endswith('.main'): context = context[:-5] self.context = context self.logger = logging.getLogger() def setup(self): if not self.Env: from couchpotato.environment import Env self.Env = Env self.is_develop = Env.get('dev') from couchpotato.core.event import addEvent addEvent('app.after_shutdown', self.close) def close(self, *args, **kwargs): logging.shutdown() def info(self, msg, replace_tuple = ()): self.logger.info(self.addContext(msg, replace_tuple)) def info2(self, msg, replace_tuple = ()): self.logger.log(19, self.addContext(msg, replace_tuple)) def debug(self, msg, replace_tuple = ()): self.logger.debug(self.addContext(msg, replace_tuple)) def error(self, msg, replace_tuple = ()): self.logger.error(self.addContext(msg, replace_tuple)) def warning(self, msg, replace_tuple = ()): self.logger.warning(self.addContext(msg, replace_tuple)) def critical(self, msg, replace_tuple = ()): self.logger.critical(self.addContext(msg, replace_tuple), exc_info = 1) def addContext(self, msg, replace_tuple = ()): return '[%+25.25s] %s' % (self.context[-25:], self.safeMessage(msg, replace_tuple)) def safeMessage(self, msg, replace_tuple = ()): from couchpotato.core.helpers.encoding import ss, toUnicode msg = ss(msg) try: if isinstance(replace_tuple, tuple): msg = msg % tuple([ss(x) if not isinstance(x, (int, float)) else x for x in list(replace_tuple)]) elif isinstance(replace_tuple, dict): msg = msg % dict((k, ss(v) if not isinstance(v, (int, float)) else v) for k, v in replace_tuple.iteritems()) else: msg = msg % ss(replace_tuple) except Exception as e: self.logger.error('Failed encoding stuff to log "%s": %s' % (msg, e)) self.setup() if not self.is_develop: for replace in self.replace_private: msg = re.sub('(\?%s=)[^\&]+' % replace, '?%s=xxx' % replace, msg) msg = re.sub('(&%s=)[^\&]+' % replace, '&%s=xxx' % replace, msg) # Replace api key try: api_key = self.Env.setting('api_key') if api_key: msg = msg.replace(api_key, 'API_KEY') except: pass return toUnicode(msg)
2,776
Python
.py
60
36.033333
124
0.575093
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,786
database.py
CouchPotato_CouchPotatoServer/couchpotato/core/database.py
import json import os import time import traceback from sqlite3 import OperationalError from CodernityDB.database import RecordNotFound from CodernityDB.index import IndexException, IndexNotFoundException, IndexConflict from couchpotato import CPLog from couchpotato.api import addApiView from couchpotato.core.event import addEvent, fireEvent, fireEventAsync from couchpotato.core.helpers.encoding import toUnicode, sp from couchpotato.core.helpers.variable import getImdb, tryInt, randomString log = CPLog(__name__) class Database(object): indexes = None db = None def __init__(self): self.indexes = {} addApiView('database.list_documents', self.listDocuments) addApiView('database.reindex', self.reindex) addApiView('database.compact', self.compact) addApiView('database.document.update', self.updateDocument) addApiView('database.document.delete', self.deleteDocument) addEvent('database.setup.after', self.startup_compact) addEvent('database.setup_index', self.setupIndex) addEvent('database.delete_corrupted', self.deleteCorrupted) addEvent('app.migrate', self.migrate) addEvent('app.after_shutdown', self.close) def getDB(self): if not self.db: from couchpotato import get_db self.db = get_db() return self.db def close(self, **kwargs): self.getDB().close() def setupIndex(self, index_name, klass): self.indexes[index_name] = klass db = self.getDB() # Category index index_instance = klass(db.path, index_name) try: # Make sure store and bucket don't exist exists = [] for x in ['buck', 'stor']: full_path = os.path.join(db.path, '%s_%s' % (index_name, x)) if os.path.exists(full_path): exists.append(full_path) if index_name not in db.indexes_names: # Remove existing buckets if index isn't there for x in exists: os.unlink(x) # Add index (will restore buckets) db.add_index(index_instance) db.reindex_index(index_name) else: # Previous info previous = db.indexes_names[index_name] previous_version = previous._version current_version = klass._version # Only edit index if versions are different if previous_version < current_version: log.debug('Index "%s" already exists, updating and reindexing', index_name) db.destroy_index(previous) db.add_index(index_instance) db.reindex_index(index_name) except: log.error('Failed adding index %s: %s', (index_name, traceback.format_exc())) def deleteDocument(self, **kwargs): db = self.getDB() try: document_id = kwargs.get('_request').get_argument('id') document = db.get('id', document_id) db.delete(document) return { 'success': True } except: return { 'success': False, 'error': traceback.format_exc() } def updateDocument(self, **kwargs): db = self.getDB() try: document = json.loads(kwargs.get('_request').get_argument('document')) d = db.update(document) document.update(d) return { 'success': True, 'document': document } except: return { 'success': False, 'error': traceback.format_exc() } def listDocuments(self, **kwargs): db = self.getDB() results = { 'unknown': [] } for document in db.all('id'): key = document.get('_t', 'unknown') if kwargs.get('show') and key != kwargs.get('show'): continue if not results.get(key): results[key] = [] results[key].append(document) return results def deleteCorrupted(self, _id, traceback_error = ''): db = self.getDB() try: log.debug('Deleted corrupted document "%s": %s', (_id, traceback_error)) corrupted = db.get('id', _id, with_storage = False) db._delete_id_index(corrupted.get('_id'), corrupted.get('_rev'), None) except: log.debug('Failed deleting corrupted: %s', traceback.format_exc()) def reindex(self, **kwargs): success = True try: db = self.getDB() db.reindex() except: log.error('Failed index: %s', traceback.format_exc()) success = False return { 'success': success } def compact(self, try_repair = True, **kwargs): success = False db = self.getDB() # Removing left over compact files db_path = sp(db.path) for f in os.listdir(sp(db.path)): for x in ['_compact_buck', '_compact_stor']: if f[-len(x):] == x: os.unlink(os.path.join(db_path, f)) try: start = time.time() size = float(db.get_db_details().get('size', 0)) log.debug('Compacting database, current size: %sMB', round(size/1048576, 2)) db.compact() new_size = float(db.get_db_details().get('size', 0)) log.debug('Done compacting database in %ss, new size: %sMB, saved: %sMB', (round(time.time()-start, 2), round(new_size/1048576, 2), round((size-new_size)/1048576, 2))) success = True except (IndexException, AttributeError): if try_repair: log.error('Something wrong with indexes, trying repair') # Remove all indexes old_indexes = self.indexes.keys() for index_name in old_indexes: try: db.destroy_index(index_name) except IndexNotFoundException: pass except: log.error('Failed removing old index %s', index_name) # Add them again for index_name in self.indexes: klass = self.indexes[index_name] # Category index index_instance = klass(db.path, index_name) try: db.add_index(index_instance) db.reindex_index(index_name) except IndexConflict: pass except: log.error('Failed adding index %s', index_name) raise self.compact(try_repair = False) else: log.error('Failed compact: %s', traceback.format_exc()) except: log.error('Failed compact: %s', traceback.format_exc()) return { 'success': success } # Compact on start def startup_compact(self): from couchpotato import Env db = self.getDB() # Try fix for migration failures on desktop if Env.get('desktop'): try: list(db.all('profile', with_doc = True)) except RecordNotFound: failed_location = '%s_failed' % db.path old_db = os.path.join(Env.get('data_dir'), 'couchpotato.db.old') if not os.path.isdir(failed_location) and os.path.isfile(old_db): log.error('Corrupt database, trying migrate again') db.close() # Rename database folder os.rename(db.path, '%s_failed' % db.path) # Rename .old database to try another migrate os.rename(old_db, old_db[:-4]) fireEventAsync('app.restart') else: log.error('Migration failed and couldn\'t recover database. Please report on GitHub, with this message.') db.reindex() return # Check size and compact if needed size = db.get_db_details().get('size') prop_name = 'last_db_compact' last_check = int(Env.prop(prop_name, default = 0)) if last_check < time.time()-604800: # 7 days self.compact() Env.prop(prop_name, value = int(time.time())) def migrate(self): from couchpotato import Env old_db = os.path.join(Env.get('data_dir'), 'couchpotato.db') if not os.path.isfile(old_db): return log.info('=' * 30) log.info('Migrating database, hold on..') time.sleep(1) if os.path.isfile(old_db): migrate_start = time.time() import sqlite3 conn = sqlite3.connect(old_db) migrate_list = { 'category': ['id', 'label', 'order', 'required', 'preferred', 'ignored', 'destination'], 'profile': ['id', 'label', 'order', 'core', 'hide'], 'profiletype': ['id', 'order', 'finish', 'wait_for', 'quality_id', 'profile_id'], 'quality': ['id', 'identifier', 'order', 'size_min', 'size_max'], 'movie': ['id', 'last_edit', 'library_id', 'status_id', 'profile_id', 'category_id'], 'library': ['id', 'identifier', 'info'], 'librarytitle': ['id', 'title', 'default', 'libraries_id'], 'library_files__file_library': ['library_id', 'file_id'], 'release': ['id', 'identifier', 'movie_id', 'status_id', 'quality_id', 'last_edit'], 'releaseinfo': ['id', 'identifier', 'value', 'release_id'], 'release_files__file_release': ['release_id', 'file_id'], 'status': ['id', 'identifier'], 'properties': ['id', 'identifier', 'value'], 'file': ['id', 'path', 'type_id'], 'filetype': ['identifier', 'id'] } migrate_data = {} rename_old = False try: c = conn.cursor() for ml in migrate_list: migrate_data[ml] = {} rows = migrate_list[ml] try: c.execute('SELECT %s FROM `%s`' % ('`' + '`,`'.join(rows) + '`', ml)) except: # ignore faulty destination_id database if ml == 'category': migrate_data[ml] = {} else: rename_old = True raise for p in c.fetchall(): columns = {} for row in migrate_list[ml]: columns[row] = p[rows.index(row)] if not migrate_data[ml].get(p[0]): migrate_data[ml][p[0]] = columns else: if not isinstance(migrate_data[ml][p[0]], list): migrate_data[ml][p[0]] = [migrate_data[ml][p[0]]] migrate_data[ml][p[0]].append(columns) conn.close() log.info('Getting data took %s', time.time() - migrate_start) db = self.getDB() if not db.opened: return # Use properties properties = migrate_data['properties'] log.info('Importing %s properties', len(properties)) for x in properties: property = properties[x] Env.prop(property.get('identifier'), property.get('value')) # Categories categories = migrate_data.get('category', []) log.info('Importing %s categories', len(categories)) category_link = {} for x in categories: c = categories[x] new_c = db.insert({ '_t': 'category', 'order': c.get('order', 999), 'label': toUnicode(c.get('label', '')), 'ignored': toUnicode(c.get('ignored', '')), 'preferred': toUnicode(c.get('preferred', '')), 'required': toUnicode(c.get('required', '')), 'destination': toUnicode(c.get('destination', '')), }) category_link[x] = new_c.get('_id') # Profiles log.info('Importing profiles') new_profiles = db.all('profile', with_doc = True) new_profiles_by_label = {} for x in new_profiles: # Remove default non core profiles if not x['doc'].get('core'): db.delete(x['doc']) else: new_profiles_by_label[x['doc']['label']] = x['_id'] profiles = migrate_data['profile'] profile_link = {} for x in profiles: p = profiles[x] exists = new_profiles_by_label.get(p.get('label')) # Update existing with order only if exists and p.get('core'): profile = db.get('id', exists) profile['order'] = tryInt(p.get('order')) profile['hide'] = p.get('hide') in [1, True, 'true', 'True'] db.update(profile) profile_link[x] = profile.get('_id') else: new_profile = { '_t': 'profile', 'label': p.get('label'), 'order': int(p.get('order', 999)), 'core': p.get('core', False), 'qualities': [], 'wait_for': [], 'finish': [] } types = migrate_data['profiletype'] for profile_type in types: p_type = types[profile_type] if types[profile_type]['profile_id'] == p['id']: if p_type['quality_id']: new_profile['finish'].append(p_type['finish']) new_profile['wait_for'].append(p_type['wait_for']) new_profile['qualities'].append(migrate_data['quality'][p_type['quality_id']]['identifier']) if len(new_profile['qualities']) > 0: new_profile.update(db.insert(new_profile)) profile_link[x] = new_profile.get('_id') else: log.error('Corrupt profile list for "%s", using default.', p.get('label')) # Qualities log.info('Importing quality sizes') new_qualities = db.all('quality', with_doc = True) new_qualities_by_identifier = {} for x in new_qualities: new_qualities_by_identifier[x['doc']['identifier']] = x['_id'] qualities = migrate_data['quality'] quality_link = {} for x in qualities: q = qualities[x] q_id = new_qualities_by_identifier[q.get('identifier')] quality = db.get('id', q_id) quality['order'] = q.get('order') quality['size_min'] = tryInt(q.get('size_min')) quality['size_max'] = tryInt(q.get('size_max')) db.update(quality) quality_link[x] = quality # Titles titles = migrate_data['librarytitle'] titles_by_library = {} for x in titles: title = titles[x] if title.get('default'): titles_by_library[title.get('libraries_id')] = title.get('title') # Releases releaseinfos = migrate_data['releaseinfo'] for x in releaseinfos: info = releaseinfos[x] # Skip if release doesn't exist for this info if not migrate_data['release'].get(info.get('release_id')): continue if not migrate_data['release'][info.get('release_id')].get('info'): migrate_data['release'][info.get('release_id')]['info'] = {} migrate_data['release'][info.get('release_id')]['info'][info.get('identifier')] = info.get('value') releases = migrate_data['release'] releases_by_media = {} for x in releases: release = releases[x] if not releases_by_media.get(release.get('movie_id')): releases_by_media[release.get('movie_id')] = [] releases_by_media[release.get('movie_id')].append(release) # Type ids types = migrate_data['filetype'] type_by_id = {} for t in types: type = types[t] type_by_id[type.get('id')] = type # Media log.info('Importing %s media items', len(migrate_data['movie'])) statuses = migrate_data['status'] libraries = migrate_data['library'] library_files = migrate_data['library_files__file_library'] releases_files = migrate_data['release_files__file_release'] all_files = migrate_data['file'] poster_type = migrate_data['filetype']['poster'] medias = migrate_data['movie'] for x in medias: m = medias[x] status = statuses.get(m['status_id']).get('identifier') l = libraries.get(m['library_id']) # Only migrate wanted movies, Skip if no identifier present if not l or not getImdb(l.get('identifier')): continue profile_id = profile_link.get(m['profile_id']) category_id = category_link.get(m['category_id']) title = titles_by_library.get(m['library_id']) releases = releases_by_media.get(x, []) info = json.loads(l.get('info', '')) files = library_files.get(m['library_id'], []) if not isinstance(files, list): files = [files] added_media = fireEvent('movie.add', { 'info': info, 'identifier': l.get('identifier'), 'profile_id': profile_id, 'category_id': category_id, 'title': title }, force_readd = False, search_after = False, update_after = False, notify_after = False, status = status, single = True) if not added_media: log.error('Failed adding media %s: %s', (l.get('identifier'), info)) continue added_media['files'] = added_media.get('files', {}) for f in files: ffile = all_files[f.get('file_id')] # Only migrate posters if ffile.get('type_id') == poster_type.get('id'): if ffile.get('path') not in added_media['files'].get('image_poster', []) and os.path.isfile(ffile.get('path')): added_media['files']['image_poster'] = [ffile.get('path')] break if 'image_poster' in added_media['files']: db.update(added_media) for rel in releases: empty_info = False if not rel.get('info'): empty_info = True rel['info'] = {} quality = quality_link.get(rel.get('quality_id')) if not quality: continue release_status = statuses.get(rel.get('status_id')).get('identifier') if rel['info'].get('download_id'): status_support = rel['info'].get('download_status_support', False) in [True, 'true', 'True'] rel['info']['download_info'] = { 'id': rel['info'].get('download_id'), 'downloader': rel['info'].get('download_downloader'), 'status_support': status_support, } # Add status to keys rel['info']['status'] = release_status if not empty_info: fireEvent('release.create_from_search', [rel['info']], added_media, quality, single = True) else: release = { '_t': 'release', 'identifier': rel.get('identifier'), 'media_id': added_media.get('_id'), 'quality': quality.get('identifier'), 'status': release_status, 'last_edit': int(time.time()), 'files': {} } # Add downloader info if provided try: release['download_info'] = rel['info']['download_info'] del rel['download_info'] except: pass # Add files release_files = releases_files.get(rel.get('id'), []) if not isinstance(release_files, list): release_files = [release_files] if len(release_files) == 0: continue for f in release_files: rfile = all_files.get(f.get('file_id')) if not rfile: continue file_type = type_by_id.get(rfile.get('type_id')).get('identifier') if not release['files'].get(file_type): release['files'][file_type] = [] release['files'][file_type].append(rfile.get('path')) try: rls = db.get('release_identifier', rel.get('identifier'), with_doc = True)['doc'] rls.update(release) db.update(rls) except: db.insert(release) log.info('Total migration took %s', time.time() - migrate_start) log.info('=' * 30) rename_old = True except OperationalError: log.error('Migrating from faulty database, probably a (too) old version: %s', traceback.format_exc()) rename_old = True except: log.error('Migration failed: %s', traceback.format_exc()) # rename old database if rename_old: random = randomString() log.info('Renaming old database to %s ', '%s.%s_old' % (old_db, random)) os.rename(old_db, '%s.%s_old' % (old_db, random)) if os.path.isfile(old_db + '-wal'): os.rename(old_db + '-wal', '%s-wal.%s_old' % (old_db, random)) if os.path.isfile(old_db + '-shm'): os.rename(old_db + '-shm', '%s-shm.%s_old' % (old_db, random))
24,784
Python
.py
497
31.181087
179
0.463011
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,787
softchroot_test.py
CouchPotato_CouchPotatoServer/couchpotato/core/softchroot_test.py
import sys import os import logging import unittest from unittest import TestCase from couchpotato.core.softchroot import SoftChroot CHROOT_DIR = '/tmp/' class SoftChrootNonInitialized(TestCase): def setUp(self): self.b = SoftChroot() def test_is_root_abs(self): with self.assertRaises(RuntimeError): self.b.is_root_abs('1') def test_is_subdir(self): with self.assertRaises(RuntimeError): self.b.is_subdir('1') def test_chroot2abs(self): with self.assertRaises(RuntimeError): self.b.chroot2abs('1') def test_abs2chroot(self): with self.assertRaises(RuntimeError): self.b.abs2chroot('1') def test_get_root(self): with self.assertRaises(RuntimeError): self.b.get_chroot() class SoftChrootNOTEnabledTest(TestCase): def setUp(self): self.b = SoftChroot() self.b.initialize(None) def test_get_root(self): with self.assertRaises(RuntimeError): self.b.get_chroot() def test_chroot2abs_noleading_slash(self): path = 'no_leading_slash' self.assertEqual( self.b.chroot2abs(path), path ) def test_chroot2abs(self): self.assertIsNone( self.b.chroot2abs(None), None ) self.assertEqual( self.b.chroot2abs(''), '' ) self.assertEqual( self.b.chroot2abs('/asdf'), '/asdf' ) def test_abs2chroot_raise_on_empty(self): with self.assertRaises(ValueError): self.b.abs2chroot(None) def test_abs2chroot(self): self.assertEqual( self.b.abs2chroot(''), '' ) self.assertEqual( self.b.abs2chroot('/asdf'), '/asdf' ) self.assertEqual( self.b.abs2chroot('/'), '/' ) def test_get_root(self): with self.assertRaises(RuntimeError): self.b.get_chroot() class SoftChrootEnabledTest(TestCase): def setUp(self): self.b = SoftChroot() self.b.initialize(CHROOT_DIR) def test_enabled(self): self.assertTrue( self.b.enabled) def test_is_subdir(self): self.assertFalse( self.b.is_subdir('') ) self.assertFalse( self.b.is_subdir(None) ) self.assertTrue( self.b.is_subdir(CHROOT_DIR) ) noslash = CHROOT_DIR[:-1] self.assertTrue( self.b.is_subdir(noslash) ) self.assertTrue( self.b.is_subdir(CHROOT_DIR + 'come') ) def test_is_root_abs_none(self): with self.assertRaises(ValueError): self.assertFalse( self.b.is_root_abs(None) ) def test_is_root_abs(self): self.assertFalse( self.b.is_root_abs('') ) self.assertTrue( self.b.is_root_abs(CHROOT_DIR) ) noslash = CHROOT_DIR[:-1] self.assertTrue( self.b.is_root_abs(noslash) ) self.assertFalse( self.b.is_root_abs(CHROOT_DIR + 'come') ) def test_chroot2abs_noleading_slash(self): path = 'no_leading_slash' path_sl = CHROOT_DIR + path #with self.assertRaises(ValueError): # self.b.chroot2abs('no_leading_slash') self.assertEqual( self.b.chroot2abs(path), path_sl ) def test_chroot2abs(self): self.assertEqual( self.b.chroot2abs(None), CHROOT_DIR ) self.assertEqual( self.b.chroot2abs(''), CHROOT_DIR ) self.assertEqual( self.b.chroot2abs('/asdf'), CHROOT_DIR + 'asdf' ) def test_abs2chroot_raise_on_empty(self): with self.assertRaises(ValueError): self.b.abs2chroot(None) with self.assertRaises(ValueError): self.b.abs2chroot('') def test_abs2chroot(self): self.assertEqual( self.b.abs2chroot(CHROOT_DIR + 'asdf'), '/asdf' ) self.assertEqual( self.b.abs2chroot(CHROOT_DIR), '/' ) self.assertEqual( self.b.abs2chroot(CHROOT_DIR.rstrip(os.path.sep)), '/' ) def test_get_root(self): self.assertEqual( self.b.get_chroot(), CHROOT_DIR )
3,849
Python
.py
90
34.944444
82
0.649772
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,788
__init__.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/__init__.py
import os import traceback from couchpotato import CPLog, md5 from couchpotato.core.event import addEvent, fireEvent, fireEventAsync from couchpotato.core.helpers.encoding import toUnicode from couchpotato.core.helpers.variable import getExt from couchpotato.core.plugins.base import Plugin import six log = CPLog(__name__) class MediaBase(Plugin): _type = None def initType(self): addEvent('media.types', self.getType) def getType(self): return self._type def createOnComplete(self, media_id): def onComplete(): try: media = fireEvent('media.get', media_id, single = True) if media: event_name = '%s.searcher.single' % media.get('type') fireEventAsync(event_name, media, on_complete = self.createNotifyFront(media_id), manual = True) except: log.error('Failed creating onComplete: %s', traceback.format_exc()) return onComplete def createNotifyFront(self, media_id): def notifyFront(): try: media = fireEvent('media.get', media_id, single = True) if media: event_name = '%s.update' % media.get('type') fireEvent('notify.frontend', type = event_name, data = media) except: log.error('Failed creating onComplete: %s', traceback.format_exc()) return notifyFront def getDefaultTitle(self, info, default_title = None): # Set default title default_title = default_title if default_title else toUnicode(info.get('title')) titles = info.get('titles', []) counter = 0 def_title = None for title in titles: if (len(default_title) == 0 and counter == 0) or len(titles) == 1 or title.lower() == toUnicode(default_title.lower()) or (toUnicode(default_title) == six.u('') and toUnicode(titles[0]) == title): def_title = toUnicode(title) break counter += 1 if not def_title and titles and len(titles) > 0: def_title = toUnicode(titles[0]) return def_title or 'UNKNOWN' def getPoster(self, media, image_urls): if 'files' not in media: media['files'] = {} existing_files = media['files'] image_type = 'poster' file_type = 'image_%s' % image_type # Make existing unique unique_files = list(set(existing_files.get(file_type, []))) # Remove files that can't be found for ef in unique_files: if not os.path.isfile(ef): unique_files.remove(ef) # Replace new files list existing_files[file_type] = unique_files if len(existing_files) == 0: del existing_files[file_type] images = image_urls.get(image_type, []) for y in ['SX300', 'tmdb']: initially_try = [x for x in images if y in x] images[:-1] = initially_try # Loop over type for image in images: if not isinstance(image, (str, unicode)): continue # Check if it has top image filename = '%s.%s' % (md5(image), getExt(image)) existing = existing_files.get(file_type, []) has_latest = False for x in existing: if filename in x: has_latest = True if not has_latest or file_type not in existing_files or len(existing_files.get(file_type, [])) == 0: file_path = fireEvent('file.download', url = image, single = True) if file_path: existing_files[file_type] = [toUnicode(file_path)] break else: break
3,818
Python
.py
87
32.632184
208
0.57764
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,789
index.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/media/index.py
from string import ascii_letters from hashlib import md5 from CodernityDB.tree_index import MultiTreeBasedIndex, TreeBasedIndex from couchpotato.core.helpers.encoding import toUnicode, simplifyString class MediaIndex(MultiTreeBasedIndex): _version = 3 custom_header = """from CodernityDB.tree_index import MultiTreeBasedIndex""" def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(MediaIndex, self).__init__(*args, **kwargs) def make_key(self, key): return md5(key).hexdigest() def make_key_value(self, data): if data.get('_t') == 'media' and (data.get('identifier') or data.get('identifiers')): identifiers = data.get('identifiers', {}) if data.get('identifier') and 'imdb' not in identifiers: identifiers['imdb'] = data.get('identifier') ids = [] for x in identifiers: ids.append(md5('%s-%s' % (x, identifiers[x])).hexdigest()) return ids, None class MediaStatusIndex(TreeBasedIndex): _version = 1 def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(MediaStatusIndex, self).__init__(*args, **kwargs) def make_key(self, key): return md5(key).hexdigest() def make_key_value(self, data): if data.get('_t') == 'media' and data.get('status'): return md5(data.get('status')).hexdigest(), None class MediaTypeIndex(TreeBasedIndex): _version = 1 def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(MediaTypeIndex, self).__init__(*args, **kwargs) def make_key(self, key): return md5(key).hexdigest() def make_key_value(self, data): if data.get('_t') == 'media' and data.get('type'): return md5(data.get('type')).hexdigest(), None class TitleSearchIndex(MultiTreeBasedIndex): _version = 1 custom_header = """from CodernityDB.tree_index import MultiTreeBasedIndex from itertools import izip from couchpotato.core.helpers.encoding import simplifyString""" def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(TitleSearchIndex, self).__init__(*args, **kwargs) self.__l = kwargs.get('w_len', 2) def make_key_value(self, data): if data.get('_t') == 'media' and len(data.get('title', '')) > 0: out = set() title = str(simplifyString(data.get('title').lower())) l = self.__l title_split = title.split() for x in range(len(title_split)): combo = ' '.join(title_split[x:])[:32].strip() out.add(combo.rjust(32, '_')) combo_range = max(l, min(len(combo), 32)) for cx in range(1, combo_range): ccombo = combo[:-cx].strip() if len(ccombo) > l: out.add(ccombo.rjust(32, '_')) return out, None def make_key(self, key): return key.rjust(32, '_').lower() class TitleIndex(TreeBasedIndex): _version = 4 custom_header = """from CodernityDB.tree_index import TreeBasedIndex from string import ascii_letters from couchpotato.core.helpers.encoding import toUnicode, simplifyString""" def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(TitleIndex, self).__init__(*args, **kwargs) def make_key(self, key): return self.simplify(key) def make_key_value(self, data): if data.get('_t') == 'media' and data.get('title') is not None and len(data.get('title')) > 0: return self.simplify(data['title']), None def simplify(self, title): title = toUnicode(title) nr_prefix = '' if title and len(title) > 0 and title[0] in ascii_letters else '#' title = simplifyString(title) for prefix in ['the ', 'an ', 'a ']: if prefix == title[:len(prefix)]: title = title[len(prefix):] break return str(nr_prefix + title).ljust(32, ' ')[:32] class StartsWithIndex(TreeBasedIndex): _version = 3 custom_header = """from CodernityDB.tree_index import TreeBasedIndex from string import ascii_letters from couchpotato.core.helpers.encoding import toUnicode, simplifyString""" def __init__(self, *args, **kwargs): kwargs['key_format'] = '1s' super(StartsWithIndex, self).__init__(*args, **kwargs) def make_key(self, key): return self.first(key) def make_key_value(self, data): if data.get('_t') == 'media' and data.get('title') is not None: return self.first(data['title']), None def first(self, title): title = toUnicode(title) title = simplifyString(title) for prefix in ['the ', 'an ', 'a ']: if prefix == title[:len(prefix)]: title = title[len(prefix):] break return str(title[0] if title and len(title) > 0 and title[0] in ascii_letters else '#').lower() class MediaChildrenIndex(TreeBasedIndex): _version = 1 def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(MediaChildrenIndex, self).__init__(*args, **kwargs) def make_key(self, key): return key def make_key_value(self, data): if data.get('_t') == 'media' and data.get('parent_id'): return data.get('parent_id'), None class MediaTagIndex(MultiTreeBasedIndex): _version = 2 custom_header = """from CodernityDB.tree_index import MultiTreeBasedIndex""" def __init__(self, *args, **kwargs): kwargs['key_format'] = '32s' super(MediaTagIndex, self).__init__(*args, **kwargs) def make_key_value(self, data): if data.get('_t') == 'media' and data.get('tags') and len(data.get('tags', [])) > 0: tags = set() for tag in data.get('tags', []): tags.add(self.make_key(tag)) return list(tags), None def make_key(self, key): return md5(key).hexdigest()
6,107
Python
.py
134
36.746269
103
0.59868
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,790
main.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/media/main.py
from datetime import timedelta import time import traceback from string import ascii_lowercase from CodernityDB.database import RecordNotFound, RecordDeleted from couchpotato import tryInt, get_db from couchpotato.api import addApiView from couchpotato.core.event import fireEvent, fireEventAsync, addEvent from couchpotato.core.helpers.encoding import toUnicode from couchpotato.core.helpers.variable import splitString, getImdb, getTitle from couchpotato.core.logger import CPLog from couchpotato.core.media import MediaBase from .index import MediaIndex, MediaStatusIndex, MediaTypeIndex, TitleSearchIndex, TitleIndex, StartsWithIndex, MediaChildrenIndex, MediaTagIndex log = CPLog(__name__) class MediaPlugin(MediaBase): _database = { 'media': MediaIndex, 'media_search_title': TitleSearchIndex, 'media_status': MediaStatusIndex, 'media_tag': MediaTagIndex, 'media_by_type': MediaTypeIndex, 'media_title': TitleIndex, 'media_startswith': StartsWithIndex, 'media_children': MediaChildrenIndex, } def __init__(self): addApiView('media.refresh', self.refresh, docs = { 'desc': 'Refresh a any media type by ID', 'params': { 'id': {'desc': 'Movie, Show, Season or Episode ID(s) you want to refresh.', 'type': 'int (comma separated)'}, } }) addApiView('media.list', self.listView, docs = { 'desc': 'List media', 'params': { 'type': {'type': 'string', 'desc': 'Media type to filter on.'}, 'status': {'type': 'array or csv', 'desc': 'Filter media by status. Example:"active,done"'}, 'release_status': {'type': 'array or csv', 'desc': 'Filter media by status of its releases. Example:"snatched,available"'}, 'limit_offset': {'desc': 'Limit and offset the media list. Examples: "50" or "50,30"'}, 'starts_with': {'desc': 'Starts with these characters. Example: "a" returns all media starting with the letter "a"'}, 'search': {'desc': 'Search media title'}, }, 'return': {'type': 'object', 'example': """{ 'success': True, 'empty': bool, any media returned or not, 'media': array, media found, }"""} }) addApiView('media.get', self.getView, docs = { 'desc': 'Get media by id', 'params': { 'id': {'desc': 'The id of the media'}, } }) addApiView('media.delete', self.deleteView, docs = { 'desc': 'Delete a media from the wanted list', 'params': { 'id': {'desc': 'Media ID(s) you want to delete.', 'type': 'int (comma separated)'}, 'delete_from': {'desc': 'Delete media from this page', 'type': 'string: all (default), wanted, manage'}, } }) addApiView('media.available_chars', self.charView) addEvent('app.load', self.addSingleRefreshView, priority = 100) addEvent('app.load', self.addSingleListView, priority = 100) addEvent('app.load', self.addSingleCharView, priority = 100) addEvent('app.load', self.addSingleDeleteView, priority = 100) addEvent('app.load', self.cleanupFaults) addEvent('media.get', self.get) addEvent('media.with_status', self.withStatus) addEvent('media.with_identifiers', self.withIdentifiers) addEvent('media.list', self.list) addEvent('media.delete', self.delete) addEvent('media.restatus', self.restatus) addEvent('media.tag', self.tag) addEvent('media.untag', self.unTag) # Wrongly tagged media files def cleanupFaults(self): medias = fireEvent('media.with_status', 'ignored', single = True) or [] db = get_db() for media in medias: try: media['status'] = 'done' db.update(media) except: pass def refresh(self, id = '', **kwargs): handlers = [] ids = splitString(id) for x in ids: refresh_handler = self.createRefreshHandler(x) if refresh_handler: handlers.append(refresh_handler) fireEvent('notify.frontend', type = 'media.busy', data = {'_id': ids}) fireEventAsync('schedule.queue', handlers = handlers) return { 'success': True, } def createRefreshHandler(self, media_id): try: media = get_db().get('id', media_id) event = '%s.update' % media.get('type') def handler(): fireEvent(event, media_id = media_id, on_complete = self.createOnComplete(media_id)) return handler except: log.error('Refresh handler for non existing media: %s', traceback.format_exc()) def addSingleRefreshView(self): for media_type in fireEvent('media.types', merge = True): addApiView('%s.refresh' % media_type, self.refresh) def get(self, media_id): try: db = get_db() imdb_id = getImdb(str(media_id)) if imdb_id: media = db.get('media', 'imdb-%s' % imdb_id, with_doc = True)['doc'] else: media = db.get('id', media_id) if media: # Attach category try: media['category'] = db.get('id', media.get('category_id')) except: pass media['releases'] = fireEvent('release.for_media', media['_id'], single = True) return media except (RecordNotFound, RecordDeleted): log.error('Media with id "%s" not found', media_id) except: raise def getView(self, id = None, **kwargs): media = self.get(id) if id else None return { 'success': media is not None, 'media': media, } def withStatus(self, status, types = None, with_doc = True): db = get_db() if types and not isinstance(types, (list, tuple)): types = [types] status = list(status if isinstance(status, (list, tuple)) else [status]) for s in status: for ms in db.get_many('media_status', s): if with_doc: try: doc = db.get('id', ms['_id']) if types and doc.get('type') not in types: continue yield doc except (RecordDeleted, RecordNotFound): log.debug('Record not found, skipping: %s', ms['_id']) except (ValueError, EOFError): fireEvent('database.delete_corrupted', ms.get('_id'), traceback_error = traceback.format_exc(0)) else: yield ms def withIdentifiers(self, identifiers, with_doc = False): db = get_db() for x in identifiers: try: return db.get('media', '%s-%s' % (x, identifiers[x]), with_doc = with_doc) except: pass log.debug('No media found with identifiers: %s', identifiers) return False def list(self, types = None, status = None, release_status = None, status_or = False, limit_offset = None, with_tags = None, starts_with = None, search = None): db = get_db() # Make a list from string if status and not isinstance(status, (list, tuple)): status = [status] if release_status and not isinstance(release_status, (list, tuple)): release_status = [release_status] if types and not isinstance(types, (list, tuple)): types = [types] if with_tags and not isinstance(with_tags, (list, tuple)): with_tags = [with_tags] # query media ids if types: all_media_ids = set() for media_type in types: all_media_ids = all_media_ids.union(set([x['_id'] for x in db.get_many('media_by_type', media_type)])) else: all_media_ids = set([x['_id'] for x in db.all('media')]) media_ids = list(all_media_ids) filter_by = {} # Filter on movie status if status and len(status) > 0: filter_by['media_status'] = set() for media_status in fireEvent('media.with_status', status, with_doc = False, single = True): filter_by['media_status'].add(media_status.get('_id')) # Filter on release status if release_status and len(release_status) > 0: filter_by['release_status'] = set() for release_status in fireEvent('release.with_status', release_status, with_doc = False, single = True): filter_by['release_status'].add(release_status.get('media_id')) # Add search filters if starts_with: starts_with = toUnicode(starts_with.lower())[0] starts_with = starts_with if starts_with in ascii_lowercase else '#' filter_by['starts_with'] = [x['_id'] for x in db.get_many('media_startswith', starts_with)] # Add tag filter if with_tags: filter_by['with_tags'] = set() for tag in with_tags: for x in db.get_many('media_tag', tag): filter_by['with_tags'].add(x['_id']) # Filter with search query if search: filter_by['search'] = [x['_id'] for x in db.get_many('media_search_title', search)] if status_or and 'media_status' in filter_by and 'release_status' in filter_by: filter_by['status'] = list(filter_by['media_status']) + list(filter_by['release_status']) del filter_by['media_status'] del filter_by['release_status'] # Filter by combining ids for x in filter_by: media_ids = [n for n in media_ids if n in filter_by[x]] total_count = len(media_ids) if total_count == 0: return 0, [] offset = 0 limit = -1 if limit_offset: splt = splitString(limit_offset) if isinstance(limit_offset, (str, unicode)) else limit_offset limit = tryInt(splt[0]) offset = tryInt(0 if len(splt) is 1 else splt[1]) # List movies based on title order medias = [] for m in db.all('media_title'): media_id = m['_id'] if media_id not in media_ids: continue if offset > 0: offset -= 1 continue media = fireEvent('media.get', media_id, single = True) # Skip if no media has been found if not media: continue # Merge releases with movie dict medias.append(media) # remove from media ids media_ids.remove(media_id) if len(media_ids) == 0 or len(medias) == limit: break return total_count, medias def listView(self, **kwargs): total_movies, movies = self.list( types = splitString(kwargs.get('type')), status = splitString(kwargs.get('status')), release_status = splitString(kwargs.get('release_status')), status_or = kwargs.get('status_or') is not None, limit_offset = kwargs.get('limit_offset'), with_tags = splitString(kwargs.get('with_tags')), starts_with = kwargs.get('starts_with'), search = kwargs.get('search') ) return { 'success': True, 'empty': len(movies) == 0, 'total': total_movies, 'movies': movies, } def addSingleListView(self): for media_type in fireEvent('media.types', merge = True): tempList = lambda *args, **kwargs : self.listView(type = media_type, **kwargs) addApiView('%s.list' % media_type, tempList, docs = { 'desc': 'List media', 'params': { 'status': {'type': 'array or csv', 'desc': 'Filter ' + media_type + ' by status. Example:"active,done"'}, 'release_status': {'type': 'array or csv', 'desc': 'Filter ' + media_type + ' by status of its releases. Example:"snatched,available"'}, 'limit_offset': {'desc': 'Limit and offset the ' + media_type + ' list. Examples: "50" or "50,30"'}, 'starts_with': {'desc': 'Starts with these characters. Example: "a" returns all ' + media_type + 's starting with the letter "a"'}, 'search': {'desc': 'Search ' + media_type + ' title'}, }, 'return': {'type': 'object', 'example': """{ 'success': True, 'empty': bool, any """ + media_type + """s returned or not, 'media': array, media found, }"""} }) def availableChars(self, types = None, status = None, release_status = None): db = get_db() # Make a list from string if status and not isinstance(status, (list, tuple)): status = [status] if release_status and not isinstance(release_status, (list, tuple)): release_status = [release_status] if types and not isinstance(types, (list, tuple)): types = [types] # query media ids if types: all_media_ids = set() for media_type in types: all_media_ids = all_media_ids.union(set([x['_id'] for x in db.get_many('media_by_type', media_type)])) else: all_media_ids = set([x['_id'] for x in db.all('media')]) media_ids = all_media_ids filter_by = {} # Filter on movie status if status and len(status) > 0: filter_by['media_status'] = set() for media_status in fireEvent('media.with_status', status, with_doc = False, single = True): filter_by['media_status'].add(media_status.get('_id')) # Filter on release status if release_status and len(release_status) > 0: filter_by['release_status'] = set() for release_status in fireEvent('release.with_status', release_status, with_doc = False, single = True): filter_by['release_status'].add(release_status.get('media_id')) # Filter by combining ids for x in filter_by: media_ids = [n for n in media_ids if n in filter_by[x]] chars = set() for x in db.all('media_startswith'): if x['_id'] in media_ids: chars.add(x['key']) if len(chars) == 27: break return list(chars) def charView(self, **kwargs): type = splitString(kwargs.get('type', 'movie')) status = splitString(kwargs.get('status', None)) release_status = splitString(kwargs.get('release_status', None)) chars = self.availableChars(type, status, release_status) return { 'success': True, 'empty': len(chars) == 0, 'chars': chars, } def addSingleCharView(self): for media_type in fireEvent('media.types', merge = True): tempChar = lambda *args, **kwargs : self.charView(type = media_type, **kwargs) addApiView('%s.available_chars' % media_type, tempChar) def delete(self, media_id, delete_from = None): try: db = get_db() media = db.get('id', media_id) if media: deleted = False media_releases = fireEvent('release.for_media', media['_id'], single = True) if delete_from == 'all': # Delete connected releases for release in media_releases: db.delete(release) db.delete(media) deleted = True else: total_releases = len(media_releases) total_deleted = 0 new_media_status = None for release in media_releases: if delete_from in ['wanted', 'snatched', 'late']: if release.get('status') != 'done': db.delete(release) total_deleted += 1 new_media_status = 'done' elif delete_from == 'manage': if release.get('status') == 'done' or media.get('status') == 'done': db.delete(release) total_deleted += 1 if (total_releases == total_deleted) or (total_releases == 0 and not new_media_status) or (not new_media_status and delete_from == 'late'): db.delete(media) deleted = True elif new_media_status: media['status'] = new_media_status # Remove profile (no use for in manage) if new_media_status == 'done': media['profile_id'] = None db.update(media) fireEvent('media.untag', media['_id'], 'recent', single = True) else: fireEvent('media.restatus', media.get('_id'), single = True) if deleted: fireEvent('notify.frontend', type = 'media.deleted', data = media) except: log.error('Failed deleting media: %s', traceback.format_exc()) return True def deleteView(self, id = '', **kwargs): ids = splitString(id) for media_id in ids: self.delete(media_id, delete_from = kwargs.get('delete_from', 'all')) return { 'success': True, } def addSingleDeleteView(self): for media_type in fireEvent('media.types', merge = True): tempDelete = lambda *args, **kwargs : self.deleteView(type = media_type, **kwargs) addApiView('%s.delete' % media_type, tempDelete, docs = { 'desc': 'Delete a ' + media_type + ' from the wanted list', 'params': { 'id': {'desc': 'Media ID(s) you want to delete.', 'type': 'int (comma separated)'}, 'delete_from': {'desc': 'Delete ' + media_type + ' from this page', 'type': 'string: all (default), wanted, manage'}, } }) def restatus(self, media_id, tag_recent = True, allowed_restatus = None): try: db = get_db() m = db.get('id', media_id) previous_status = m['status'] log.debug('Changing status for %s', getTitle(m)) if not m['profile_id']: m['status'] = 'done' else: m['status'] = 'active' try: profile = db.get('id', m['profile_id']) media_releases = fireEvent('release.for_media', m['_id'], single = True) done_releases = [release for release in media_releases if release.get('status') == 'done'] if done_releases: # Check if we are finished with the media for release in done_releases: if fireEvent('quality.isfinish', {'identifier': release['quality'], 'is_3d': release.get('is_3d', False)}, profile, timedelta(seconds = time.time() - release['last_edit']).days, single = True): m['status'] = 'done' break elif previous_status == 'done': m['status'] = 'done' except RecordNotFound: log.debug('Failed restatus, keeping previous: %s', traceback.format_exc()) m['status'] = previous_status # Only update when status has changed if previous_status != m['status'] and (not allowed_restatus or m['status'] in allowed_restatus): db.update(m) # Tag media as recent if tag_recent: self.tag(media_id, 'recent', update_edited = True) return m['status'] except: log.error('Failed restatus: %s', traceback.format_exc()) def tag(self, media_id, tag, update_edited = False): try: db = get_db() m = db.get('id', media_id) if update_edited: m['last_edit'] = int(time.time()) tags = m.get('tags') or [] if tag not in tags: tags.append(tag) m['tags'] = tags db.update(m) return True except: log.error('Failed tagging: %s', traceback.format_exc()) return False def unTag(self, media_id, tag): try: db = get_db() m = db.get('id', media_id) tags = m.get('tags') or [] if tag in tags: new_tags = list(set(tags)) new_tags.remove(tag) m['tags'] = new_tags db.update(m) return True except: log.error('Failed untagging: %s', traceback.format_exc()) return False
21,493
Python
.py
450
34.508889
221
0.535983
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,791
__init__.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/searcher/__init__.py
from .main import Searcher def autoload(): return Searcher() config = [{ 'name': 'searcher', 'order': 20, 'groups': [ { 'tab': 'searcher', 'name': 'searcher', 'label': 'Basics', 'description': 'General search options', 'options': [ { 'name': 'preferred_method', 'label': 'First search', 'description': 'Which of the methods do you prefer', 'default': 'both', 'type': 'dropdown', 'values': [('usenet & torrents', 'both'), ('usenet', 'nzb'), ('torrents', 'torrent')], }, ], }, { 'tab': 'searcher', 'subtab': 'category', 'subtab_label': 'Categories', 'name': 'filter', 'label': 'Global filters', 'description': 'Prefer, ignore & required words in release names', 'options': [ { 'name': 'preferred_words', 'label': 'Preferred', 'default': '', 'placeholder': 'Example: CtrlHD, Amiable, Wiki', 'description': 'Words that give the releases a higher score.' }, { 'name': 'required_words', 'label': 'Required', 'default': '', 'placeholder': 'Example: DTS, AC3 & English', 'description': 'Release should contain at least one set of words. Sets are separated by "," and each word within a set must be separated with "&"' }, { 'name': 'ignored_words', 'label': 'Ignored', 'default': 'german, dutch, french, truefrench, danish, swedish, spanish, italian, korean, dubbed, swesub, korsub, dksubs, vain, HC', 'description': 'Ignores releases that match any of these sets. (Works like explained above)' }, ], }, ], }, { 'name': 'nzb', 'groups': [ { 'tab': 'searcher', 'name': 'searcher', 'label': 'NZB', 'wizard': True, 'options': [ { 'name': 'retention', 'label': 'Usenet Retention', 'default': 1500, 'type': 'int', 'unit': 'days' }, ], }, ], }, { 'name': 'torrent', 'groups': [ { 'tab': 'searcher', 'name': 'searcher', 'wizard': True, 'options': [ { 'name': 'minimum_seeders', 'advanced': True, 'label': 'Minimum seeders', 'description': 'Ignore torrents with seeders below this number', 'default': 1, 'type': 'int', 'unit': 'seeders' }, ], }, ], }]
3,170
Python
.py
93
19.806452
166
0.398178
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,792
base.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/searcher/base.py
from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin log = CPLog(__name__) class SearcherBase(Plugin): in_progress = False def __init__(self): super(SearcherBase, self).__init__() addEvent('searcher.progress', self.getProgress) addEvent('%s.searcher.progress' % self.getType(), self.getProgress) self.initCron() def initCron(self): """ Set the searcher cronjob Make sure to reset cronjob after setting has changed """ _type = self.getType() def setCrons(): fireEvent('schedule.cron', '%s.searcher.all' % _type, self.searchAll, day = self.conf('cron_day'), hour = self.conf('cron_hour'), minute = self.conf('cron_minute')) addEvent('app.load', setCrons) addEvent('setting.save.%s_searcher.cron_day.after' % _type, setCrons) addEvent('setting.save.%s_searcher.cron_hour.after' % _type, setCrons) addEvent('setting.save.%s_searcher.cron_minute.after' % _type, setCrons) def getProgress(self, **kwargs): """ Return progress of current searcher""" progress = { self.getType(): self.in_progress } return progress
1,316
Python
.py
29
36.931034
116
0.641005
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,793
main.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/searcher/main.py
import datetime import re from couchpotato.api import addApiView from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.encoding import simplifyString from couchpotato.core.helpers.variable import splitString, removeEmpty, removeDuplicate from couchpotato.core.logger import CPLog from couchpotato.core.media._base.searcher.base import SearcherBase log = CPLog(__name__) class Searcher(SearcherBase): # noinspection PyMissingConstructor def __init__(self): addEvent('searcher.protocols', self.getSearchProtocols) addEvent('searcher.contains_other_quality', self.containsOtherQuality) addEvent('searcher.correct_3d', self.correct3D) addEvent('searcher.correct_year', self.correctYear) addEvent('searcher.correct_name', self.correctName) addEvent('searcher.correct_words', self.correctWords) addEvent('searcher.search', self.search) addApiView('searcher.full_search', self.searchAllView, docs = { 'desc': 'Starts a full search for all media', }) addApiView('searcher.progress', self.getProgressForAll, docs = { 'desc': 'Get the progress of all media searches', 'return': {'type': 'object', 'example': """{ 'movie': False || object, total & to_go, 'show': False || object, total & to_go, }"""}, }) def searchAllView(self): results = {} for _type in fireEvent('media.types'): results[_type] = fireEvent('%s.searcher.all_view' % _type) return results def getProgressForAll(self): progress = fireEvent('searcher.progress', merge = True) return progress def search(self, protocols, media, quality): results = [] for search_protocol in protocols: protocol_results = fireEvent('provider.search.%s.%s' % (search_protocol, media.get('type')), media, quality, merge = True) if protocol_results: results += protocol_results sorted_results = sorted(results, key = lambda k: k['score'], reverse = True) download_preference = self.conf('preferred_method', section = 'searcher') if download_preference != 'both': sorted_results = sorted(sorted_results, key = lambda k: k['protocol'][:3], reverse = (download_preference == 'torrent')) return sorted_results def getSearchProtocols(self): download_protocols = fireEvent('download.enabled_protocols', merge = True) provider_protocols = fireEvent('provider.enabled_protocols', merge = True) if download_protocols and len(list(set(provider_protocols) & set(download_protocols))) == 0: log.error('There aren\'t any providers enabled for your downloader (%s). Check your settings.', ','.join(download_protocols)) return [] for useless_provider in list(set(provider_protocols) - set(download_protocols)): log.debug('Provider for "%s" enabled, but no downloader.', useless_provider) search_protocols = download_protocols if len(search_protocols) == 0: log.error('There aren\'t any downloaders enabled. Please pick one in settings.') return [] return search_protocols def containsOtherQuality(self, nzb, movie_year = None, preferred_quality = None): if not preferred_quality: preferred_quality = {} found = {} # Try guessing via quality tags guess = fireEvent('quality.guess', files = [nzb.get('name')], size = nzb.get('size', None), single = True) if guess: found[guess['identifier']] = True # Hack for older movies that don't contain quality tag name = nzb['name'] size = nzb.get('size', 0) year_name = fireEvent('scanner.name_year', name, single = True) if len(found) == 0 and movie_year < datetime.datetime.now().year - 3 and not year_name.get('year', None): if size > 20000: # Assume bd50 log.info('Quality was missing in name, assuming it\'s a BR-Disk based on the size: %s', size) found['bd50'] = True elif size > 3000: # Assume dvdr log.info('Quality was missing in name, assuming it\'s a DVD-R based on the size: %s', size) found['dvdr'] = True else: # Assume dvdrip log.info('Quality was missing in name, assuming it\'s a DVD-Rip based on the size: %s', size) found['dvdrip'] = True # Allow other qualities for allowed in preferred_quality.get('allow'): if found.get(allowed): del found[allowed] if found.get(preferred_quality['identifier']) and len(found) == 1: return False return found def correct3D(self, nzb, preferred_quality = None): if not preferred_quality: preferred_quality = {} if not preferred_quality.get('custom'): return threed = preferred_quality['custom'].get('3d') # Try guessing via quality tags guess = fireEvent('quality.guess', [nzb.get('name')], single = True) if guess: return threed == guess.get('is_3d') # If no quality guess, assume not 3d else: return threed == False def correctYear(self, haystack, year, year_range): if not isinstance(haystack, (list, tuple, set)): haystack = [haystack] year_name = {} for string in haystack: year_name = fireEvent('scanner.name_year', string, single = True) if year_name and ((year - year_range) <= year_name.get('year') <= (year + year_range)): log.debug('Movie year matches range: %s looking for %s', (year_name.get('year'), year)) return True log.debug('Movie year doesn\'t matche range: %s looking for %s', (year_name.get('year'), year)) return False def correctName(self, check_name, movie_name): check_names = [check_name] # Match names between " try: check_names.append(re.search(r'([\'"])[^\1]*\1', check_name).group(0)) except: pass # Match longest name between [] try: check_names.append(max(re.findall(r'[^[]*\[([^]]*)\]', check_name), key = len).strip()) except: pass for check_name in removeDuplicate(check_names): check_movie = fireEvent('scanner.name_year', check_name, single = True) try: check_words = removeEmpty(re.split('\W+', check_movie.get('name', ''))) movie_words = removeEmpty(re.split('\W+', simplifyString(movie_name))) if len(check_words) > 0 and len(movie_words) > 0 and len(list(set(check_words) - set(movie_words))) == 0: return True except: pass return False def containsWords(self, rel_name, rel_words, conf, media): # Make sure it has required words words = splitString(self.conf('%s_words' % conf, section = 'searcher').lower()) try: words = removeDuplicate(words + splitString(media['category'][conf].lower())) except: pass req_match = 0 for req_set in words: if len(req_set) >= 2 and (req_set[:1] + req_set[-1:]) == '//': if re.search(req_set[1:-1], rel_name): log.debug('Regex match: %s', req_set[1:-1]) req_match += 1 else: req = splitString(req_set, '&') req_match += len(list(set(rel_words) & set(req))) == len(req) return words, req_match > 0 def correctWords(self, rel_name, media): media_title = fireEvent('searcher.get_search_title', media, single = True) media_words = re.split('\W+', simplifyString(media_title)) rel_name = simplifyString(rel_name) rel_words = re.split('\W+', rel_name) required_words, contains_required = self.containsWords(rel_name, rel_words, 'required', media) if len(required_words) > 0 and not contains_required: log.info2('Wrong: Required word missing: %s', rel_name) return False ignored_words, contains_ignored = self.containsWords(rel_name, rel_words, 'ignored', media) if len(ignored_words) > 0 and contains_ignored: log.info2("Wrong: '%s' contains 'ignored words'", rel_name) return False # Ignore porn stuff pron_tags = ['xxx', 'sex', 'anal', 'tits', 'fuck', 'porn', 'orgy', 'milf', 'boobs', 'erotica', 'erotic', 'cock', 'dick'] pron_words = list(set(rel_words) & set(pron_tags) - set(media_words)) if pron_words: log.info('Wrong: %s, probably pr0n', rel_name) return False return True class SearchSetupError(Exception): pass
8,876
Python
.py
166
43.186747
137
0.613713
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,794
__init__.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/matcher/__init__.py
from .main import Matcher def autoload(): return Matcher() config = []
78
Python
.py
4
16.75
25
0.71831
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,795
base.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/matcher/base.py
from couchpotato.core.event import addEvent from couchpotato.core.helpers.encoding import simplifyString from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin log = CPLog(__name__) class MatcherBase(Plugin): type = None def __init__(self): if self.type: addEvent('%s.matcher.correct' % self.type, self.correct) def correct(self, chain, release, media, quality): raise NotImplementedError() def flattenInfo(self, info): # Flatten dictionary of matches (chain info) if isinstance(info, dict): return dict([(key, self.flattenInfo(value)) for key, value in info.items()]) # Flatten matches result = None for match in info: if isinstance(match, dict): if result is None: result = {} for key, value in match.items(): if key not in result: result[key] = [] result[key].append(value) else: if result is None: result = [] result.append(match) return result def constructFromRaw(self, match): if not match: return None parts = [ ''.join([ y for y in x[1:] if y ]) for x in match ] return ''.join(parts)[:-1].strip() def simplifyValue(self, value): if not value: return value if isinstance(value, basestring): return simplifyString(value) if isinstance(value, list): return [self.simplifyValue(x) for x in value] raise ValueError("Unsupported value type") def chainMatch(self, chain, group, tags): info = self.flattenInfo(chain.info[group]) found_tags = [] for tag, accepted in tags.items(): values = [self.simplifyValue(x) for x in info.get(tag, [None])] if any([val in accepted for val in values]): found_tags.append(tag) log.debug('tags found: %s, required: %s' % (found_tags, tags.keys())) if set(tags.keys()) == set(found_tags): return True return all([key in found_tags for key, value in tags.items()])
2,320
Python
.py
59
28.40678
88
0.570215
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,796
main.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/matcher/main.py
from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.variable import possibleTitles from couchpotato.core.logger import CPLog from couchpotato.core.media._base.matcher.base import MatcherBase from caper import Caper log = CPLog(__name__) class Matcher(MatcherBase): def __init__(self): super(Matcher, self).__init__() self.caper = Caper() addEvent('matcher.parse', self.parse) addEvent('matcher.match', self.match) addEvent('matcher.flatten_info', self.flattenInfo) addEvent('matcher.construct_from_raw', self.constructFromRaw) addEvent('matcher.correct_title', self.correctTitle) addEvent('matcher.correct_quality', self.correctQuality) def parse(self, name, parser='scene'): return self.caper.parse(name, parser) def match(self, release, media, quality): match = fireEvent('matcher.parse', release['name'], single = True) if len(match.chains) < 1: log.info2('Wrong: %s, unable to parse release name (no chains)', release['name']) return False for chain in match.chains: if fireEvent('%s.matcher.correct' % media['type'], chain, release, media, quality, single = True): return chain return False def correctTitle(self, chain, media): root = fireEvent('library.root', media, single = True) if 'show_name' not in chain.info or not len(chain.info['show_name']): log.info('Wrong: missing show name in parsed result') return False # Get the lower-case parsed show name from the chain chain_words = [x.lower() for x in chain.info['show_name']] # Build a list of possible titles of the media we are searching for titles = root['info']['titles'] # Add year suffix titles (will result in ['<name_one>', '<name_one> <suffix_one>', '<name_two>', ...]) suffixes = [None, root['info']['year']] titles = [ title + ((' %s' % suffix) if suffix else '') for title in titles for suffix in suffixes ] # Check show titles match # TODO check xem names for title in titles: for valid_words in [x.split(' ') for x in possibleTitles(title)]: if valid_words == chain_words: return True return False def correctQuality(self, chain, quality, quality_map): if quality['identifier'] not in quality_map: log.info2('Wrong: unknown preferred quality %s', quality['identifier']) return False if 'video' not in chain.info: log.info2('Wrong: no video tags found') return False video_tags = quality_map[quality['identifier']] if not self.chainMatch(chain, 'video', video_tags): log.info2('Wrong: %s tags not in chain', video_tags) return False return True
2,988
Python
.py
62
38.564516
110
0.625733
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,797
base.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/providers/base.py
from urlparse import urlparse import json import re from requests import HTTPError import time import traceback import xml.etree.ElementTree as XMLTree try: from xml.etree.ElementTree import ParseError as XmlParseError except ImportError: from xml.parsers.expat import ExpatError as XmlParseError from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.encoding import ss from couchpotato.core.helpers.variable import tryFloat, mergeDicts, md5, \ possibleTitles from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env log = CPLog(__name__) class MultiProvider(Plugin): def __init__(self): self._classes = [] for Type in self.getTypes(): klass = Type() # Overwrite name so logger knows what we're talking about klass.setName('%s:%s' % (self.getName(), klass.getName())) self._classes.append(klass) def getTypes(self): return [] def getClasses(self): return self._classes class Provider(Plugin): type = None # movie, show, subtitle, trailer, ... http_time_between_calls = 10 # Default timeout for url requests last_available_check = {} is_available = {} def isAvailable(self, test_url): if Env.get('dev'): return True now = time.time() host = urlparse(test_url).hostname if self.last_available_check.get(host) < now - 900: self.last_available_check[host] = now try: self.urlopen(test_url, 30) self.is_available[host] = True except: log.error('"%s" unavailable, trying again in an 15 minutes.', host) self.is_available[host] = False return self.is_available.get(host, False) def getJsonData(self, url, decode_from = None, **kwargs): cache_key = md5(url) data = self.getCache(cache_key, url, **kwargs) if data: try: data = data.strip() if decode_from: data = data.decode(decode_from) return json.loads(data) except: log.error('Failed to parsing %s: %s', (self.getName(), traceback.format_exc())) return [] def getRSSData(self, url, item_path = 'channel/item', **kwargs): cache_key = md5(url) data = self.getCache(cache_key, url, **kwargs) if data and len(data) > 0: try: data = XMLTree.fromstring(data) return self.getElements(data, item_path) except: try: data = XMLTree.fromstring(ss(data)) return self.getElements(data, item_path) except XmlParseError: log.error('Invalid XML returned, check "%s" manually for issues', url) except: log.error('Failed to parsing %s: %s', (self.getName(), traceback.format_exc())) return [] def getHTMLData(self, url, **kwargs): cache_key = md5(url) return self.getCache(cache_key, url, **kwargs) class YarrProvider(Provider): protocol = None # nzb, torrent, torrent_magnet cat_ids = {} cat_backup_id = None size_gb = ['gb', 'gib'] size_mb = ['mb', 'mib'] size_kb = ['kb', 'kib'] last_login_check = None login_failures = 0 login_fail_msg = None def __init__(self): addEvent('provider.enabled_protocols', self.getEnabledProtocol) addEvent('provider.belongs_to', self.belongsTo) addEvent('provider.search.%s.%s' % (self.protocol, self.type), self.search) def getEnabledProtocol(self): if self.isEnabled(): return self.protocol else: return [] def buildUrl(self, *args, **kwargs): pass def login(self): # Check if we are still logged in every hour now = time.time() if self.last_login_check and self.last_login_check < (now - 3600): try: output = self.urlopen(self.urls['login_check']) if self.loginCheckSuccess(output): self.last_login_check = now return True except: pass self.last_login_check = None if self.last_login_check: return True try: output = self.urlopen(self.urls['login'], data = self.getLoginParams()) if self.loginSuccess(output): self.last_login_check = now self.login_failures = 0 return True error = 'unknown' except Exception as e: if isinstance(e, HTTPError): if e.response.status_code >= 400 and e.response.status_code < 500: self.login_failures += 1 if self.login_failures >= 3: self.disableAccount() error = traceback.format_exc() self.last_login_check = None if self.login_fail_msg and self.login_fail_msg in output: error = "Login credentials rejected." self.disableAccount() log.error('Failed to login %s: %s', (self.getName(), error)) return False def loginSuccess(self, output): return True def loginCheckSuccess(self, output): return True def loginDownload(self, url = '', nzb_id = ''): try: if not self.login(): log.error('Failed downloading from %s', self.getName()) return self.urlopen(url) except: log.error('Failed downloading from %s: %s', (self.getName(), traceback.format_exc())) def getLoginParams(self): return {} def download(self, url = '', nzb_id = ''): try: return self.urlopen(url, headers = {'User-Agent': Env.getIdentifier()}, show_error = False) except: log.error('Failed getting release from %s: %s', (self.getName(), traceback.format_exc())) return 'try_next' def search(self, media, quality): if self.isDisabled(): return [] # Login if needed if self.urls.get('login') and not self.login(): log.error('Failed to login to: %s', self.getName()) return [] # Create result container imdb_results = hasattr(self, '_search') results = ResultList(self, media, quality, imdb_results = imdb_results) # Do search based on imdb id if imdb_results: self._search(media, quality, results) # Search possible titles else: media_title = fireEvent('library.query', media, include_year = False, single = True) for title in possibleTitles(media_title): self._searchOnTitle(title, media, quality, results) return results def belongsTo(self, url, provider = None, host = None): try: if provider and provider == self.getName(): return self hostname = urlparse(url).hostname if host and hostname in host: return self else: for url_type in self.urls: download_url = self.urls[url_type] if hostname in download_url: return self except: log.debug('Url %s doesn\'t belong to %s', (url, self.getName())) return def parseSize(self, size): size_raw = size.lower() size = tryFloat(re.sub(r'[^0-9.]', '', size).strip()) for s in self.size_gb: if s in size_raw: return size * 1024 for s in self.size_mb: if s in size_raw: return size for s in self.size_kb: if s in size_raw: return size / 1024 return 0 def getCatId(self, quality = None): if not quality: quality = {} identifier = quality.get('identifier') want_3d = False if quality.get('custom'): want_3d = quality['custom'].get('3d') for ids, qualities in self.cat_ids: if identifier in qualities or (want_3d and '3d' in qualities): return ids if self.cat_backup_id: return [self.cat_backup_id] return [] def disableAccount(self): log.error("Failed %s login, disabling provider. " "Please check the configuration. Re-enabling the " "provider without fixing the problem may result " "in an IP ban, depending on the site.", self.getName()) self.conf(self.enabled_option, False) self.login_failures = 0 class ResultList(list): result_ids = None provider = None media = None quality = None def __init__(self, provider, media, quality, **kwargs): self.result_ids = [] self.provider = provider self.media = media self.quality = quality self.kwargs = kwargs super(ResultList, self).__init__() def extend(self, results): for r in results: self.append(r) def append(self, result): new_result = self.fillResult(result) is_correct = fireEvent('searcher.correct_release', new_result, self.media, self.quality, imdb_results = self.kwargs.get('imdb_results', False), single = True) if is_correct and new_result['id'] not in self.result_ids: is_correct_weight = float(is_correct) new_result['score'] += fireEvent('score.calculate', new_result, self.media, single = True) old_score = new_result['score'] new_result['score'] = int(old_score * is_correct_weight) log.info2('Found correct release with weight %.02f, old_score(%d) now scaled to score(%d)', ( is_correct_weight, old_score, new_result['score'] )) self.found(new_result) self.result_ids.append(result['id']) super(ResultList, self).append(new_result) def fillResult(self, result): defaults = { 'id': 0, 'protocol': self.provider.protocol, 'type': self.provider.type, 'provider': self.provider.getName(), 'download': self.provider.loginDownload if self.provider.urls.get('login') else self.provider.download, 'seed_ratio': Env.setting('seed_ratio', section = self.provider.getName().lower(), default = ''), 'seed_time': Env.setting('seed_time', section = self.provider.getName().lower(), default = ''), 'url': '', 'name': '', 'age': 0, 'size': 0, 'description': '', 'score': 0 } return mergeDicts(defaults, result) def found(self, new_result): if not new_result.get('provider_extra'): new_result['provider_extra'] = '' else: new_result['provider_extra'] = ', %s' % new_result['provider_extra'] log.info('Found: score(%(score)s) on %(provider)s%(provider_extra)s: %(name)s', new_result)
11,332
Python
.py
274
30.510949
115
0.574427
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,798
base.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/providers/userscript/base.py
from urlparse import urlparse from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.encoding import simplifyString from couchpotato.core.helpers.variable import getImdb, md5 from couchpotato.core.logger import CPLog from couchpotato.core.media._base.providers.base import Provider log = CPLog(__name__) class UserscriptBase(Provider): type = 'userscript' version = 1 http_time_between_calls = 0 includes = [] excludes = [] def __init__(self): addEvent('userscript.get_includes', self.getInclude) addEvent('userscript.get_excludes', self.getExclude) addEvent('userscript.get_provider_version', self.getVersion) addEvent('userscript.get_movie_via_url', self.belongsTo) def search(self, name, year = None): result = fireEvent('movie.search', q = '%s %s' % (name, year), limit = 1, merge = True) if len(result) > 0: movie = fireEvent('movie.info', identifier = result[0].get('imdb'), extended = False, merge = True) return movie else: return None def belongsTo(self, url): host = urlparse(url).hostname host_split = host.split('.') if len(host_split) > 2: host = host[len(host_split[0]):] for include in self.includes: if host in include: return self.getMovie(url) return def getUrl(self, url): return self.getCache(md5(simplifyString(url)), url = url) def getMovie(self, url): try: data = self.getUrl(url) except: data = '' return self.getInfo(getImdb(data)) def getInfo(self, identifier): return fireEvent('movie.info', identifier = identifier, extended = False, merge = True) def getInclude(self): return self.includes def getExclude(self): return self.excludes def getVersion(self): return self.version
1,971
Python
.py
50
31.68
111
0.648947
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)
7,799
base.py
CouchPotato_CouchPotatoServer/couchpotato/core/media/_base/providers/metadata/base.py
from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin log = CPLog(__name__) class MetaDataBase(Plugin): pass
153
Python
.py
5
28.2
48
0.806897
CouchPotato/CouchPotatoServer
3,869
1,214
1,266
GPL-3.0
9/5/2024, 5:10:17 PM (Europe/Amsterdam)