code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from decimal import Decimal def round_float(a): return float(Decimal(str(a)).quantize(Decimal('.00'), rounding='ROUND_HALF_UP')) # return 4.55 def isfloat(a): try: a = float(a) except: return False return True def load_time_period(): path = '/root/work_place/zhy/kuaidian/data/feature_data/online_process/sp_period/sp_period.txt' sp_period = [] with open(path,'r',encoding='utf8') as f: for line in f : line = line.strip().split() [begin,end,exp] = line sp_period.append(line) return sp_period def load_info(): data = {} count = 0 with open('/root/anaconda3/lib/python3.8/site-packages/zhy_tool//price_info.txt','r',encoding='utf8') as f : for line in f : line = line.strip().split() count += 1 if count == 1 : continue [prov,month,hours,tag] = line for m in month.split(','): for h in hours.split(','): key = '_'.join([prov,m,h]) if key not in data : data[key] = tag if '.' not in hours: key = '_'.join([prov, m, h + '.5']) data[key] = tag return data def tag_price(province,time): price_tags = load_info() month = time.split('-')[1] month = str(int(month)) [h,m,s] = time.split()[1].split(':') h = int(h) m = int(m) if m >= 30: h = h+0.5 h = str(h) key=province + '_' + month + '_' + h if key in price_tags: return price_tags[key] key =province + '_all_' + h if key in price_tags: return price_tags[key] else: return '2' def get_name(time,province): #time = '2022-06-01 1:15:20' #province = '北京' tag = tag_price(province,time) name= {'4':'尖峰','3':'峰','2':'平','1':'谷'} #print(name[tag]) return name[tag] def str2arr(s): if type(s) is list : return s s = s[1:-1].replace("'","").split(',') return s if __name__ == '__main__': time = '2022-06-01 1:15:20' province = '北京' get_name(time,province)
zhy-tools
/zhy_tools-0.0.2.tar.gz/zhy_tools-0.0.2/price_tag.py
price_tag.py
BOT_NAME = 'scrapy_demo' SPIDER_MODULES = ['scrapy_demo.spiders'] NEWSPIDER_MODULE = 'scrapy_demo.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'scrapy_demo (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: DEFAULT_REQUEST_HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en', } # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'scrapy_demo.middlewares.ScrapyDemoSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'scrapy_demo.middlewares.ScrapyDemoDownloaderMiddleware': 543, #} # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html # ITEM_PIPELINES = { # 'scrapy_demo.pipelines.ScrapyDemoPipeline': 300, # 'scrapy_demo.pipelines.SpiderMongoDemoPipeline': 300, # } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' LOG_LEVEL = 'WARNING' # 重试 RETRY_ENABLED = True RETRY_TIMES = 3 # RETRY_HTTP_CODES = [500, 502, 503, 504, 408, 404]
zhyscrapy
/zhyscrapy-1.0.tar.gz/zhyscrapy-1.0/scrapy_demo/settings.py
settings.py
from scrapy import signals # useful for handling different item types with a single interface from itemadapter import is_item, ItemAdapter class ScrapyDemoSpiderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, or item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Request or item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class ScrapyDemoDownloaderMiddleware: # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): from fake_useragent import UserAgent ua = UserAgent() request.headers['User-Agent'] = ua.random def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
zhyscrapy
/zhyscrapy-1.0.tar.gz/zhyscrapy-1.0/scrapy_demo/middlewares.py
middlewares.py
import json from scrapy import cmdline from scrapy_demo import settings class Spider(object): def __init__(self, file_path): self.file_path = file_path # pipline @staticmethod def change_pipline(pipeline_data: dict): save_type = pipeline_data.get('type') if save_type == 'mongo': settings.HOST = pipeline_data.get('host') settings.PORT = pipeline_data.get('port') settings.DB = pipeline_data.get('db') settings.COLLECTION = pipeline_data.get("collection") settings.ITEM_PIPELINES = { 'scrapy_demo.pipelines.SpiderMongoDemoPipeline': 300, } elif save_type == 'csv': settings.FILE_PATH = pipeline_data.get('file_path') settings.ITEM_PIPELINES = { 'scrapy_demo.pipelines.SpiderCsvPipeline': 300, } elif save_type == 'mysql': pass else: pass # setting @staticmethod def change_setting(json_data: dict): settings.DATAS = json_data.get('datas') settings.RETRY_TIMES = json_data.get('RETRY_TIMES') settings.DOWNLOAD_DELAY = json_data.get('DOWNLOAD_DELAY') headers = json_data.get('DEFAULT_REQUEST_HEADERS') if headers == None: settings.DOWNLOADER_MIDDLEWARES = { 'scrapy_demo.middlewares.ScrapyDemoDownloaderMiddleware': 543, } else: settings.DEFAULT_REQUEST_HEADERS = json_data.get('DEFAULT_REQUEST_HEADERS') settings.ALLOWED_DOMAINS = json_data.get('allowed_domains') settings.START_URL = json_data.get('start_url') # settings.START_PAGE = json_data.get('start_page') # settings.END_PAGE = json_data.get('end_page') def run(self): json_data = json.load(open(self.file_path, 'r', encoding="utf-8")) self.change_pipline(pipeline_data=json_data.get('save_pipeline')) self.change_setting(json_data=json_data) # 运行爬虫 cmdline.execute('scrapy crawl test'.split()) pass if __name__ == '__main__': file_path = r'C:\Users\17580\Desktop\scrapy-redis分享\demo.json' spider = Spider(file_path=file_path) spider.run()
zhyscrapy
/zhyscrapy-1.0.tar.gz/zhyscrapy-1.0/scrapy_demo/run_spider.py
run_spider.py
# zi_api_auth_client To use this library you need to install the library *zi_api_auth_client* using pip. This library supports 2 types of authentication methods. Both the methods return a JWT token which you can use to make api calls for enterprise-api on production. <ol> <li> <h4>Username and password authentication:</h4> Usage: <ol> <li>import zi_api_auth_client</li> <li>jwt_token = zi_api_auth_client.user_name_pwd_authentication("your_user_name", "your_password") </li> </ol> <li> <h4>PKI authentication:</h4> This type of authentication needs a private key and a client ID to generate the JWT token. <br> Usage: <ol> <li> import zi_api_auth_client </li> <li> Paste your private key. <pre><code> key = ''' -----BEGIN PRIVATE KEY----- Your private key goes here -----END PRIVATE KEY-----''' </code></pre> </li> <li>jwt_token = zi_api_auth_client.pki_authentication("your_user_name", "your_client_id", key) </li> </ol> </ol> **Note: If you get the error "ValueError: Could not deserialize key data." when doing PKI authentication, make sure that your private key has been properly formatted. Paste the private key as a multi-line string in python.** *Correct way*: The following is the right way to paste your private key. <pre><code> ''' -----BEGIN PRIVATE KEY----- Your private key goes here -----END PRIVATE KEY-----''' </code></pre> *Wrong way*: Pasting the private key as follows would throw the error "ValueError: Could not deserialize key data." because there are extra spaces on each line in the key. <pre><code> ''' -----BEGIN PRIVATE KEY----- Your private key goes here -----END PRIVATE KEY-----''' </code></pre>
zi-api-auth-client
/zi_api_auth_client-2.0.1.tar.gz/zi_api_auth_client-2.0.1/README.md
README.md
import jwt from datetime import datetime, timedelta import requests import json class AuthClient: def __init__(self, user_name): self.user_name = user_name self.audience = 'enterprise_api' self.issuer = '[email protected]' self.authenticate_url = "https://api.zoominfo.com/authenticate" self.expiry_time_in_seconds = 300 self.hashing_algorithm = 'RS256' def user_name_pwd_authentication(self, password): headers = {'Accept': "application/json", 'user-agent': ""} request_body = {'username': self.user_name, 'password': password} response = requests.post(self.authenticate_url, headers=headers, data=request_body) if not response.ok: response.reason = response.text return response.raise_for_status() return self._extract_jwt_from_text(response.text) def pki_authentication(self, client_id, private_key): return self._post_and_get_jwt(client_id, private_key) def _post_and_get_jwt(self, client_id, private_key): client_jwt = self._get_client_jwt(client_id, private_key) headers = {'Authorization': f"Bearer {client_jwt}", 'Accept': "application/json", 'user-agent': ""} response = requests.post(self.authenticate_url, headers=headers) if not response.ok: response.reason = response.text return response.raise_for_status() return self._extract_jwt_from_text(response.text) def _get_client_jwt(self, client_id, private_key): current_time = datetime.utcnow() claims = { 'aud': self.audience, 'iss': self.issuer, 'iat': current_time, 'exp': current_time + timedelta(seconds=self.expiry_time_in_seconds), 'client_id': client_id, 'username': self.user_name } encoded_jwt = jwt.encode(claims, private_key, algorithm=self.hashing_algorithm) # `PyJWT` switched to returning a string in v2.0.0 return encoded_jwt.decode("utf-8") if isinstance(encoded_jwt, bytes) else encoded_jwt def _extract_jwt_from_text(self, text_input): json_response = json.loads(text_input) return json_response["jwt"]
zi-api-auth-client
/zi_api_auth_client-2.0.1.tar.gz/zi_api_auth_client-2.0.1/zi_api_auth_client/zi_api_auth_client.py
zi_api_auth_client.py
# zi-i18n A Experimental Internationalization example: Translation ```python #in "example.py" file from zi_i18n import I18n i18n = I18n("locale", "en_US") print(i18n.translate("example.text")) #in "locale/en_US.zi.lang" file <!example.text: "Test"> #output: Test ``` Pluralization ```python #in "example.py" file from zi_i18n import I18n i18n = I18n("locale", "en_US") print(i18n.translate("example.plural", count=0)) print(i18n.translate("example.plural", count=1)) print(i18n.translate("example.plural", count=5)) #in "locale/en_US.zi.lang" file <%example.plural: {"zero": "0", "one": "1", "many": ">= 2"} #output: # 0 # 1 # >= 2 ```
zi-i18n
/zi-i18n-0.0.8.tar.gz/zi-i18n-0.0.8/README.md
README.md
import json import os import re import time from .object import Translation LANG = os.getenv("LANG").split(".")[0] or "en_US" class I18n: def __init__(self, directory: str = "locale", language: str = LANG, cache: bool = True): self.dir = directory or "." self.def_lang = LANG or "en_US" self.languages = [] self.suffix = ".zi.lang" files = os.listdir(self.dir) for f in files: if f.endswith(self.suffix): self.languages.append(f) self.cache_on = cache self.cache = {} self.change_lang(language) def fetch_translations(self, text: str = None, count: int = None): if not text: return lang = self.lang if self.lang + self.suffix not in self.languages: import warnings warnings.warn(f"Language '{self.lang}' Not Found") lang = "en_US" if self.cache_on and lang in self.cache and text in self.cache[lang]: cache = self.cache[lang][text] return Translation(text, cache["result"], cache["type"]) def fetch(query): regex = r"^<(.)(\S*): \"(.*)\">" match = re.search(regex, query) if not match: regex = r"^<(.)(\S*): ({(.*)})>" match = re.search(regex, query) match_res = None if match: match_res = match.groups() if match_res and match_res[1] == text: if match_res[0] == "!": if self.cache_on: if lang not in self.cache: self.cache[lang] = {} self.cache[lang][match_res[1]] = {"type": match_res[0], "result": match_res[2]} return Translation(match_res[1], match_res[2], match_res[0]) elif match_res[0] == "%": pluralized = self.pluralize(match_res[2], count) if pluralized: if self.cache_on: if lang not in self.cache: self.cache[lang] = {} self.cache[lang][match_res[1]] = {"type": match_res[0], "result": pluralized} return Translation(match_res[1], pluralized, match_res[0]) for i in self.read: res = fetch(i) if res: return res return Translation(text, type="?") def pluralize(self, text: str, count: int): if count is None: return None _json = json.loads(text) if count > 1: return _json.get("many", None) elif count == 1: return _json.get("one", None) elif count < 1: return _json.get("zero", None) else: return None def change_lang(self, language: str, clear_cache: bool=False): if clear_cache and self.cache_on: self.clear_cache(self.lang) self.lang = language self.fallback = open( f"{self.dir}/{self.def_lang}{self.suffix}", "r" ).readlines() if self.lang == self.def_lang: self.read = self.fallback else: try: self.read = open(f"{self.dir}/{language}{self.suffix}", "r").readlines() except FileNotFoundError: self.read = self.fallback if self.read != self.fallback: self.read += self.fallback def translate(self, text: str, count: int = None): return self.fetch_translations(text, count) @property def latency(self): start = time.perf_counter() with self.translate("latency.test"): end = time.perf_counter() latency = end - start return latency # translate alias t = translate def clear_cache(self, language=None): if not language: self.cache = {} return if language not in self.cache: return self.cache[language] = {}
zi-i18n
/zi-i18n-0.0.8.tar.gz/zi-i18n-0.0.8/zi_i18n/i18n.py
i18n.py
import logging from enum import Enum class DCEventType(Enum): UPTURN = 1 DOWNTURN = 2 OVERSHOOT = 3 class TradeStrategy(Enum): TF = 1 CT = 2 class Config: def __init__(self, strategy, delta_p, initial_mode=None, initial_p_ext=None): self.strategy = strategy self.delta_p = delta_p if initial_mode is None and initial_p_ext is None: if strategy == TradeStrategy.TF: self.initial_mode = DCEventType.UPTURN self.initial_p_ext = 0.0 else: self.initial_mode = DCEventType.DOWNTURN self.initial_p_ext = 1000000000.0 else: self.initial_mode = initial_mode self.initial_p_ext = initial_p_ext class ZI_DCT0: def __init__(self, logger, config: Config): self.logger = logger self.config = config self.mode = config.initial_mode self.current_event = DCEventType.OVERSHOOT self.p_ext = config.initial_p_ext self.p_start_dc = 0 self.t_start_dc = 0 self.t_end_dc = 0 self.t_start_os = 0 self.t_end_os = 0 pass def observe(self, p_t, t=0): if self.config is None: self.logger.error('No configuration') return self.logger.debug('p_ext={} p_t={}'.format(self.p_ext, p_t)) if self.mode == DCEventType.UPTURN: if p_t <= self.p_ext * (1.0 - self.config.delta_p): self.turn(p_t, t, DCEventType.DOWNTURN) else: if self.p_ext < p_t: self.shoot(p_t, t) self.current_event = DCEventType.OVERSHOOT else: # mode is DOWNTURN if p_t >= self.p_ext * (1.0 + self.config.delta_p): self.turn(p_t, t, DCEventType.UPTURN) else: if self.p_ext > p_t: self.shoot(p_t, t) self.current_event = DCEventType.OVERSHOOT return self.current_event def shoot(self, p_t, t): self.p_ext = p_t self.t_start_dc = t self.t_end_os = t - 1 def turn(self, p_t, t, dc_event_type): self.mode = dc_event_type self.current_event = dc_event_type self.p_start_dc = self.p_ext self.p_ext = p_t self.t_end_dc = t self.t_start_os = t + 1 def is_buy_signaled(self): buy_signaled = (TradeStrategy.TF == self.config.strategy and DCEventType.UPTURN == self.current_event) or ( TradeStrategy.CT == self.config.strategy and DCEventType.DOWNTURN == self.current_event) return buy_signaled def is_sell_signaled(self): sell_signaled = (TradeStrategy.TF == self.config.strategy and DCEventType.DOWNTURN == self.current_event) or ( TradeStrategy.CT == self.config.strategy and DCEventType.UPTURN == self.current_event) return sell_signaled
zi_dct0
/zi_dct0-0.0.8-py3-none-any.whl/core/algo.py
algo.py
# Zscaler Internet Access CLI This is a CLI for Zscaler Internet Access. This cli (or library package) is designed to support the Zscaler Internet Access (ZIA) [API](https://help.zscaler.com/zia/about-api) and [SD-WAN API](https://help.zscaler.com/zia/sd-wan-api-integration) (aka "Partner API"). All API referecnes can be found here [[LINK](https://help.zscaler.com/zia/api)]. **PLEASE READ THE DOCUMENTATION BEFORE CONTACTING ZSCALER** This CLI has been developed mainly using Python 3.8.5 on Ubuntu 20.04 LTS (Focal Fossa). **NOTE:** This repository will experience frequent updates. To minimize breakage, public method names will not change. If you run into any defects, please open issues [[HERE.](https://github.com/omitroom13/zia/issues)] ## Quick Start 1) If you have not verified your credentials, we suggest starting [[HERE](https://help.zscaler.com/zia/configuring-postman-rest-api-client)], unless you are already familar with this API. 2) Set profile ``` $ mkdir ~/.zscaler $ cat > ~/.zscaler/profile.yaml <<EOF default: url: https://admin.<ZIA-CLOUD>.net username: <ZIA-ADMIN-USER-ID> password: <ZIA-ADMIN-USER-PASSWORD> apikey: <ZIA-API-KEY> partner: url: https://admin.<ZIA-CLOUD>.net username: <ZIA-PARTNER-ADMIN-USER-ID> password: <ZIA-PARTNER-ADMIN-USER-PASSWORD> apikey: <PARTNER-API-KEY> EOF ``` 3) Install package ``` $ pip install zia ``` 4) Check out examples ``` $ zia --help $ zia policies --help $ zia policies list [ { "id": 463593, "accessControl": "READ_WRITE", "name": "URL Filtering Rule-1", "order": 8, "protocols": [ "ANY_RULE" ], "urlCategories": [ "OTHER_ADULT_MATERIAL", "ADULT_THEMES", "LINGERIE_BIKINI", "NUDITY", "PORNOGRAPHY", "SEXUALITY", "ADULT_SEX_EDUCATION", "K_12_SEX_EDUCATION", "OTHER_DRUGS", "OTHER_ILLEGAL_OR_QUESTIONABLE", "COPYRIGHT_INFRINGEMENT", "COMPUTER_HACKING", "QUESTIONABLE", "PROFANITY", "MATURE_HUMOR", "ANONYMIZER" ], ... ``` ## API Support ### SD-WAN (Partner) API * **VPN Credentials** * **Locations** * **Activate** ## Licensing This work is released under the MIT license, forked from [eparra's zscaler-python-sdk v0.5](https://github.com/eparra/zscaler-python-sdk/). A copy of the license is provided in the [LICENSE](https://github.com/omitroom13/zia/blob/master/LICENSE) file. ## Reporting Issues If you have bugs or other issues specifically pertaining to this library, file them [here](https://github.com/omitroom13/zia/issues). ## References * https://help.zscaler.com/zia/api * https://help.zscaler.com/zia/zscaler-api-developer-guide * https://help.zscaler.com/zia/sd-wan-api-integration
zia
/zia-0.1.4.tar.gz/zia-0.1.4/README.md
README.md
# ziafont Ziafont reads TrueType/OpenType font files and draws characters and strings as SVG <path> elements. Unlike the SVG <text> element, the output of Ziafont's SVG will render identically on any system, independent of whether the original font is available. Ziafont supports fonts with TrueType glyph outlines contained in a "glyf" table in the font (these fonts typically have a .ttf extensions), or fonts with a "CFF " table (typically with a .otf extension). Kerning adjustment and glyph substitution are supported if the font has a "GPOS" table. Documentation is available at [readthedocs](https://ziafont.readthedocs.io). There is also an [online demo](https://cdelker.github.io/pyscript/ziafont.html) of Glyph rendering using Ziafont.
ziafont
/ziafont-0.6.tar.gz/ziafont-0.6/README.md
README.md
# ziamath Render MathML or LaTeX Math expressions as SVG using pure Python. Does not require a Latex installation, nor a network connection. Ziamath comes with the STIXTwoMath-Regular font installed for use by default. Other Math-enabled Open Type fonts (TTF or OTF files) may also be used. ![Example](https://github.com/cdelker/ziamath/blob/05e25b1789acc8ee816971d384aa851ffb197f7a/example.png) Documentation is available at [readthedocs](https://ziamath.readthedocs.io). Also try the [online demo](https://cdelker.github.io/pyscript/ziamath.html) based on Pyscript.
ziamath
/ziamath-0.8.1.tar.gz/ziamath-0.8.1/README.md
README.md
===== Zibal ===== A Django app for bank payments by Zibal (https://zibal.ir/) Detailed documentation is in the "docs" directory. Quick start ----------- ### 0. install ```sh pip install requests pip install zibal-django ``` ### 1. start Add "zibal" to your INSTALLED_APPS setting like this:: INSTALLED_APPS = [ ... 'zibal', ] ### 2. migrate Run ``python manage.py migrate`` to create the zibal models. ### 3. admin Start the development server and visit http://127.0.0.1:8000/admin/ for Purchase historys Model in admin. ### 4.Instructions For each transaction you first need to request and then confirm it. For this operation, you can use 2 methods : request and callback. You can use the Request method anywhere in the project. For the callback method, it is recommended to write once in a view with a fixed address and always use it. See the GitHub page of the project for more information https://github.com/mohammad3020/django-zibal
zibal-django
/zibal-django-1.1.tar.gz/zibal-django-1.1/README.rst
README.rst
import requests import json from .models import PurchaseHistory from django.contrib.auth import get_user_model from django.shortcuts import redirect User=get_user_model() class Zibal(): def __init__(self , merchant ): self.merchant = merchant def request_result(self, result): switcher = { 100: "با موفقیت تایید شد.", 102: "merchant یافت نشد.", 103: "Mamerchant غیرفعالrch", 104: "merchant نامعتبر", 201: "قبلا تایید شده.", 105: "amount بایستی بزرگتر از 1,000 ریال باشد.", 106: "callbackUrl نامعتبر می‌باشد. (شروع با http و یا https)", 113: "amount مبلغ تراکنش از سقف میزان تراکنش بیشتر است.", } return switcher.get(result, "خطا در پرداخت") def verify_result(self, result): switcher = { 100: "با موفقیت تایید شد.", 102: "merchant یافت نشد.", 103: "Mamerchant غیرفعالrch", 104: "merchant نامعتبر", 201: "قبلا تایید شده.", 202: "سفارش پرداخت نشده یا ناموفق بوده است.", 203: "trackId نامعتبر می‌باشد.", } return switcher.get(result, "خطا در پرداخت") def request(self ,callback_url , order_number , amount_RIAL , mobile , description , user_id=None): try: user = User.objects.get(pk=user_id) ins = PurchaseHistory.objects.create(user = user, amount = amount_RIAL, order = order_number) except: ins = PurchaseHistory.objects.create(amount=amount_RIAL, order=order_number) data = {} print(self.merchant) data['merchant'] = self.merchant data['callbackUrl'] = callback_url data['amount'] = amount_RIAL data['orderId'] = ins.pk if mobile is not None: data['mobile'] = mobile if description is not None: data['description'] = description # data['multiplexingInfos'] = multiplexingInfos url = "https://gateway.zibal.ir/v1/request" response = requests.post(url=url, json=data) response = json.loads(response.text) if str(response['result']) == "100" or str(response['result']) == "201": ins.trackId = str(response['trackId']) ins.result = str(response['result']) ins.message = str(response['message']) ins.save() start_pay_url = "https://gateway.zibal.ir/start/" + ins.trackId return {"status": "successful", "start_pay_url": start_pay_url, "code" : 11} else: res = self.request_result(response['result'] ) return {"status" : "error" , "message" : res , "code" : 12} def callback(self , request): if request.GET.get('success') == '1': trackId = request.GET.get('trackId') orderId = request.GET.get('orderId') try: ins = PurchaseHistory.objects.get(trackId=trackId, pk=orderId, is_paid=False) except: try: ins = PurchaseHistory.objects.get(trackId=trackId, pk=orderId, is_paid=True) return {"status": "error", "message": "شما این پرداخت را انجام داده اید", "code" : 21 } except: return {"status": "error", "message": "تراکنش شما یافت نشد", "code" : 22 } data = {} data['merchant'] = self.merchant data['trackId'] = ins.trackId url = "https://gateway.zibal.ir/v1/verify" response = requests.post(url=url, json=data) response = json.loads(response.text) ins.paidAt = response['paidAt'] ins.cardNumber = str(response['cardNumber']) ins.status = str(response['status']) ins.amount = str(response['amount']) ins.refNumber = str(response['refNumber']) ins.result = str(response['result']) ins.message = str(response['message']) ins.is_call_verify = True ins.is_paid = True ins.save() res = self.verify_result(response['result']) return {"status": "successful", "message": res , "code": 20 , "PurchaseHistory" : ins } else: return {"status": "error", "message": "تراکنش شما موفق نبود", "code": 23}
zibal-django
/zibal-django-1.1.tar.gz/zibal-django-1.1/zibal/zb.py
zb.py
from django.http import HttpResponse, Http404 from django.shortcuts import render import requests import json from .models import PurchaseHistory from django.shortcuts import redirect from .utils import zibal from django.conf import settings from .zb import Zibal as zb from django.contrib.auth import get_user_model User=get_user_model() merchant = settings.ZIBAL_MERCHANT callback_url = settings.DOMAIN_ADDRESS_ZIBAL_CALLBACK def request(request): order = request.GET.get('order') amount = request.GET.get('amount') mobile = request.GET.get('mobile') description = request.GET.get('description') if amount is None : raise Http404 # if request.method == "POST": # pass # else: # raise Http404 if order is None : order=-1 if request.user.is_authenticated: ins = PurchaseHistory.objects.create(user=request.user, amount=amount , order=order) else: ins = PurchaseHistory.objects.create( amount=amount , order=order) data = {} data['merchant'] = merchant data['callbackUrl'] = callback_url data['amount'] = amount data['orderId'] = ins.pk if mobile is not None: data['mobile'] = mobile if description is not None: data['description'] = description # data['multiplexingInfos'] = multiplexingInfos url = "https://gateway.zibal.ir/v1/request" response = requests.post(url=url, json=data) response = json.loads(response.text) if str(response['result']) == "100" or str(response['result']) =="201" : ins.trackId = str(response['trackId']) ins.result = str(response['result']) ins.message = str(response['message']) ins.save() start_pay_url = "https://gateway.zibal.ir/start/" + ins.trackId return redirect(start_pay_url) else: return HttpResponse("خطایی رخ داده ، لطفا با پشتیبانی تماس بگیرید") def back(request): if request.GET.get('success') == '1': trackId = request.GET.get('trackId') orderId = request.GET.get('orderId') try: ins = PurchaseHistory.objects.get(trackId=trackId , pk = orderId , is_paid=False ) except: try: ins = PurchaseHistory.objects.get(trackId=trackId, pk=orderId, is_paid=True) return render(request, 'verify.html', context={'error': False, 'message': "شما این پرداخت را انجام داده اید"}) except: pass return render(request , 'verify.html' , context={'error' : True , 'message' : "تراکنش شما یافت نشد"}) data = {} data['merchant'] = merchant data['trackId'] = ins.trackId url = "https://gateway.zibal.ir/v1/verify" response = requests.post(url=url, json=data) response = json.loads(response.text) ins.paidAt = response['paidAt'] ins.cardNumber = str(response['cardNumber']) ins.status = str(response['status']) ins.amount = str(response['amount']) ins.refNumber = str(response['refNumber']) ins.result = str(response['result']) ins.message = str(response['message']) ins.is_call_verify = True ins.is_paid = True ins.save() zibal(ins.order) return render(request, 'verify.html', context={'error':False , 'message': "پرداخت شما با موفقیت صورت گرفت . با تشکر"}) else: return render(request, 'verify.html', context={'error': True, 'message': "تراکنش شما موفق نبود"}) def testzb(request): order = request.GET.get('order') amount = request.GET.get('amount') mobile = request.GET.get('mobile') description = request.GET.get('description') callback_url = "http://127.0.0.1:8000/zibal/callback/" zb_obj = zb(merchant) data = zb_obj.request(callback_url ,order , amount , mobile , description , request.user ) print(data) if data['status'] == "successful": return redirect(data['start_pay_url']) else: return HttpResponse(data["message"]) def testback(request): zb_obj = zb(merchant) data = zb_obj.callback(request) purchase_history_object = data["PurchaseHistory"] if data['status'] == "successful": return HttpResponse(data['message']) else: return HttpResponse(data["message"])
zibal-django
/zibal-django-1.1.tar.gz/zibal-django-1.1/zibal/views.py
views.py
# Zibal Payment Gateway [![N|Zibal](https://github.com/zibalco/zibal-opencart-v2.3/raw/master/admin/view/image/payment/zibal.png)](https://github.com/zibalco/zibal-opencart-v2.3/raw/master/admin/view/image/payment/zibal.png) ### Installation Zibal Payment pacakge requires [Requests](https://pypi.org/project/requests/) to run. Install the package using pip ```sh $ pip install zibal ``` For upgrading to newer versions ```sh $ pip install zibal --upgrade ``` ### Usage You can send a request and verify your payment using this package. Also you can use this package to translate the result codes to printable messages Pass your merchant_id and callback url while creating a zibal instance ```python import zibal.zibal as zibal merchant_id = 'Your merchant id, use zibal for testing' callback_url = 'https://yourdomain.com/callbackUrl' zb = zibal.zibal(merchant_id, callback_url) amount = 30000 # IRR request_to_zibal = zb.request(amount) ``` Now you can access the parameters using ```python track_id = request_to_zibal['trackId'] request_result_code = request_to_zibal['result'] ``` Pass the result code to the translator function "requeset_result(result_code)" to create printable output Python3 example: ```python print(zb.request_result(request_result_code)) ``` Verify the payment using the verify function ```python verify_zibal = zb.verify(track_id) verify_result = verify_zibal['result'] ``` Now you can access the parameters using ```python ref_number = verify_zibal['refNumber'] verify_result_code = verify_zibal['result'] ``` Pass the result code to the translator function "verify_result(result_code)" to create printable output Python3 example: ```python print(zb.verify_result(verify_result_code)) ```
zibal
/zibal-1.0.0.tar.gz/zibal-1.0.0/README.md
README.md
# Zibal Payment Gateway [![N|Zibal](https://github.com/zibalco/zibal-opencart-v2.3/raw/master/admin/view/image/payment/zibal.png)](https://github.com/zibalco/zibal-opencart-v2.3/raw/master/admin/view/image/payment/zibal.png) ### Installation Zibal Platform pacakge requires [Requests](https://pypi.org/project/requests/) to run. Install the package using pip ```sh $ pip install zibalPlatform ``` For upgrading to newer versions ```sh $ pip install zibalPlatform --upgrade ``` ### Usage You can access Zibal.ir platform API using this package. Also you can use this package to translate the result codes to printable messages. Pass your "access-token" while creating a zibalPlatform instance. Below is an example of how you can use this package to access 'wallet/list' endpoint ```python import zibalPlatform.zibalPlatform as zibalPlatform access_token = 'Your access-token' platform_endpoint = 'v1/wallet/balance' zb = zibalPlatform.zibalPlatform(access_token) data = { "id": "1010101", } request_to_zibal = zb.sendRequestToZibal(path=platform_endpoint, parameters=data) ``` Now you can access the parameters like this example ```python result_code = request_to_zibal['result'] ``` Pass the result code to the translator function "platform_result(result_code)" to receive printable output Python3 example: ```python print(zb.platform_result(result_code)) ```
zibalPlatform
/zibalPlatform-1.0.0.tar.gz/zibalPlatform-1.0.0/README.md
README.md
# Paquete de autenticación y autorización de Zibanu para Django - zibanu.django.auth package Este paquete contiene los servicios y librerias necesarias para la autenticación y autorización de usuarios a través de la API de Django. Estos componentes proporcionan la funcionalidad necesaria para gestionar la autenticación de usuarios y permitir el acceso a recursos protegidos. El repositorio ofrece once (11) servicios API REST para el login, cambio de contraseña, listado de grupo, inicio de sesión, permisos de listado, actualización de perfil, actualización de autenticación, solicitud de contraseña, agregar usuario, eliminar usuario, listar usuarios o actualizar usuarios. ## APIs - [Login (Iniciar sesión)](#login-iniciar-sesión) - [Refresh (Actualizar)](#refresh-actualizar) - [Change Password (Cambio de contraseña)](#zibanudjangoauthapiservicesuserchange_password-cambio-de-contraseña) - [Request Password (Solicitud de contraseña)](#zibanudjangoauthapiservicesuserrequest_password-solicitud-de-contraseña) - [User Add (Agregar usuario)](#zibanudjangoauthapiservicesuseradd-agregar-usuario) - [User Delete (Eliminar usuario)](#zibanudjangoauthapiservicesuserdelete-eliminar-usuario) - [User List (Lista de usuarios)](#zibanudjangoauthapiservicesuserlist-lista-de-usuarios) - [User Update (Actualización de usuarios)](#zibanudjangoauthapiservicesuserupdate-module-actualización-de-usuarios) - [Permission List (Permisos de lista)](#zibanudjangoauthapiservicespermissionlist-permisos-de-lista) - [Profile Update (Actualización de perfil)](#zibanudjangoauthapiservicesprofileupdate-actualización-de-perfil) - [Group List (Lista de grupo)](#zibanudjangoauthapiservicesgrouplist-lista-de-grupo) ### Login (Iniciar sesión) Toma un conjunto de credenciales de usuario y devuelve un token web JSON deslizante para probar la autenticación de esas credenciales. Retorna: ``` { "email": "string" "password": "string" } ``` ### Refresh (Actualizar) Toma un token web JSON deslizante y devuelve una versión nueva y actualizada del período de actualización del token que no ha expirado. Retorna: ``` { "token": "string" } ``` # zibanu.django.auth.api.services package Contiene módulos o clases relacionados con la funcionalidad de los servicios de autenticación de Zibanu para Django. ## zibanu.django.auth.api.services.user module Este modulo contiene la definición de la clase UserService. Esta clase es una subclase de la clase ModelViewSet y proporciona un conjunto de servicios REST para el modelo de admiinistración de usuarios de django. Define los siguientes métodos: ### zibanu.django.auth.api.services.user.change_password (Cambio de contraseña) Servicio REST para cambiar la contraseña del usuario. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP 200 si no existen errores y un objeto JSON. ``` { "full_name": "Guest", "email": "[email protected]", "last_login": "2023-08-02T05:27:42.500Z", "username": "lRhuazZ9swzssfflX6.kwald@icQeVTu-+X3f0b5922c_xe4j4dG@RkKkA3r0TX@RlfdHPFxTrsoZnK9dWS2Y6Ehb@EE_b0TzF", "is_staff": true, "is_superuser": true } ``` ____________ ### zibanu.django.auth.api.services.user.request_password (Solicitud de contraseña) Servicio REST para solicitar contraseña y enviar por correo electrónico. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP 200 si no existen errores y un objeto JSON. ``` { "full_name": "Guest", "email": "[email protected]", "last_login": "2023-08-02T05:36:44.403Z", "username": "mWwuZ", "is_staff": true, "is_superuser": true } ``` ____________ ### zibanu.django.auth.api.services.user.add (Agregar usuario) Servicio REST para crear usuario con su perfil. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP 200 si no existen errores y un objeto JSON. ``` { "full_name": "Guest", "email": "[email protected]", "last_login": "2023-08-02T05:37:05.899Z", "username": "ydGJD6gGCVlSaN@balstNsnJLj", "is_staff": true, "is_superuser": true } ``` ____________ ### zibanu.django.auth.api.services.user.delete (Eliminar usuario) Servicio REST para eliminar un objeto de usuario. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP 200 si no existen errores y un objeto JSON. ``` { "full_name": "Guest", "email": "[email protected]", "last_login": "2023-08-02T05:37:32.699Z", "username": "w2OUlyqJrgc_1vWUXxflSt86eOuV2sitCh5zLiy8Cm_ldalAlZUDSkyRtmxiu+unwhsJp_-Nnu-kPULH8AHI3hVDc_reAd7i.iT1o", "is_staff": true, "is_superuser": true } ``` ____________ ### zibanu.django.auth.api.services.user.list (Lista de usuarios) Servicio REST para actualizar el usuario, incluyendo perfil, grupos y permisos. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP 200 si no existen errores y un objeto JSON. ``` [ { "full_name": "Guest", "email": "[email protected]", "last_login": "2023-08-02T05:38:00.491Z", "username": "U07l706kG6cV5Ljy-re2Y", "is_staff": true, "is_superuser": true } ] ``` ____________ ### zibanu.django.auth.api.services.user.update (Actualización de usuarios) Servicio REST para actualizar el usuario, incluyendo perfil, grupos y permisos. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Response: Objeto de respuesta con estado HTTP (200 si se realiza correctamente). ``` { "full_name": "Guest", "email": "[email protected]", "last_login": "2023-08-02T05:38:56.663Z", "username": "lQhl73VM6B03n3Xaz9F58o3LaJknj4VXPj8rqyXCCxu.-mPX2cJLdagL+84dRUVtBs4BO", "is_staff": true, "is_superuser": true } ``` ## zibanu.django.auth.api.services.permission module Contiene un conjunto de métodos para gestionar los permisos de los servicios relacionados con la autenticación y la autorización de Zibanu para Django. ### zibanu.django.auth.api.services.permission.list (Permisos de lista) Servicio REST para permisos de lista Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP y conjunto de datos. ``` [ { "id": 0, "name": "string" } ] ``` ## zibanu.django.auth.api.services.profile module Contiene un conjunto de métodos para la gestión de perfiles de usuario de Zibanu para Django. ### zibanu.django.auth.api.services.profile.update (Actualización de perfil) Servicio REST para actualizar el modelo UserProfile. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP 200 si no existen errores y un objeto JSON. ``` { "timezone": "Africa/Abidjan", "theme": "string", "lang": "str", "avatar": "string", "messages_timeout": 0, "keep_logged_in": true, "app_profile": { "additionalProp1": "string", "additionalProp2": "string", "additionalProp3": "string" }, "multiple_login": true, "secure_password": true } ``` ## zibanu.django.auth.api.services.group module Contiene un conjunto de métodos para la gestión de grupos de usuarios de Zibanu para Django. ### zibanu.django.auth.api.services.group.list (Lista de grupo) Servicio REST para listar grupos. Parámetros: - *Request*: Solicitar objeto de HTTP. - **args*: Tupla de parámetros. - ***kwargs*: Diccionario de parámetros. Retorna: - Objeto Response con estado HTTP y lista de dataset. ``` [ { "id": 0, "name": "string" } ] ``` ## zibanu.django.auth.lib package Paquete que contiene módulos, clases y utilidades relacionadas con la autenticación y autorización de Zibanu para Django. ## zibanu.django.auth.lib.signals module Este módulo tiene como objetivo manejar señales personalizadas de Django para capturar eventos relacionados con la autenticación y la gestión de contraseñas. Se definen dos señales: - Se utiliza para gestionar eventos relacionados con el cambio de contraseña. ``` on_change_password = dispatch.Signal() ``` - Se utiliza para gestionar eventos relacionados con el restablecimiento de contraseña. ``` on_request_password = dispatch.Signal() ``` ________ Los decoradores `@receiver` se utilizan para asociar funciones receptoras (event handlers) a las señales definidas. Cada una de ellas se activará cuando se emita la señal correspondiente. ``` @receiver(on_change_password, dispatch_uid="on_change_password") ``` - Asigna la función receptora a la señal `on_change_password`. Se agrega un identificador único (`dispatch_uid`) para garantizar que la conexión de la señal sea única y no se duplique. ________ ``` @receiver(on_request_password, dispatch_uid="on_request_password") ``` - Asigna la función receptora a la señal `on_request_password`. Se agrega un identificador único (`dispatch_uid`) para garantizar que la conexión de la señal sea única y no se duplique. ________ ``` @receiver(user_logged_in, dispatch_uid="on_user_logged_in") ``` - Asigna la función receptora a la señal `user_logged_in`. Se agrega un identificador único (`dispatch_uid`) para garantizar que la conexión de la señal sea única y no se duplique. ________ ``` @receiver(user_login_failed, dispatch_uid="on_user_login_failed") ``` - Asigna la función receptora a la señal `user_login_failed`. Se agrega un identificador único (`dispatch_uid`) para garantizar que la conexión de la señal sea única y no se duplique. ________ ``` auth_event(sender: Any, user: Any = None, **kwargs)→ None: ``` Esta función actúa como un manejador para eventos capturados por las señales de cambio de contraseña o solicitud de contraseña. Parámetros: - *sender*: Clase de emisor de la señal. - *user*: Objeto de usuario para obtener datos. - ***kwargs*: Diccionario con campos y parámetros. Retorno: - Ninguno. ## zibanu.django.auth.lib.utils module Este modulo contiene la siguiente función: - `get_user`: Obtiene el objeto de usuario de SimpleJWT TokenUser. Parámetros: - *user*: Objeto de usuario de tipo de usuario de token SimpleJWT o tipo de objeto de usuario Retorna: - user: Tipo de objeto de usuario de Django. # zibanu.django.auth.api.serializers package Este directorio contiene serializadores para la API de autenticación de Zibanu para Django. ## zibanu.django.auth.api.serializers.group module GroupListSerializer es un serializador para una lista de grupos. Incluye los siguientes campos: * id: El ID del grupo. * name: El nombre del grupo. ## zibanu.django.auth.api.serializers.permission module PermissionSerializer es un serializador para un permiso. Incluye los siguientes campos: * id: El ID del permiso. * name: El nombre del permiso. ## zibanu.django.auth.api.serializers.profile module ProfileSerializer es un serializador para un perfil de usuario. Incluye los siguientes campos: * timezone: La zona horaria del usuario. * theme: El tema del usuario. * lang: El idioma del usuario. * avatar: El avatar del usuario. * message_timeout: Tiempo de espera de los mensajes del usuario. * keep_logged_in: Si el usuario desea permanecer conectado. * app_profile: El perfil de la aplicación del usuario. * multiple_login: Si el usuario permite múltiples inicios de sesión. * secure_password: Si la contraseña del usuario es segura. ## zibanu.django.auth.api.serializers.token module TokenObtainSerializer es un serializador para obtener un token mediante la autenticación de correo electrónico. Incluye los siguientes campos: * username_field: El campo que se usará para la autenticación del nombre de usuario. * email: La dirección de correo electrónico del usuario. * password: La contraseña del usuario. TokenObtainSlidingSerializer es una subclase de TokenObtainSerializer que usa un token deslizante. Incluye los siguientes campos: * token. ## zibanu.django.auth.api.serializers.user module La clase UserSerializer se utiliza para serializar y deserializar un solo objeto de usuario. Incluye los siguientes campos:UserSerializer es un serializador para un usuario. Incluye los siguientes campos: * email. * full_name. * last_login. * is_staff. * is_superuser. * is_active. * profile. * roles. * first_name. * last_name. * permissions. * username. * password. El método `create` se utiliza para crear un nuevo objeto de usuario. Toma un diccionario de datos validados como entrada y crea un nuevo objeto de usuario con los datos proporcionados. Si el objeto de usuario se crea correctamente, devuelve el objeto de usuario. Si el objeto de usuario ya existe, genera una excepción `ValidationError`. ### UserListSerializer UserListSerializer es un serializador para una lista de usuarios. Incluye los siguientes campos: * full_name. * email. * last_login. * username. * is_staff. * is_superuser. El método `get_full_name` se utiliza para obtener el nombre completo de un objeto de usuario. Toma un objeto de usuario como entrada y devuelve el nombre completo del usuario.
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/README.md
README.md
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 8/04/23 7:18 # Project: Django Plugins # Module Name: apps # Description: # **************************************************************** from django.apps import apps from django.apps import AppConfig from django.conf import settings from django.utils.translation import gettext_lazy as _ class ZbDjangoAuth(AppConfig): """ Inherited class from django.apps.AppConfig to define configuration of zibanu.django.auth app. """ default_auto_field = "django.db.models.AutoField" name = "zibanu.django.auth" verbose_name = _("Zibanu Auth for Django") label = "zb_auth" def ready(self): """ Override method used for django application loader after the application has been loaded successfully. Returns ------- None Settings ------- ZB_AUTH_INCLUDE_GROUPS: If True, includes the set of groups to which the user belongs, False ignores them. Default: True ZB_AUTH_INCLUDE_PERMISSIONS: If True, includes the set of permissions the user has, False ignores them. Default: False ZB_AUTH_CHANGE_PASSWORD_TEMPLATE: Template used to generate password change confirmation email. Default: "on_change_password" ZB_AUTH_REQUEST_PASSWORD_TEMPLATE: Template used to generate request password email. Default: "on_request_password" ZB_AUTH_ALLOW_MULTIPLE_LOGIN: If True, allows a user to have multiple access from the same type of application, False only allows one access. Default is FALSE """ # Import signals import zibanu.django.auth.lib.signals # Set default settings for Simple JWT Module settings.ZB_AUTH_INCLUDE_GROUPS = getattr(settings, "ZB_AUTH_INCLUDE_GROUPS", True) settings.ZB_AUTH_INCLUDE_PERMISSIONS = getattr(settings, "ZB_AUTH_INCLUDE_PERMISSIONS", False) settings.ZB_AUTH_CHANGE_PASSWORD_TEMPLATE = getattr(settings, "ZB_AUTH_CHANGE_PASSWORD_TEMPLATE", "change_password") settings.ZB_AUTH_REQUEST_PASSWORD_TEMPLATE = getattr(settings, "ZB_AUTH_REQUEST_PASSWORD_TEMPLATE", "request_password") settings.ZB_AUTH_ALLOW_MULTIPLE_LOGIN = getattr(settings, "ZB_AUTH_ALLOW_MULTIPLE_LOGIN", False) settings.ZB_AUTH_AVATAR_BASE64 = getattr(settings, "ZB_AUTH_AVATAR_FORMAT", True) settings.ZB_AUTH_AVATAR_SIZE = getattr(settings, "ZB_AUTH_AVATAR_SIZE", 0)
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/apps.py
apps.py
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 10/04/23 13:52 # Project: Django Plugins # Module Name: models # Description: # **************************************************************** from django.conf import settings from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from timezone_utils.choices import ALL_TIMEZONES_CHOICES from zibanu.django.db import models class UserProfile(models.Model): """ UserProfile model to store """ user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="profile", related_query_name="user") timezone = models.CharField(max_length=50, null=False, blank=False, default="UTC", choices=ALL_TIMEZONES_CHOICES, verbose_name=_("Time Zone")) theme = models.CharField(max_length=50, null=True, blank=False, verbose_name=_("User Theme")) lang = models.CharField(max_length=3, null=False, blank=False, default="en", verbose_name=_("Language")) avatar = models.ImageField(upload_to='profile_pics/', null=True, verbose_name=_("Avatar")) messages_timeout = models.IntegerField(default=10, null=False, blank=False, verbose_name=_("Message's Timeout")) keep_logged_in = models.BooleanField(default=False, null=False, blank=False, verbose_name=_("Keep Logged In")) multiple_login = models.BooleanField(default=False, null=False, blank=False, verbose_name=_("Allow multiple login")) secure_password = models.BooleanField(default=False, null=False, blank=False, verbose_name=_("Force secure password")) app_profile = models.JSONField(null=True, blank=False, verbose_name=_("Custom Application Profile")) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Override method to force the flag multiple_login at user profile to False if is_staff attribute is False, and validate if ZB_AUTH_ALLOW_MULTIPLE_LOGIN setting is TRUE Parameters ---------- force_insert: Force insert flag force_update: Force update flag using: Using database setting update_fields: Set of fields to update only. Returns ------- None """ if not settings.ZB_AUTH_ALLOW_MULTIPLE_LOGIN: if not self.user.is_staff: self.multiple_login = False return super().save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) class Meta: db_table = "zb_auth_user_profile"
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/models.py
models.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timezone', models.CharField(choices=[('Europe/Dublin', 'Europe/Dublin'), ('America/Goose_Bay', 'America/Goose_Bay'), ('Europe/Helsinki', 'Europe/Helsinki'), ('PST8PDT', 'PST8PDT'), ('America/Whitehorse', 'America/Whitehorse'), ('Asia/Macao', 'Asia/Macao'), ('America/Indiana/Marengo', 'America/Indiana/Marengo'), ('Asia/Kuching', 'Asia/Kuching'), ('Kwajalein', 'Kwajalein'), ('Asia/Khandyga', 'Asia/Khandyga'), ('Asia/Novokuznetsk', 'Asia/Novokuznetsk'), ('Canada/Yukon', 'Canada/Yukon'), ('Atlantic/Faeroe', 'Atlantic/Faeroe'), ('Australia/Sydney', 'Australia/Sydney'), ('America/Blanc-Sablon', 'America/Blanc-Sablon'), ('America/Metlakatla', 'America/Metlakatla'), ('Atlantic/Canary', 'Atlantic/Canary'), ('America/Yellowknife', 'America/Yellowknife'), ('Asia/Muscat', 'Asia/Muscat'), ('Europe/Volgograd', 'Europe/Volgograd'), ('Asia/Macau', 'Asia/Macau'), ('Canada/Eastern', 'Canada/Eastern'), ('CST6CDT', 'CST6CDT'), ('Asia/Thimphu', 'Asia/Thimphu'), ('America/Fort_Wayne', 'America/Fort_Wayne'), ('Turkey', 'Turkey'), ('GB-Eire', 'GB-Eire'), ('Asia/Thimbu', 'Asia/Thimbu'), ('Indian/Kerguelen', 'Indian/Kerguelen'), ('America/Coral_Harbour', 'America/Coral_Harbour'), ('Universal', 'Universal'), ('Africa/Accra', 'Africa/Accra'), ('Africa/Johannesburg', 'Africa/Johannesburg'), ('Antarctica/Syowa', 'Antarctica/Syowa'), ('Asia/Aqtau', 'Asia/Aqtau'), ('Africa/Asmara', 'Africa/Asmara'), ('America/Toronto', 'America/Toronto'), ('America/Indiana/Winamac', 'America/Indiana/Winamac'), ('America/Thunder_Bay', 'America/Thunder_Bay'), ('Africa/Algiers', 'Africa/Algiers'), ('NZ', 'NZ'), ('Antarctica/Troll', 'Antarctica/Troll'), ('Etc/GMT-8', 'Etc/GMT-8'), ('Australia/West', 'Australia/West'), ('Africa/Asmera', 'Africa/Asmera'), ('Pacific/Truk', 'Pacific/Truk'), ('Etc/GMT+6', 'Etc/GMT+6'), ('US/Aleutian', 'US/Aleutian'), ('Africa/Blantyre', 'Africa/Blantyre'), ('America/Merida', 'America/Merida'), ('America/Argentina/La_Rioja', 'America/Argentina/La_Rioja'), ('Europe/Copenhagen', 'Europe/Copenhagen'), ('Australia/Queensland', 'Australia/Queensland'), ('Europe/Ulyanovsk', 'Europe/Ulyanovsk'), ('Atlantic/Madeira', 'Atlantic/Madeira'), ('Antarctica/South_Pole', 'Antarctica/South_Pole'), ('Etc/GMT+9', 'Etc/GMT+9'), ('Africa/Kigali', 'Africa/Kigali'), ('Antarctica/Davis', 'Antarctica/Davis'), ('Asia/Choibalsan', 'Asia/Choibalsan'), ('Asia/Hong_Kong', 'Asia/Hong_Kong'), ('America/Guayaquil', 'America/Guayaquil'), ('America/Curacao', 'America/Curacao'), ('America/Tijuana', 'America/Tijuana'), ('America/Halifax', 'America/Halifax'), ('Asia/Dacca', 'Asia/Dacca'), ('America/Mendoza', 'America/Mendoza'), ('Asia/Chita', 'Asia/Chita'), ('America/El_Salvador', 'America/El_Salvador'), ('America/Montserrat', 'America/Montserrat'), ('America/Indianapolis', 'America/Indianapolis'), ('America/Port_of_Spain', 'America/Port_of_Spain'), ('America/Guyana', 'America/Guyana'), ('Asia/Chungking', 'Asia/Chungking'), ('America/Puerto_Rico', 'America/Puerto_Rico'), ('America/Caracas', 'America/Caracas'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('America/Virgin', 'America/Virgin'), ('Australia/LHI', 'Australia/LHI'), ('MST', 'MST'), ('America/Argentina/Rio_Gallegos', 'America/Argentina/Rio_Gallegos'), ('America/Antigua', 'America/Antigua'), ('Asia/Novosibirsk', 'Asia/Novosibirsk'), ('Europe/Vatican', 'Europe/Vatican'), ('Pacific/Guadalcanal', 'Pacific/Guadalcanal'), ('America/St_Kitts', 'America/St_Kitts'), ('Asia/Ho_Chi_Minh', 'Asia/Ho_Chi_Minh'), ('US/Pacific', 'US/Pacific'), ('Asia/Manila', 'Asia/Manila'), ('America/Lower_Princes', 'America/Lower_Princes'), ('Asia/Jayapura', 'Asia/Jayapura'), ('America/Cambridge_Bay', 'America/Cambridge_Bay'), ('Etc/Zulu', 'Etc/Zulu'), ('Australia/Brisbane', 'Australia/Brisbane'), ('Pacific/Palau', 'Pacific/Palau'), ('Africa/Casablanca', 'Africa/Casablanca'), ('Asia/Irkutsk', 'Asia/Irkutsk'), ('Europe/Stockholm', 'Europe/Stockholm'), ('Pacific/Yap', 'Pacific/Yap'), ('Pacific/Johnston', 'Pacific/Johnston'), ('Asia/Kashgar', 'Asia/Kashgar'), ('Asia/Famagusta', 'Asia/Famagusta'), ('Australia/ACT', 'Australia/ACT'), ('Asia/Kamchatka', 'Asia/Kamchatka'), ('Asia/Tehran', 'Asia/Tehran'), ('Europe/Rome', 'Europe/Rome'), ('Asia/Colombo', 'Asia/Colombo'), ('Pacific/Fiji', 'Pacific/Fiji'), ('Indian/Cocos', 'Indian/Cocos'), ('Africa/Sao_Tome', 'Africa/Sao_Tome'), ('America/Moncton', 'America/Moncton'), ('America/Juneau', 'America/Juneau'), ('America/Santa_Isabel', 'America/Santa_Isabel'), ('America/Anguilla', 'America/Anguilla'), ('Africa/Mbabane', 'Africa/Mbabane'), ('Australia/Darwin', 'Australia/Darwin'), ('Asia/Seoul', 'Asia/Seoul'), ('America/Dominica', 'America/Dominica'), ('Etc/GMT-2', 'Etc/GMT-2'), ('Africa/Maseru', 'Africa/Maseru'), ('Canada/Pacific', 'Canada/Pacific'), ('America/Detroit', 'America/Detroit'), ('Pacific/Wallis', 'Pacific/Wallis'), ('America/Jujuy', 'America/Jujuy'), ('Canada/Mountain', 'Canada/Mountain'), ('America/Marigot', 'America/Marigot'), ('America/Ojinaga', 'America/Ojinaga'), ('Asia/Aden', 'Asia/Aden'), ('Australia/Victoria', 'Australia/Victoria'), ('America/Maceio', 'America/Maceio'), ('Asia/Kabul', 'Asia/Kabul'), ('America/Noronha', 'America/Noronha'), ('Pacific/Gambier', 'Pacific/Gambier'), ('Africa/Douala', 'Africa/Douala'), ('America/Nassau', 'America/Nassau'), ('Australia/Melbourne', 'Australia/Melbourne'), ('Africa/Lome', 'Africa/Lome'), ('US/Hawaii', 'US/Hawaii'), ('Europe/Kirov', 'Europe/Kirov'), ('UTC', 'UTC'), ('Australia/Currie', 'Australia/Currie'), ('Etc/GMT+11', 'Etc/GMT+11'), ('W-SU', 'W-SU'), ('America/Porto_Velho', 'America/Porto_Velho'), ('Asia/Rangoon', 'Asia/Rangoon'), ('Etc/UTC', 'Etc/UTC'), ('Asia/Sakhalin', 'Asia/Sakhalin'), ('Atlantic/Cape_Verde', 'Atlantic/Cape_Verde'), ('America/Hermosillo', 'America/Hermosillo'), ('America/Mazatlan', 'America/Mazatlan'), ('America/Cayenne', 'America/Cayenne'), ('Antarctica/Macquarie', 'Antarctica/Macquarie'), ('America/Argentina/San_Juan', 'America/Argentina/San_Juan'), ('Indian/Antananarivo', 'Indian/Antananarivo'), ('Brazil/East', 'Brazil/East'), ('Etc/GMT+2', 'Etc/GMT+2'), ('America/Montreal', 'America/Montreal'), ('America/Resolute', 'America/Resolute'), ('HST', 'HST'), ('Europe/Vaduz', 'Europe/Vaduz'), ('Indian/Mayotte', 'Indian/Mayotte'), ('America/North_Dakota/Center', 'America/North_Dakota/Center'), ('America/Grand_Turk', 'America/Grand_Turk'), ('America/Denver', 'America/Denver'), ('America/Jamaica', 'America/Jamaica'), ('Europe/Minsk', 'Europe/Minsk'), ('Asia/Yakutsk', 'Asia/Yakutsk'), ('America/Phoenix', 'America/Phoenix'), ('Europe/Bratislava', 'Europe/Bratislava'), ('US/Eastern', 'US/Eastern'), ('Europe/Zagreb', 'Europe/Zagreb'), ('Europe/Oslo', 'Europe/Oslo'), ('PRC', 'PRC'), ('Etc/GMT+10', 'Etc/GMT+10'), ('Asia/Kathmandu', 'Asia/Kathmandu'), ('Pacific/Apia', 'Pacific/Apia'), ('America/Recife', 'America/Recife'), ('Asia/Dili', 'Asia/Dili'), ('America/Chihuahua', 'America/Chihuahua'), ('Pacific/Pago_Pago', 'Pacific/Pago_Pago'), ('Asia/Yerevan', 'Asia/Yerevan'), ('Etc/GMT+0', 'Etc/GMT+0'), ('Cuba', 'Cuba'), ('Europe/Ljubljana', 'Europe/Ljubljana'), ('Africa/Addis_Ababa', 'Africa/Addis_Ababa'), ('America/Eirunepe', 'America/Eirunepe'), ('Europe/Guernsey', 'Europe/Guernsey'), ('Asia/Oral', 'Asia/Oral'), ('Etc/GMT0', 'Etc/GMT0'), ('Europe/Luxembourg', 'Europe/Luxembourg'), ('Etc/GMT-10', 'Etc/GMT-10'), ('Pacific/Nauru', 'Pacific/Nauru'), ('America/Knox_IN', 'America/Knox_IN'), ('America/Inuvik', 'America/Inuvik'), ('America/Manaus', 'America/Manaus'), ('Asia/Tashkent', 'Asia/Tashkent'), ('US/East-Indiana', 'US/East-Indiana'), ('Asia/Saigon', 'Asia/Saigon'), ('America/Bahia_Banderas', 'America/Bahia_Banderas'), ('America/Montevideo', 'America/Montevideo'), ('Etc/GMT+8', 'Etc/GMT+8'), ('Asia/Dushanbe', 'Asia/Dushanbe'), ('Europe/Zurich', 'Europe/Zurich'), ('Etc/Universal', 'Etc/Universal'), ('Pacific/Rarotonga', 'Pacific/Rarotonga'), ('Australia/NSW', 'Australia/NSW'), ('America/Creston', 'America/Creston'), ('Europe/Moscow', 'Europe/Moscow'), ('Africa/Bangui', 'Africa/Bangui'), ('America/Cordoba', 'America/Cordoba'), ('Etc/GMT+7', 'Etc/GMT+7'), ('Asia/Brunei', 'Asia/Brunei'), ('America/Argentina/Cordoba', 'America/Argentina/Cordoba'), ('Poland', 'Poland'), ('America/Winnipeg', 'America/Winnipeg'), ('America/Cancun', 'America/Cancun'), ('Europe/Astrakhan', 'Europe/Astrakhan'), ('Pacific/Kosrae', 'Pacific/Kosrae'), ('Asia/Vladivostok', 'Asia/Vladivostok'), ('Factory', 'Factory'), ('Asia/Dhaka', 'Asia/Dhaka'), ('America/Asuncion', 'America/Asuncion'), ('Africa/Windhoek', 'Africa/Windhoek'), ('Brazil/Acre', 'Brazil/Acre'), ('Europe/Kyiv', 'Europe/Kyiv'), ('Asia/Dubai', 'Asia/Dubai'), ('America/St_Lucia', 'America/St_Lucia'), ('America/Matamoros', 'America/Matamoros'), ('America/Grenada', 'America/Grenada'), ('Asia/Qyzylorda', 'Asia/Qyzylorda'), ('Europe/Uzhgorod', 'Europe/Uzhgorod'), ('America/Danmarkshavn', 'America/Danmarkshavn'), ('Canada/Atlantic', 'Canada/Atlantic'), ('Atlantic/St_Helena', 'Atlantic/St_Helena'), ('Brazil/West', 'Brazil/West'), ('Pacific/Fakaofo', 'Pacific/Fakaofo'), ('America/Cuiaba', 'America/Cuiaba'), ('Asia/Kuwait', 'Asia/Kuwait'), ('America/Catamarca', 'America/Catamarca'), ('America/Cayman', 'America/Cayman'), ('Asia/Katmandu', 'Asia/Katmandu'), ('Etc/GMT-7', 'Etc/GMT-7'), ('Asia/Qatar', 'Asia/Qatar'), ('Africa/Lusaka', 'Africa/Lusaka'), ('Asia/Urumqi', 'Asia/Urumqi'), ('Europe/Tallinn', 'Europe/Tallinn'), ('Australia/Lord_Howe', 'Australia/Lord_Howe'), ('Europe/Podgorica', 'Europe/Podgorica'), ('America/Punta_Arenas', 'America/Punta_Arenas'), ('Asia/Yangon', 'Asia/Yangon'), ('Indian/Mauritius', 'Indian/Mauritius'), ('Africa/Lubumbashi', 'Africa/Lubumbashi'), ('America/Rankin_Inlet', 'America/Rankin_Inlet'), ('Asia/Omsk', 'Asia/Omsk'), ('Asia/Riyadh', 'Asia/Riyadh'), ('Canada/Central', 'Canada/Central'), ('Africa/Tripoli', 'Africa/Tripoli'), ('Africa/Malabo', 'Africa/Malabo'), ('EET', 'EET'), ('Etc/GMT-9', 'Etc/GMT-9'), ('Asia/Tomsk', 'Asia/Tomsk'), ('Asia/Ulan_Bator', 'Asia/Ulan_Bator'), ('Indian/Chagos', 'Indian/Chagos'), ('America/Ciudad_Juarez', 'America/Ciudad_Juarez'), ('Africa/Maputo', 'Africa/Maputo'), ('GMT0', 'GMT0'), ('America/New_York', 'America/New_York'), ('Africa/Khartoum', 'Africa/Khartoum'), ('Etc/GMT-1', 'Etc/GMT-1'), ('Africa/Libreville', 'Africa/Libreville'), ('Pacific/Easter', 'Pacific/Easter'), ('Asia/Atyrau', 'Asia/Atyrau'), ('Europe/Istanbul', 'Europe/Istanbul'), ('Antarctica/Mawson', 'Antarctica/Mawson'), ('America/Argentina/San_Luis', 'America/Argentina/San_Luis'), ('Antarctica/Casey', 'Antarctica/Casey'), ('Iran', 'Iran'), ('America/Martinique', 'America/Martinique'), ('Australia/Perth', 'Australia/Perth'), ('Europe/Brussels', 'Europe/Brussels'), ('Africa/Cairo', 'Africa/Cairo'), ('Europe/Prague', 'Europe/Prague'), ('Africa/Mogadishu', 'Africa/Mogadishu'), ('Indian/Reunion', 'Indian/Reunion'), ('Pacific/Funafuti', 'Pacific/Funafuti'), ('America/Iqaluit', 'America/Iqaluit'), ('America/Dawson_Creek', 'America/Dawson_Creek'), ('America/Kentucky/Monticello', 'America/Kentucky/Monticello'), ('America/Godthab', 'America/Godthab'), ('America/Los_Angeles', 'America/Los_Angeles'), ('Asia/Damascus', 'Asia/Damascus'), ('Asia/Kolkata', 'Asia/Kolkata'), ('America/Campo_Grande', 'America/Campo_Grande'), ('Europe/Simferopol', 'Europe/Simferopol'), ('Pacific/Majuro', 'Pacific/Majuro'), ('Etc/GMT-5', 'Etc/GMT-5'), ('America/Aruba', 'America/Aruba'), ('Asia/Kuala_Lumpur', 'Asia/Kuala_Lumpur'), ('Europe/Isle_of_Man', 'Europe/Isle_of_Man'), ('Africa/Ndjamena', 'Africa/Ndjamena'), ('Asia/Beirut', 'Asia/Beirut'), ('Asia/Amman', 'Asia/Amman'), ('America/Regina', 'America/Regina'), ('Europe/Belfast', 'Europe/Belfast'), ('Antarctica/McMurdo', 'Antarctica/McMurdo'), ('Japan', 'Japan'), ('America/Santiago', 'America/Santiago'), ('Asia/Hebron', 'Asia/Hebron'), ('America/Barbados', 'America/Barbados'), ('America/Port-au-Prince', 'America/Port-au-Prince'), ('Etc/GMT-12', 'Etc/GMT-12'), ('Asia/Tbilisi', 'Asia/Tbilisi'), ('Iceland', 'Iceland'), ('Etc/GMT-14', 'Etc/GMT-14'), ('Pacific/Chatham', 'Pacific/Chatham'), ('Europe/Madrid', 'Europe/Madrid'), ('Chile/EasterIsland', 'Chile/EasterIsland'), ('Africa/Abidjan', 'Africa/Abidjan'), ('America/Miquelon', 'America/Miquelon'), ('Etc/GMT-13', 'Etc/GMT-13'), ('Pacific/Tarawa', 'Pacific/Tarawa'), ('America/Managua', 'America/Managua'), ('Asia/Barnaul', 'Asia/Barnaul'), ('America/Louisville', 'America/Louisville'), ('Antarctica/Palmer', 'Antarctica/Palmer'), ('Etc/GMT-3', 'Etc/GMT-3'), ('Pacific/Samoa', 'Pacific/Samoa'), ('Asia/Anadyr', 'Asia/Anadyr'), ('Asia/Pyongyang', 'Asia/Pyongyang'), ('America/Adak', 'America/Adak'), ('Australia/Broken_Hill', 'Australia/Broken_Hill'), ('Asia/Ust-Nera', 'Asia/Ust-Nera'), ('Etc/GMT+3', 'Etc/GMT+3'), ('Pacific/Honolulu', 'Pacific/Honolulu'), ('Libya', 'Libya'), ('America/Guadeloupe', 'America/Guadeloupe'), ('America/Argentina/Jujuy', 'America/Argentina/Jujuy'), ('America/St_Vincent', 'America/St_Vincent'), ('America/Panama', 'America/Panama'), ('America/Belem', 'America/Belem'), ('Asia/Ulaanbaatar', 'Asia/Ulaanbaatar'), ('Africa/Nouakchott', 'Africa/Nouakchott'), ('America/Argentina/ComodRivadavia', 'America/Argentina/ComodRivadavia'), ('America/St_Johns', 'America/St_Johns'), ('Africa/Ceuta', 'Africa/Ceuta'), ('Africa/Porto-Novo', 'Africa/Porto-Novo'), ('Europe/Malta', 'Europe/Malta'), ('America/Argentina/Tucuman', 'America/Argentina/Tucuman'), ('Europe/Budapest', 'Europe/Budapest'), ('Europe/Busingen', 'Europe/Busingen'), ('US/Michigan', 'US/Michigan'), ('America/Mexico_City', 'America/Mexico_City'), ('NZ-CHAT', 'NZ-CHAT'), ('America/Havana', 'America/Havana'), ('Asia/Aqtobe', 'Asia/Aqtobe'), ('Africa/Timbuktu', 'Africa/Timbuktu'), ('US/Mountain', 'US/Mountain'), ('America/Rio_Branco', 'America/Rio_Branco'), ('Asia/Jerusalem', 'Asia/Jerusalem'), ('Asia/Taipei', 'Asia/Taipei'), ('US/Indiana-Starke', 'US/Indiana-Starke'), ('America/Kentucky/Louisville', 'America/Kentucky/Louisville'), ('Europe/Riga', 'Europe/Riga'), ('Asia/Qostanay', 'Asia/Qostanay'), ('Etc/GMT+1', 'Etc/GMT+1'), ('America/Pangnirtung', 'America/Pangnirtung'), ('America/Nipigon', 'America/Nipigon'), ('Europe/Skopje', 'Europe/Skopje'), ('Australia/Canberra', 'Australia/Canberra'), ('Europe/Mariehamn', 'Europe/Mariehamn'), ('Pacific/Galapagos', 'Pacific/Galapagos'), ('GMT', 'GMT'), ('America/Rosario', 'America/Rosario'), ('Singapore', 'Singapore'), ('Asia/Bishkek', 'Asia/Bishkek'), ('Indian/Christmas', 'Indian/Christmas'), ('Africa/Ouagadougou', 'Africa/Ouagadougou'), ('America/Belize', 'America/Belize'), ('America/Edmonton', 'America/Edmonton'), ('America/Sao_Paulo', 'America/Sao_Paulo'), ('America/Argentina/Buenos_Aires', 'America/Argentina/Buenos_Aires'), ('Etc/GMT-4', 'Etc/GMT-4'), ('Africa/Banjul', 'Africa/Banjul'), ('Australia/Adelaide', 'Australia/Adelaide'), ('Indian/Comoro', 'Indian/Comoro'), ('Asia/Bahrain', 'Asia/Bahrain'), ('America/Indiana/Knox', 'America/Indiana/Knox'), ('Africa/Djibouti', 'Africa/Djibouti'), ('Atlantic/Faroe', 'Atlantic/Faroe'), ('Pacific/Saipan', 'Pacific/Saipan'), ('Europe/Sofia', 'Europe/Sofia'), ('ROK', 'ROK'), ('Asia/Ashkhabad', 'Asia/Ashkhabad'), ('America/Indiana/Indianapolis', 'America/Indiana/Indianapolis'), ('Africa/Kampala', 'Africa/Kampala'), ('Africa/Lagos', 'Africa/Lagos'), ('Asia/Tel_Aviv', 'Asia/Tel_Aviv'), ('Asia/Samarkand', 'Asia/Samarkand'), ('Africa/Nairobi', 'Africa/Nairobi'), ('America/Argentina/Catamarca', 'America/Argentina/Catamarca'), ('America/Kralendijk', 'America/Kralendijk'), ('US/Arizona', 'US/Arizona'), ('America/Shiprock', 'America/Shiprock'), ('Arctic/Longyearbyen', 'Arctic/Longyearbyen'), ('Europe/San_Marino', 'Europe/San_Marino'), ('Canada/Newfoundland', 'Canada/Newfoundland'), ('Africa/Monrovia', 'Africa/Monrovia'), ('Europe/Saratov', 'Europe/Saratov'), ('Indian/Maldives', 'Indian/Maldives'), ('America/Bahia', 'America/Bahia'), ('GMT-0', 'GMT-0'), ('America/Sitka', 'America/Sitka'), ('GMT+0', 'GMT+0'), ('America/Nome', 'America/Nome'), ('Etc/GMT+12', 'Etc/GMT+12'), ('America/Monterrey', 'America/Monterrey'), ('America/Rainy_River', 'America/Rainy_River'), ('Greenwich', 'Greenwich'), ('Europe/Tiraspol', 'Europe/Tiraspol'), ('America/North_Dakota/Beulah', 'America/North_Dakota/Beulah'), ('Pacific/Tahiti', 'Pacific/Tahiti'), ('Etc/Greenwich', 'Etc/Greenwich'), ('Asia/Bangkok', 'Asia/Bangkok'), ('America/Argentina/Ushuaia', 'America/Argentina/Ushuaia'), ('Atlantic/Azores', 'Atlantic/Azores'), ('America/Indiana/Vincennes', 'America/Indiana/Vincennes'), ('Pacific/Port_Moresby', 'Pacific/Port_Moresby'), ('America/Ensenada', 'America/Ensenada'), ('Africa/Gaborone', 'Africa/Gaborone'), ('Hongkong', 'Hongkong'), ('Europe/Vilnius', 'Europe/Vilnius'), ('Pacific/Pohnpei', 'Pacific/Pohnpei'), ('America/Chicago', 'America/Chicago'), ('Asia/Makassar', 'Asia/Makassar'), ('Europe/Kaliningrad', 'Europe/Kaliningrad'), ('Europe/Berlin', 'Europe/Berlin'), ('Pacific/Norfolk', 'Pacific/Norfolk'), ('America/Santarem', 'America/Santarem'), ('Europe/Athens', 'Europe/Athens'), ('ROC', 'ROC'), ('Europe/Amsterdam', 'Europe/Amsterdam'), ('Asia/Magadan', 'Asia/Magadan'), ('America/Fortaleza', 'America/Fortaleza'), ('Brazil/DeNoronha', 'Brazil/DeNoronha'), ('America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem'), ('America/Indiana/Tell_City', 'America/Indiana/Tell_City'), ('Pacific/Pitcairn', 'Pacific/Pitcairn'), ('Pacific/Kanton', 'Pacific/Kanton'), ('America/Argentina/Mendoza', 'America/Argentina/Mendoza'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Asia/Chongqing', 'Asia/Chongqing'), ('America/Thule', 'America/Thule'), ('Europe/Tirane', 'Europe/Tirane'), ('America/Anchorage', 'America/Anchorage'), ('Europe/Sarajevo', 'Europe/Sarajevo'), ('America/Nuuk', 'America/Nuuk'), ('America/Boise', 'America/Boise'), ('America/Indiana/Petersburg', 'America/Indiana/Petersburg'), ('America/Bogota', 'America/Bogota'), ('Asia/Vientiane', 'Asia/Vientiane'), ('Asia/Almaty', 'Asia/Almaty'), ('MST7MDT', 'MST7MDT'), ('America/Guatemala', 'America/Guatemala'), ('Asia/Shanghai', 'Asia/Shanghai'), ('Asia/Phnom_Penh', 'Asia/Phnom_Penh'), ('Pacific/Guam', 'Pacific/Guam'), ('Atlantic/Stanley', 'Atlantic/Stanley'), ('Asia/Istanbul', 'Asia/Istanbul'), ('Europe/Lisbon', 'Europe/Lisbon'), ('Australia/Tasmania', 'Australia/Tasmania'), ('MET', 'MET'), ('Europe/Gibraltar', 'Europe/Gibraltar'), ('Australia/North', 'Australia/North'), ('America/Buenos_Aires', 'America/Buenos_Aires'), ('CET', 'CET'), ('Europe/Nicosia', 'Europe/Nicosia'), ('Pacific/Enderbury', 'Pacific/Enderbury'), ('America/Araguaina', 'America/Araguaina'), ('America/Tortola', 'America/Tortola'), ('Asia/Ashgabat', 'Asia/Ashgabat'), ('Atlantic/Jan_Mayen', 'Atlantic/Jan_Mayen'), ('Portugal', 'Portugal'), ('Asia/Ujung_Pandang', 'Asia/Ujung_Pandang'), ('Etc/GMT+4', 'Etc/GMT+4'), ('America/St_Thomas', 'America/St_Thomas'), ('America/Vancouver', 'America/Vancouver'), ('Asia/Karachi', 'Asia/Karachi'), ('America/Indiana/Vevay', 'America/Indiana/Vevay'), ('Atlantic/Bermuda', 'Atlantic/Bermuda'), ('America/Lima', 'America/Lima'), ('Africa/Dakar', 'Africa/Dakar'), ('America/Costa_Rica', 'America/Costa_Rica'), ('Asia/Harbin', 'Asia/Harbin'), ('Chile/Continental', 'Chile/Continental'), ('America/Swift_Current', 'America/Swift_Current'), ('Pacific/Efate', 'Pacific/Efate'), ('Etc/GMT-11', 'Etc/GMT-11'), ('America/La_Paz', 'America/La_Paz'), ('Israel', 'Israel'), ('Europe/Kiev', 'Europe/Kiev'), ('Europe/Samara', 'Europe/Samara'), ('Europe/Andorra', 'Europe/Andorra'), ('WET', 'WET'), ('Asia/Jakarta', 'Asia/Jakarta'), ('America/St_Barthelemy', 'America/St_Barthelemy'), ('Navajo', 'Navajo'), ('America/Argentina/Salta', 'America/Argentina/Salta'), ('Europe/London', 'Europe/London'), ('Antarctica/DumontDUrville', 'Antarctica/DumontDUrville'), ('Africa/Luanda', 'Africa/Luanda'), ('America/Santo_Domingo', 'America/Santo_Domingo'), ('Mexico/BajaNorte', 'Mexico/BajaNorte'), ('Indian/Mahe', 'Indian/Mahe'), ('Asia/Baku', 'Asia/Baku'), ('Egypt', 'Egypt'), ('US/Alaska', 'US/Alaska'), ('Asia/Baghdad', 'Asia/Baghdad'), ('Zulu', 'Zulu'), ('Australia/South', 'Australia/South'), ('Europe/Paris', 'Europe/Paris'), ('Mexico/BajaSur', 'Mexico/BajaSur'), ('Asia/Yekaterinburg', 'Asia/Yekaterinburg'), ('GB', 'GB'), ('Africa/Freetown', 'Africa/Freetown'), ('America/Atikokan', 'America/Atikokan'), ('UCT', 'UCT'), ('Europe/Monaco', 'Europe/Monaco'), ('Asia/Hovd', 'Asia/Hovd'), ('Europe/Belgrade', 'Europe/Belgrade'), ('America/Porto_Acre', 'America/Porto_Acre'), ('Europe/Zaporozhye', 'Europe/Zaporozhye'), ('America/Scoresbysund', 'America/Scoresbysund'), ('EST', 'EST'), ('Canada/Saskatchewan', 'Canada/Saskatchewan'), ('Atlantic/South_Georgia', 'Atlantic/South_Georgia'), ('Africa/Bujumbura', 'Africa/Bujumbura'), ('Etc/UCT', 'Etc/UCT'), ('America/Yakutat', 'America/Yakutat'), ('Europe/Warsaw', 'Europe/Warsaw'), ('Europe/Bucharest', 'Europe/Bucharest'), ('US/Central', 'US/Central'), ('Asia/Pontianak', 'Asia/Pontianak'), ('Pacific/Noumea', 'Pacific/Noumea'), ('Australia/Hobart', 'Australia/Hobart'), ('Africa/Kinshasa', 'Africa/Kinshasa'), ('Etc/GMT-0', 'Etc/GMT-0'), ('Pacific/Kwajalein', 'Pacific/Kwajalein'), ('Mexico/General', 'Mexico/General'), ('Asia/Nicosia', 'Asia/Nicosia'), ('Africa/Harare', 'Africa/Harare'), ('Atlantic/Reykjavik', 'Atlantic/Reykjavik'), ('Asia/Tokyo', 'Asia/Tokyo'), ('Australia/Eucla', 'Australia/Eucla'), ('Australia/Yancowinna', 'Australia/Yancowinna'), ('Pacific/Kiritimati', 'Pacific/Kiritimati'), ('Asia/Gaza', 'Asia/Gaza'), ('Europe/Jersey', 'Europe/Jersey'), ('Australia/Lindeman', 'Australia/Lindeman'), ('Africa/Juba', 'Africa/Juba'), ('America/Tegucigalpa', 'America/Tegucigalpa'), ('US/Samoa', 'US/Samoa'), ('Pacific/Auckland', 'Pacific/Auckland'), ('Africa/Bissau', 'Africa/Bissau'), ('Pacific/Niue', 'Pacific/Niue'), ('America/Atka', 'America/Atka'), ('Europe/Chisinau', 'Europe/Chisinau'), ('Asia/Calcutta', 'Asia/Calcutta'), ('America/Menominee', 'America/Menominee'), ('America/Glace_Bay', 'America/Glace_Bay'), ('Europe/Vienna', 'Europe/Vienna'), ('Antarctica/Vostok', 'Antarctica/Vostok'), ('Africa/Tunis', 'Africa/Tunis'), ('Africa/El_Aaiun', 'Africa/El_Aaiun'), ('America/Fort_Nelson', 'America/Fort_Nelson'), ('Etc/GMT+5', 'Etc/GMT+5'), ('Africa/Bamako', 'Africa/Bamako'), ('America/Dawson', 'America/Dawson'), ('America/Paramaribo', 'America/Paramaribo'), ('Africa/Niamey', 'Africa/Niamey'), ('Antarctica/Rothera', 'Antarctica/Rothera'), ('Jamaica', 'Jamaica'), ('Pacific/Chuuk', 'Pacific/Chuuk'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Etc/GMT', 'Etc/GMT'), ('Pacific/Bougainville', 'Pacific/Bougainville'), ('EST5EDT', 'EST5EDT'), ('Asia/Singapore', 'Asia/Singapore'), ('Etc/GMT-6', 'Etc/GMT-6'), ('America/Boa_Vista', 'America/Boa_Vista'), ('Africa/Conakry', 'Africa/Conakry'), ('Africa/Brazzaville', 'Africa/Brazzaville'), ('Pacific/Tongatapu', 'Pacific/Tongatapu'), ('Eire', 'Eire'), ('Pacific/Wake', 'Pacific/Wake'), ('Asia/Srednekolymsk', 'Asia/Srednekolymsk'), ('Pacific/Marquesas', 'Pacific/Marquesas'), ('Pacific/Midway', 'Pacific/Midway')], default='UTC', max_length=50, verbose_name='Time Zone')), ('theme', models.CharField(max_length=50, null=True, verbose_name='User Theme')), ('lang', models.CharField(default='en', max_length=3, verbose_name='Language')), ('avatar', models.BinaryField(null=True, verbose_name='Avatar')), ('messages_timeout', models.IntegerField(default=10, verbose_name="Message's Timeout")), ('keep_logged_in', models.BooleanField(default=False, verbose_name='Keep Logged In')), ('app_profile', models.JSONField(null=True, verbose_name='Custom Application Profile')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', related_query_name='user', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'zb_auth_user_profile', }, ), ]
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/migrations/0001_initial.py
0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zb_auth', '0001_initial'), ] operations = [ migrations.AlterField( model_name='userprofile', name='timezone', field=models.CharField(choices=[('Africa/Abidjan', 'Africa/Abidjan'), ('Africa/Accra', 'Africa/Accra'), ('Africa/Addis_Ababa', 'Africa/Addis_Ababa'), ('Africa/Algiers', 'Africa/Algiers'), ('Africa/Asmara', 'Africa/Asmara'), ('Africa/Asmera', 'Africa/Asmera'), ('Africa/Bamako', 'Africa/Bamako'), ('Africa/Bangui', 'Africa/Bangui'), ('Africa/Banjul', 'Africa/Banjul'), ('Africa/Bissau', 'Africa/Bissau'), ('Africa/Blantyre', 'Africa/Blantyre'), ('Africa/Brazzaville', 'Africa/Brazzaville'), ('Africa/Bujumbura', 'Africa/Bujumbura'), ('Africa/Cairo', 'Africa/Cairo'), ('Africa/Casablanca', 'Africa/Casablanca'), ('Africa/Ceuta', 'Africa/Ceuta'), ('Africa/Conakry', 'Africa/Conakry'), ('Africa/Dakar', 'Africa/Dakar'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('Africa/Djibouti', 'Africa/Djibouti'), ('Africa/Douala', 'Africa/Douala'), ('Africa/El_Aaiun', 'Africa/El_Aaiun'), ('Africa/Freetown', 'Africa/Freetown'), ('Africa/Gaborone', 'Africa/Gaborone'), ('Africa/Harare', 'Africa/Harare'), ('Africa/Johannesburg', 'Africa/Johannesburg'), ('Africa/Juba', 'Africa/Juba'), ('Africa/Kampala', 'Africa/Kampala'), ('Africa/Khartoum', 'Africa/Khartoum'), ('Africa/Kigali', 'Africa/Kigali'), ('Africa/Kinshasa', 'Africa/Kinshasa'), ('Africa/Lagos', 'Africa/Lagos'), ('Africa/Libreville', 'Africa/Libreville'), ('Africa/Lome', 'Africa/Lome'), ('Africa/Luanda', 'Africa/Luanda'), ('Africa/Lubumbashi', 'Africa/Lubumbashi'), ('Africa/Lusaka', 'Africa/Lusaka'), ('Africa/Malabo', 'Africa/Malabo'), ('Africa/Maputo', 'Africa/Maputo'), ('Africa/Maseru', 'Africa/Maseru'), ('Africa/Mbabane', 'Africa/Mbabane'), ('Africa/Mogadishu', 'Africa/Mogadishu'), ('Africa/Monrovia', 'Africa/Monrovia'), ('Africa/Nairobi', 'Africa/Nairobi'), ('Africa/Ndjamena', 'Africa/Ndjamena'), ('Africa/Niamey', 'Africa/Niamey'), ('Africa/Nouakchott', 'Africa/Nouakchott'), ('Africa/Ouagadougou', 'Africa/Ouagadougou'), ('Africa/Porto-Novo', 'Africa/Porto-Novo'), ('Africa/Sao_Tome', 'Africa/Sao_Tome'), ('Africa/Timbuktu', 'Africa/Timbuktu'), ('Africa/Tripoli', 'Africa/Tripoli'), ('Africa/Tunis', 'Africa/Tunis'), ('Africa/Windhoek', 'Africa/Windhoek'), ('America/Adak', 'America/Adak'), ('America/Anchorage', 'America/Anchorage'), ('America/Anguilla', 'America/Anguilla'), ('America/Antigua', 'America/Antigua'), ('America/Araguaina', 'America/Araguaina'), ('America/Argentina/Buenos_Aires', 'America/Argentina/Buenos_Aires'), ('America/Argentina/Catamarca', 'America/Argentina/Catamarca'), ('America/Argentina/ComodRivadavia', 'America/Argentina/ComodRivadavia'), ('America/Argentina/Cordoba', 'America/Argentina/Cordoba'), ('America/Argentina/Jujuy', 'America/Argentina/Jujuy'), ('America/Argentina/La_Rioja', 'America/Argentina/La_Rioja'), ('America/Argentina/Mendoza', 'America/Argentina/Mendoza'), ('America/Argentina/Rio_Gallegos', 'America/Argentina/Rio_Gallegos'), ('America/Argentina/Salta', 'America/Argentina/Salta'), ('America/Argentina/San_Juan', 'America/Argentina/San_Juan'), ('America/Argentina/San_Luis', 'America/Argentina/San_Luis'), ('America/Argentina/Tucuman', 'America/Argentina/Tucuman'), ('America/Argentina/Ushuaia', 'America/Argentina/Ushuaia'), ('America/Aruba', 'America/Aruba'), ('America/Asuncion', 'America/Asuncion'), ('America/Atikokan', 'America/Atikokan'), ('America/Atka', 'America/Atka'), ('America/Bahia', 'America/Bahia'), ('America/Bahia_Banderas', 'America/Bahia_Banderas'), ('America/Barbados', 'America/Barbados'), ('America/Belem', 'America/Belem'), ('America/Belize', 'America/Belize'), ('America/Blanc-Sablon', 'America/Blanc-Sablon'), ('America/Boa_Vista', 'America/Boa_Vista'), ('America/Bogota', 'America/Bogota'), ('America/Boise', 'America/Boise'), ('America/Buenos_Aires', 'America/Buenos_Aires'), ('America/Cambridge_Bay', 'America/Cambridge_Bay'), ('America/Campo_Grande', 'America/Campo_Grande'), ('America/Cancun', 'America/Cancun'), ('America/Caracas', 'America/Caracas'), ('America/Catamarca', 'America/Catamarca'), ('America/Cayenne', 'America/Cayenne'), ('America/Cayman', 'America/Cayman'), ('America/Chicago', 'America/Chicago'), ('America/Chihuahua', 'America/Chihuahua'), ('America/Ciudad_Juarez', 'America/Ciudad_Juarez'), ('America/Coral_Harbour', 'America/Coral_Harbour'), ('America/Cordoba', 'America/Cordoba'), ('America/Costa_Rica', 'America/Costa_Rica'), ('America/Creston', 'America/Creston'), ('America/Cuiaba', 'America/Cuiaba'), ('America/Curacao', 'America/Curacao'), ('America/Danmarkshavn', 'America/Danmarkshavn'), ('America/Dawson', 'America/Dawson'), ('America/Dawson_Creek', 'America/Dawson_Creek'), ('America/Denver', 'America/Denver'), ('America/Detroit', 'America/Detroit'), ('America/Dominica', 'America/Dominica'), ('America/Edmonton', 'America/Edmonton'), ('America/Eirunepe', 'America/Eirunepe'), ('America/El_Salvador', 'America/El_Salvador'), ('America/Ensenada', 'America/Ensenada'), ('America/Fort_Nelson', 'America/Fort_Nelson'), ('America/Fort_Wayne', 'America/Fort_Wayne'), ('America/Fortaleza', 'America/Fortaleza'), ('America/Glace_Bay', 'America/Glace_Bay'), ('America/Godthab', 'America/Godthab'), ('America/Goose_Bay', 'America/Goose_Bay'), ('America/Grand_Turk', 'America/Grand_Turk'), ('America/Grenada', 'America/Grenada'), ('America/Guadeloupe', 'America/Guadeloupe'), ('America/Guatemala', 'America/Guatemala'), ('America/Guayaquil', 'America/Guayaquil'), ('America/Guyana', 'America/Guyana'), ('America/Halifax', 'America/Halifax'), ('America/Havana', 'America/Havana'), ('America/Hermosillo', 'America/Hermosillo'), ('America/Indiana/Indianapolis', 'America/Indiana/Indianapolis'), ('America/Indiana/Knox', 'America/Indiana/Knox'), ('America/Indiana/Marengo', 'America/Indiana/Marengo'), ('America/Indiana/Petersburg', 'America/Indiana/Petersburg'), ('America/Indiana/Tell_City', 'America/Indiana/Tell_City'), ('America/Indiana/Vevay', 'America/Indiana/Vevay'), ('America/Indiana/Vincennes', 'America/Indiana/Vincennes'), ('America/Indiana/Winamac', 'America/Indiana/Winamac'), ('America/Indianapolis', 'America/Indianapolis'), ('America/Inuvik', 'America/Inuvik'), ('America/Iqaluit', 'America/Iqaluit'), ('America/Jamaica', 'America/Jamaica'), ('America/Jujuy', 'America/Jujuy'), ('America/Juneau', 'America/Juneau'), ('America/Kentucky/Louisville', 'America/Kentucky/Louisville'), ('America/Kentucky/Monticello', 'America/Kentucky/Monticello'), ('America/Knox_IN', 'America/Knox_IN'), ('America/Kralendijk', 'America/Kralendijk'), ('America/La_Paz', 'America/La_Paz'), ('America/Lima', 'America/Lima'), ('America/Los_Angeles', 'America/Los_Angeles'), ('America/Louisville', 'America/Louisville'), ('America/Lower_Princes', 'America/Lower_Princes'), ('America/Maceio', 'America/Maceio'), ('America/Managua', 'America/Managua'), ('America/Manaus', 'America/Manaus'), ('America/Marigot', 'America/Marigot'), ('America/Martinique', 'America/Martinique'), ('America/Matamoros', 'America/Matamoros'), ('America/Mazatlan', 'America/Mazatlan'), ('America/Mendoza', 'America/Mendoza'), ('America/Menominee', 'America/Menominee'), ('America/Merida', 'America/Merida'), ('America/Metlakatla', 'America/Metlakatla'), ('America/Mexico_City', 'America/Mexico_City'), ('America/Miquelon', 'America/Miquelon'), ('America/Moncton', 'America/Moncton'), ('America/Monterrey', 'America/Monterrey'), ('America/Montevideo', 'America/Montevideo'), ('America/Montreal', 'America/Montreal'), ('America/Montserrat', 'America/Montserrat'), ('America/Nassau', 'America/Nassau'), ('America/New_York', 'America/New_York'), ('America/Nipigon', 'America/Nipigon'), ('America/Nome', 'America/Nome'), ('America/Noronha', 'America/Noronha'), ('America/North_Dakota/Beulah', 'America/North_Dakota/Beulah'), ('America/North_Dakota/Center', 'America/North_Dakota/Center'), ('America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem'), ('America/Nuuk', 'America/Nuuk'), ('America/Ojinaga', 'America/Ojinaga'), ('America/Panama', 'America/Panama'), ('America/Pangnirtung', 'America/Pangnirtung'), ('America/Paramaribo', 'America/Paramaribo'), ('America/Phoenix', 'America/Phoenix'), ('America/Port-au-Prince', 'America/Port-au-Prince'), ('America/Port_of_Spain', 'America/Port_of_Spain'), ('America/Porto_Acre', 'America/Porto_Acre'), ('America/Porto_Velho', 'America/Porto_Velho'), ('America/Puerto_Rico', 'America/Puerto_Rico'), ('America/Punta_Arenas', 'America/Punta_Arenas'), ('America/Rainy_River', 'America/Rainy_River'), ('America/Rankin_Inlet', 'America/Rankin_Inlet'), ('America/Recife', 'America/Recife'), ('America/Regina', 'America/Regina'), ('America/Resolute', 'America/Resolute'), ('America/Rio_Branco', 'America/Rio_Branco'), ('America/Rosario', 'America/Rosario'), ('America/Santa_Isabel', 'America/Santa_Isabel'), ('America/Santarem', 'America/Santarem'), ('America/Santiago', 'America/Santiago'), ('America/Santo_Domingo', 'America/Santo_Domingo'), ('America/Sao_Paulo', 'America/Sao_Paulo'), ('America/Scoresbysund', 'America/Scoresbysund'), ('America/Shiprock', 'America/Shiprock'), ('America/Sitka', 'America/Sitka'), ('America/St_Barthelemy', 'America/St_Barthelemy'), ('America/St_Johns', 'America/St_Johns'), ('America/St_Kitts', 'America/St_Kitts'), ('America/St_Lucia', 'America/St_Lucia'), ('America/St_Thomas', 'America/St_Thomas'), ('America/St_Vincent', 'America/St_Vincent'), ('America/Swift_Current', 'America/Swift_Current'), ('America/Tegucigalpa', 'America/Tegucigalpa'), ('America/Thule', 'America/Thule'), ('America/Thunder_Bay', 'America/Thunder_Bay'), ('America/Tijuana', 'America/Tijuana'), ('America/Toronto', 'America/Toronto'), ('America/Tortola', 'America/Tortola'), ('America/Vancouver', 'America/Vancouver'), ('America/Virgin', 'America/Virgin'), ('America/Whitehorse', 'America/Whitehorse'), ('America/Winnipeg', 'America/Winnipeg'), ('America/Yakutat', 'America/Yakutat'), ('America/Yellowknife', 'America/Yellowknife'), ('Antarctica/Casey', 'Antarctica/Casey'), ('Antarctica/Davis', 'Antarctica/Davis'), ('Antarctica/DumontDUrville', 'Antarctica/DumontDUrville'), ('Antarctica/Macquarie', 'Antarctica/Macquarie'), ('Antarctica/Mawson', 'Antarctica/Mawson'), ('Antarctica/McMurdo', 'Antarctica/McMurdo'), ('Antarctica/Palmer', 'Antarctica/Palmer'), ('Antarctica/Rothera', 'Antarctica/Rothera'), ('Antarctica/South_Pole', 'Antarctica/South_Pole'), ('Antarctica/Syowa', 'Antarctica/Syowa'), ('Antarctica/Troll', 'Antarctica/Troll'), ('Antarctica/Vostok', 'Antarctica/Vostok'), ('Arctic/Longyearbyen', 'Arctic/Longyearbyen'), ('Asia/Aden', 'Asia/Aden'), ('Asia/Almaty', 'Asia/Almaty'), ('Asia/Amman', 'Asia/Amman'), ('Asia/Anadyr', 'Asia/Anadyr'), ('Asia/Aqtau', 'Asia/Aqtau'), ('Asia/Aqtobe', 'Asia/Aqtobe'), ('Asia/Ashgabat', 'Asia/Ashgabat'), ('Asia/Ashkhabad', 'Asia/Ashkhabad'), ('Asia/Atyrau', 'Asia/Atyrau'), ('Asia/Baghdad', 'Asia/Baghdad'), ('Asia/Bahrain', 'Asia/Bahrain'), ('Asia/Baku', 'Asia/Baku'), ('Asia/Bangkok', 'Asia/Bangkok'), ('Asia/Barnaul', 'Asia/Barnaul'), ('Asia/Beirut', 'Asia/Beirut'), ('Asia/Bishkek', 'Asia/Bishkek'), ('Asia/Brunei', 'Asia/Brunei'), ('Asia/Calcutta', 'Asia/Calcutta'), ('Asia/Chita', 'Asia/Chita'), ('Asia/Choibalsan', 'Asia/Choibalsan'), ('Asia/Chongqing', 'Asia/Chongqing'), ('Asia/Chungking', 'Asia/Chungking'), ('Asia/Colombo', 'Asia/Colombo'), ('Asia/Dacca', 'Asia/Dacca'), ('Asia/Damascus', 'Asia/Damascus'), ('Asia/Dhaka', 'Asia/Dhaka'), ('Asia/Dili', 'Asia/Dili'), ('Asia/Dubai', 'Asia/Dubai'), ('Asia/Dushanbe', 'Asia/Dushanbe'), ('Asia/Famagusta', 'Asia/Famagusta'), ('Asia/Gaza', 'Asia/Gaza'), ('Asia/Harbin', 'Asia/Harbin'), ('Asia/Hebron', 'Asia/Hebron'), ('Asia/Ho_Chi_Minh', 'Asia/Ho_Chi_Minh'), ('Asia/Hong_Kong', 'Asia/Hong_Kong'), ('Asia/Hovd', 'Asia/Hovd'), ('Asia/Irkutsk', 'Asia/Irkutsk'), ('Asia/Istanbul', 'Asia/Istanbul'), ('Asia/Jakarta', 'Asia/Jakarta'), ('Asia/Jayapura', 'Asia/Jayapura'), ('Asia/Jerusalem', 'Asia/Jerusalem'), ('Asia/Kabul', 'Asia/Kabul'), ('Asia/Kamchatka', 'Asia/Kamchatka'), ('Asia/Karachi', 'Asia/Karachi'), ('Asia/Kashgar', 'Asia/Kashgar'), ('Asia/Kathmandu', 'Asia/Kathmandu'), ('Asia/Katmandu', 'Asia/Katmandu'), ('Asia/Khandyga', 'Asia/Khandyga'), ('Asia/Kolkata', 'Asia/Kolkata'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Asia/Kuala_Lumpur', 'Asia/Kuala_Lumpur'), ('Asia/Kuching', 'Asia/Kuching'), ('Asia/Kuwait', 'Asia/Kuwait'), ('Asia/Macao', 'Asia/Macao'), ('Asia/Macau', 'Asia/Macau'), ('Asia/Magadan', 'Asia/Magadan'), ('Asia/Makassar', 'Asia/Makassar'), ('Asia/Manila', 'Asia/Manila'), ('Asia/Muscat', 'Asia/Muscat'), ('Asia/Nicosia', 'Asia/Nicosia'), ('Asia/Novokuznetsk', 'Asia/Novokuznetsk'), ('Asia/Novosibirsk', 'Asia/Novosibirsk'), ('Asia/Omsk', 'Asia/Omsk'), ('Asia/Oral', 'Asia/Oral'), ('Asia/Phnom_Penh', 'Asia/Phnom_Penh'), ('Asia/Pontianak', 'Asia/Pontianak'), ('Asia/Pyongyang', 'Asia/Pyongyang'), ('Asia/Qatar', 'Asia/Qatar'), ('Asia/Qostanay', 'Asia/Qostanay'), ('Asia/Qyzylorda', 'Asia/Qyzylorda'), ('Asia/Rangoon', 'Asia/Rangoon'), ('Asia/Riyadh', 'Asia/Riyadh'), ('Asia/Saigon', 'Asia/Saigon'), ('Asia/Sakhalin', 'Asia/Sakhalin'), ('Asia/Samarkand', 'Asia/Samarkand'), ('Asia/Seoul', 'Asia/Seoul'), ('Asia/Shanghai', 'Asia/Shanghai'), ('Asia/Singapore', 'Asia/Singapore'), ('Asia/Srednekolymsk', 'Asia/Srednekolymsk'), ('Asia/Taipei', 'Asia/Taipei'), ('Asia/Tashkent', 'Asia/Tashkent'), ('Asia/Tbilisi', 'Asia/Tbilisi'), ('Asia/Tehran', 'Asia/Tehran'), ('Asia/Tel_Aviv', 'Asia/Tel_Aviv'), ('Asia/Thimbu', 'Asia/Thimbu'), ('Asia/Thimphu', 'Asia/Thimphu'), ('Asia/Tokyo', 'Asia/Tokyo'), ('Asia/Tomsk', 'Asia/Tomsk'), ('Asia/Ujung_Pandang', 'Asia/Ujung_Pandang'), ('Asia/Ulaanbaatar', 'Asia/Ulaanbaatar'), ('Asia/Ulan_Bator', 'Asia/Ulan_Bator'), ('Asia/Urumqi', 'Asia/Urumqi'), ('Asia/Ust-Nera', 'Asia/Ust-Nera'), ('Asia/Vientiane', 'Asia/Vientiane'), ('Asia/Vladivostok', 'Asia/Vladivostok'), ('Asia/Yakutsk', 'Asia/Yakutsk'), ('Asia/Yangon', 'Asia/Yangon'), ('Asia/Yekaterinburg', 'Asia/Yekaterinburg'), ('Asia/Yerevan', 'Asia/Yerevan'), ('Atlantic/Azores', 'Atlantic/Azores'), ('Atlantic/Bermuda', 'Atlantic/Bermuda'), ('Atlantic/Canary', 'Atlantic/Canary'), ('Atlantic/Cape_Verde', 'Atlantic/Cape_Verde'), ('Atlantic/Faeroe', 'Atlantic/Faeroe'), ('Atlantic/Faroe', 'Atlantic/Faroe'), ('Atlantic/Jan_Mayen', 'Atlantic/Jan_Mayen'), ('Atlantic/Madeira', 'Atlantic/Madeira'), ('Atlantic/Reykjavik', 'Atlantic/Reykjavik'), ('Atlantic/South_Georgia', 'Atlantic/South_Georgia'), ('Atlantic/St_Helena', 'Atlantic/St_Helena'), ('Atlantic/Stanley', 'Atlantic/Stanley'), ('Australia/ACT', 'Australia/ACT'), ('Australia/Adelaide', 'Australia/Adelaide'), ('Australia/Brisbane', 'Australia/Brisbane'), ('Australia/Broken_Hill', 'Australia/Broken_Hill'), ('Australia/Canberra', 'Australia/Canberra'), ('Australia/Currie', 'Australia/Currie'), ('Australia/Darwin', 'Australia/Darwin'), ('Australia/Eucla', 'Australia/Eucla'), ('Australia/Hobart', 'Australia/Hobart'), ('Australia/LHI', 'Australia/LHI'), ('Australia/Lindeman', 'Australia/Lindeman'), ('Australia/Lord_Howe', 'Australia/Lord_Howe'), ('Australia/Melbourne', 'Australia/Melbourne'), ('Australia/NSW', 'Australia/NSW'), ('Australia/North', 'Australia/North'), ('Australia/Perth', 'Australia/Perth'), ('Australia/Queensland', 'Australia/Queensland'), ('Australia/South', 'Australia/South'), ('Australia/Sydney', 'Australia/Sydney'), ('Australia/Tasmania', 'Australia/Tasmania'), ('Australia/Victoria', 'Australia/Victoria'), ('Australia/West', 'Australia/West'), ('Australia/Yancowinna', 'Australia/Yancowinna'), ('Brazil/Acre', 'Brazil/Acre'), ('Brazil/DeNoronha', 'Brazil/DeNoronha'), ('Brazil/East', 'Brazil/East'), ('Brazil/West', 'Brazil/West'), ('CET', 'CET'), ('CST6CDT', 'CST6CDT'), ('Canada/Atlantic', 'Canada/Atlantic'), ('Canada/Central', 'Canada/Central'), ('Canada/Eastern', 'Canada/Eastern'), ('Canada/Mountain', 'Canada/Mountain'), ('Canada/Newfoundland', 'Canada/Newfoundland'), ('Canada/Pacific', 'Canada/Pacific'), ('Canada/Saskatchewan', 'Canada/Saskatchewan'), ('Canada/Yukon', 'Canada/Yukon'), ('Chile/Continental', 'Chile/Continental'), ('Chile/EasterIsland', 'Chile/EasterIsland'), ('Cuba', 'Cuba'), ('EET', 'EET'), ('EST', 'EST'), ('EST5EDT', 'EST5EDT'), ('Egypt', 'Egypt'), ('Eire', 'Eire'), ('Etc/GMT', 'Etc/GMT'), ('Etc/GMT+0', 'Etc/GMT+0'), ('Etc/GMT+1', 'Etc/GMT+1'), ('Etc/GMT+10', 'Etc/GMT+10'), ('Etc/GMT+11', 'Etc/GMT+11'), ('Etc/GMT+12', 'Etc/GMT+12'), ('Etc/GMT+2', 'Etc/GMT+2'), ('Etc/GMT+3', 'Etc/GMT+3'), ('Etc/GMT+4', 'Etc/GMT+4'), ('Etc/GMT+5', 'Etc/GMT+5'), ('Etc/GMT+6', 'Etc/GMT+6'), ('Etc/GMT+7', 'Etc/GMT+7'), ('Etc/GMT+8', 'Etc/GMT+8'), ('Etc/GMT+9', 'Etc/GMT+9'), ('Etc/GMT-0', 'Etc/GMT-0'), ('Etc/GMT-1', 'Etc/GMT-1'), ('Etc/GMT-10', 'Etc/GMT-10'), ('Etc/GMT-11', 'Etc/GMT-11'), ('Etc/GMT-12', 'Etc/GMT-12'), ('Etc/GMT-13', 'Etc/GMT-13'), ('Etc/GMT-14', 'Etc/GMT-14'), ('Etc/GMT-2', 'Etc/GMT-2'), ('Etc/GMT-3', 'Etc/GMT-3'), ('Etc/GMT-4', 'Etc/GMT-4'), ('Etc/GMT-5', 'Etc/GMT-5'), ('Etc/GMT-6', 'Etc/GMT-6'), ('Etc/GMT-7', 'Etc/GMT-7'), ('Etc/GMT-8', 'Etc/GMT-8'), ('Etc/GMT-9', 'Etc/GMT-9'), ('Etc/GMT0', 'Etc/GMT0'), ('Etc/Greenwich', 'Etc/Greenwich'), ('Etc/UCT', 'Etc/UCT'), ('Etc/UTC', 'Etc/UTC'), ('Etc/Universal', 'Etc/Universal'), ('Etc/Zulu', 'Etc/Zulu'), ('Europe/Amsterdam', 'Europe/Amsterdam'), ('Europe/Andorra', 'Europe/Andorra'), ('Europe/Astrakhan', 'Europe/Astrakhan'), ('Europe/Athens', 'Europe/Athens'), ('Europe/Belfast', 'Europe/Belfast'), ('Europe/Belgrade', 'Europe/Belgrade'), ('Europe/Berlin', 'Europe/Berlin'), ('Europe/Bratislava', 'Europe/Bratislava'), ('Europe/Brussels', 'Europe/Brussels'), ('Europe/Bucharest', 'Europe/Bucharest'), ('Europe/Budapest', 'Europe/Budapest'), ('Europe/Busingen', 'Europe/Busingen'), ('Europe/Chisinau', 'Europe/Chisinau'), ('Europe/Copenhagen', 'Europe/Copenhagen'), ('Europe/Dublin', 'Europe/Dublin'), ('Europe/Gibraltar', 'Europe/Gibraltar'), ('Europe/Guernsey', 'Europe/Guernsey'), ('Europe/Helsinki', 'Europe/Helsinki'), ('Europe/Isle_of_Man', 'Europe/Isle_of_Man'), ('Europe/Istanbul', 'Europe/Istanbul'), ('Europe/Jersey', 'Europe/Jersey'), ('Europe/Kaliningrad', 'Europe/Kaliningrad'), ('Europe/Kiev', 'Europe/Kiev'), ('Europe/Kirov', 'Europe/Kirov'), ('Europe/Kyiv', 'Europe/Kyiv'), ('Europe/Lisbon', 'Europe/Lisbon'), ('Europe/Ljubljana', 'Europe/Ljubljana'), ('Europe/London', 'Europe/London'), ('Europe/Luxembourg', 'Europe/Luxembourg'), ('Europe/Madrid', 'Europe/Madrid'), ('Europe/Malta', 'Europe/Malta'), ('Europe/Mariehamn', 'Europe/Mariehamn'), ('Europe/Minsk', 'Europe/Minsk'), ('Europe/Monaco', 'Europe/Monaco'), ('Europe/Moscow', 'Europe/Moscow'), ('Europe/Nicosia', 'Europe/Nicosia'), ('Europe/Oslo', 'Europe/Oslo'), ('Europe/Paris', 'Europe/Paris'), ('Europe/Podgorica', 'Europe/Podgorica'), ('Europe/Prague', 'Europe/Prague'), ('Europe/Riga', 'Europe/Riga'), ('Europe/Rome', 'Europe/Rome'), ('Europe/Samara', 'Europe/Samara'), ('Europe/San_Marino', 'Europe/San_Marino'), ('Europe/Sarajevo', 'Europe/Sarajevo'), ('Europe/Saratov', 'Europe/Saratov'), ('Europe/Simferopol', 'Europe/Simferopol'), ('Europe/Skopje', 'Europe/Skopje'), ('Europe/Sofia', 'Europe/Sofia'), ('Europe/Stockholm', 'Europe/Stockholm'), ('Europe/Tallinn', 'Europe/Tallinn'), ('Europe/Tirane', 'Europe/Tirane'), ('Europe/Tiraspol', 'Europe/Tiraspol'), ('Europe/Ulyanovsk', 'Europe/Ulyanovsk'), ('Europe/Uzhgorod', 'Europe/Uzhgorod'), ('Europe/Vaduz', 'Europe/Vaduz'), ('Europe/Vatican', 'Europe/Vatican'), ('Europe/Vienna', 'Europe/Vienna'), ('Europe/Vilnius', 'Europe/Vilnius'), ('Europe/Volgograd', 'Europe/Volgograd'), ('Europe/Warsaw', 'Europe/Warsaw'), ('Europe/Zagreb', 'Europe/Zagreb'), ('Europe/Zaporozhye', 'Europe/Zaporozhye'), ('Europe/Zurich', 'Europe/Zurich'), ('GB', 'GB'), ('GB-Eire', 'GB-Eire'), ('GMT', 'GMT'), ('GMT+0', 'GMT+0'), ('GMT-0', 'GMT-0'), ('GMT0', 'GMT0'), ('Greenwich', 'Greenwich'), ('HST', 'HST'), ('Hongkong', 'Hongkong'), ('Iceland', 'Iceland'), ('Indian/Antananarivo', 'Indian/Antananarivo'), ('Indian/Chagos', 'Indian/Chagos'), ('Indian/Christmas', 'Indian/Christmas'), ('Indian/Cocos', 'Indian/Cocos'), ('Indian/Comoro', 'Indian/Comoro'), ('Indian/Kerguelen', 'Indian/Kerguelen'), ('Indian/Mahe', 'Indian/Mahe'), ('Indian/Maldives', 'Indian/Maldives'), ('Indian/Mauritius', 'Indian/Mauritius'), ('Indian/Mayotte', 'Indian/Mayotte'), ('Indian/Reunion', 'Indian/Reunion'), ('Iran', 'Iran'), ('Israel', 'Israel'), ('Jamaica', 'Jamaica'), ('Japan', 'Japan'), ('Kwajalein', 'Kwajalein'), ('Libya', 'Libya'), ('MET', 'MET'), ('MST', 'MST'), ('MST7MDT', 'MST7MDT'), ('Mexico/BajaNorte', 'Mexico/BajaNorte'), ('Mexico/BajaSur', 'Mexico/BajaSur'), ('Mexico/General', 'Mexico/General'), ('NZ', 'NZ'), ('NZ-CHAT', 'NZ-CHAT'), ('Navajo', 'Navajo'), ('PRC', 'PRC'), ('PST8PDT', 'PST8PDT'), ('Pacific/Apia', 'Pacific/Apia'), ('Pacific/Auckland', 'Pacific/Auckland'), ('Pacific/Bougainville', 'Pacific/Bougainville'), ('Pacific/Chatham', 'Pacific/Chatham'), ('Pacific/Chuuk', 'Pacific/Chuuk'), ('Pacific/Easter', 'Pacific/Easter'), ('Pacific/Efate', 'Pacific/Efate'), ('Pacific/Enderbury', 'Pacific/Enderbury'), ('Pacific/Fakaofo', 'Pacific/Fakaofo'), ('Pacific/Fiji', 'Pacific/Fiji'), ('Pacific/Funafuti', 'Pacific/Funafuti'), ('Pacific/Galapagos', 'Pacific/Galapagos'), ('Pacific/Gambier', 'Pacific/Gambier'), ('Pacific/Guadalcanal', 'Pacific/Guadalcanal'), ('Pacific/Guam', 'Pacific/Guam'), ('Pacific/Honolulu', 'Pacific/Honolulu'), ('Pacific/Johnston', 'Pacific/Johnston'), ('Pacific/Kanton', 'Pacific/Kanton'), ('Pacific/Kiritimati', 'Pacific/Kiritimati'), ('Pacific/Kosrae', 'Pacific/Kosrae'), ('Pacific/Kwajalein', 'Pacific/Kwajalein'), ('Pacific/Majuro', 'Pacific/Majuro'), ('Pacific/Marquesas', 'Pacific/Marquesas'), ('Pacific/Midway', 'Pacific/Midway'), ('Pacific/Nauru', 'Pacific/Nauru'), ('Pacific/Niue', 'Pacific/Niue'), ('Pacific/Norfolk', 'Pacific/Norfolk'), ('Pacific/Noumea', 'Pacific/Noumea'), ('Pacific/Pago_Pago', 'Pacific/Pago_Pago'), ('Pacific/Palau', 'Pacific/Palau'), ('Pacific/Pitcairn', 'Pacific/Pitcairn'), ('Pacific/Pohnpei', 'Pacific/Pohnpei'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Pacific/Port_Moresby', 'Pacific/Port_Moresby'), ('Pacific/Rarotonga', 'Pacific/Rarotonga'), ('Pacific/Saipan', 'Pacific/Saipan'), ('Pacific/Samoa', 'Pacific/Samoa'), ('Pacific/Tahiti', 'Pacific/Tahiti'), ('Pacific/Tarawa', 'Pacific/Tarawa'), ('Pacific/Tongatapu', 'Pacific/Tongatapu'), ('Pacific/Truk', 'Pacific/Truk'), ('Pacific/Wake', 'Pacific/Wake'), ('Pacific/Wallis', 'Pacific/Wallis'), ('Pacific/Yap', 'Pacific/Yap'), ('Poland', 'Poland'), ('Portugal', 'Portugal'), ('ROC', 'ROC'), ('ROK', 'ROK'), ('Singapore', 'Singapore'), ('Turkey', 'Turkey'), ('UCT', 'UCT'), ('US/Alaska', 'US/Alaska'), ('US/Aleutian', 'US/Aleutian'), ('US/Arizona', 'US/Arizona'), ('US/Central', 'US/Central'), ('US/East-Indiana', 'US/East-Indiana'), ('US/Eastern', 'US/Eastern'), ('US/Hawaii', 'US/Hawaii'), ('US/Indiana-Starke', 'US/Indiana-Starke'), ('US/Michigan', 'US/Michigan'), ('US/Mountain', 'US/Mountain'), ('US/Pacific', 'US/Pacific'), ('US/Samoa', 'US/Samoa'), ('UTC', 'UTC'), ('Universal', 'Universal'), ('W-SU', 'W-SU'), ('WET', 'WET'), ('Zulu', 'Zulu')], default='UTC', max_length=50, verbose_name='Time Zone'), ), ]
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/migrations/0002_alter_userprofile_timezone.py
0002_alter_userprofile_timezone.py
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 27/04/23 7:02 # Project: Zibanu - Django # Module Name: token # Description: # **************************************************************** from django.contrib.auth import authenticate from django.contrib.auth import get_user_model from django.contrib.auth import user_logged_in, user_login_failed from django.contrib.auth.models import update_last_login from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import AuthenticationFailed from rest_framework_simplejwt.serializers import TokenObtainSerializer, TokenRefreshSlidingSerializer from rest_framework_simplejwt.settings import api_settings from rest_framework_simplejwt.tokens import SlidingToken, RefreshToken from typing import Dict, Any from zibanu.django.auth.api.serializers.user import UserTokenSerializer from zibanu.django.auth.lib.utils import get_cache_key from zibanu.django.utils import get_http_origin class EmailTokenObtainSerializer(TokenObtainSerializer): """ SimpleJWTToken serializer to get token with full user object payload for email authentication method. """ username_field = get_user_model().EMAIL_FIELD def __init__(self, *args, **kwargs): """ Constructor method for EmailTokenObtainSerializer Class Parameters ---------- *args: Single tuple of parameters values **kwargs: Dictionary with key - value of parameters. """ super().__init__(*args, **kwargs) self.__request = self.context.get("request") self.__key_suffix = get_http_origin(self.context.get("request"), md5=True) self.__close_sessions = self.context.get("request").data.pop("close", False) self.error_messages["multiple_login"] = _("The user does not have allowed multiple login. Please close previous sessions.") self.error_messages["invalid_user"] = _("The token does not have associated user.") self.user = None @property def close_sessions(self): """ Property to view if request has close sessions flag active. Returns ------- close_sessions: boolean: True if close previous session, otherwise False or None """ return self.__close_sessions def _validate_sessions(self, user): """ Method to validate if the user has another open session. If request data parameter close is True, create new session and close others. Parameters ---------- user: User object representation. Returns ------- None """ if user.profile is not None and not user.profile.multiple_login: cache_key = get_cache_key(self.__request, user) cached_token = cache.get(cache_key, None) if self.close_sessions and cached_token is not None: cached_token.blacklist() cache.delete(cache_key) else: if cached_token is not None: raise AuthenticationFailed(self.error_messages["multiple_login"]) def _save_cache(self, token: Any) -> str: """ Method to save the token in cache if multiple_login are not allowed. Parameters ---------- token: Token object Returns ------- String with token """ # Validate cache if required if self.user.profile is not None and not self.user.profile.multiple_login: cache.set(get_cache_key(self.__request, self.user), token, timeout=token.lifetime.total_seconds()) return str(token) @classmethod def get_token(cls, user): """ Get JWT token including full user object data Parameters ---------- user: User object to serialize Returns ------- token: SlidingToken object """ token = super().get_token(user) # Include user data user_serializer = UserTokenSerializer(instance=user) token["user"] = user_serializer.data return token def validate(self, attrs: Dict[str, Any]) -> Dict[Any, Any]: """ Serializer validate method to validate user object from attrs parameter Parameters ---------- attrs: Request dictionary attributes Returns ------- None: Empty data """ user = get_user_model().objects.filter(email__iexact=attrs.get(self.username_field)).first() if user is None: user_login_failed.send(self.__class__, user=None, request=self.context.get("request"), detail=attrs.get(self.username_field)) raise AuthenticationFailed(self.error_messages["no_active_account"], "no_active_account") self._validate_sessions(user) authenticate_kwargs = { get_user_model().USERNAME_FIELD: user.get_username(), "password": attrs.get("password") } self.user = authenticate(**authenticate_kwargs) if not api_settings.USER_AUTHENTICATION_RULE(self.user): raise AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return {} class EmailTokenObtainSlidingSerializer(EmailTokenObtainSerializer): """ TokenSlidingSerializer child class of EmailTokenObtainSerializer """ token_class = SlidingToken def validate(self, attrs: Dict[str, Any]) -> Dict[Any, Any]: """ Serializer validate method to validate user object from request attributes Parameters ---------- attrs: Request dictionary attributes Returns ------- data: SlidingToken object with full user object data """ data = super().validate(attrs) token = self.get_token(self.user) data["token"] = self._save_cache(token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) user_logged_in.send(sender=self.__class__, user=self.user, request=self.context.get("request")) return data class EmailTokenRefreshSlidingSerializer(TokenRefreshSlidingSerializer): """ EmailTokenRefreshSlidingSerializer child class from TokenRefreshSlidingSerializer that implements validation from cached tokens and store a new token in cache. """ def __init__(self, *args, **kwargs): """ Override method to set a new message for invalid token. Parameters ---------- *args: Single tuple of parameters values **kwargs: Dictionary with key/value of parameters. """ super().__init__(*args, **kwargs) self.__request = self.context.get("request") self.error_messages["invalid_token"] = _("You're trying to refresh and invalid token.") def __get_user(self, token: SlidingToken): user_id = token.payload.get("user_id") user = None try: user = get_user_model().objects.get(pk=user_id) except ObjectDoesNotExist: user = None finally: return user def validate(self, attrs): """ Override method to implement a cached token validation and new token generation. Parameters ---------- attrs: Set of attributes for token generation Returns ------- Dictionary with "token" key and new token value. """ token = self.token_class(attrs["token"]) token.check_exp(api_settings.SLIDING_TOKEN_REFRESH_EXP_CLAIM) # Load user from token and generate cache key user = self.__get_user(token) if user is None: raise AuthenticationFailed(self.error_messages["invalid_user"]) cache_key = get_cache_key(self.__request, user) # Validate if multiple login flag is active if not user.profile.multiple_login: cached_token = cache.get(cache_key, None) if cached_token is None: raise AuthenticationFailed(self.error_messages["invalid_token"]) else: cached_token.blacklist() # Generate new token token = SlidingToken.for_user(user) user_serializer = UserTokenSerializer(instance=user) token["user"] = user_serializer.data # Set new token in cache if multiple login flag is active if not user.profile.multiple_login: cache.set(cache_key, token, timeout=token.lifetime.total_seconds()) return {"token": str(token)}
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/api/serializers/token.py
token.py
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 27/04/23 6:57 # Project: Zibanu - Django # Module Name: user # Description: Set of serializers for user entity # **************************************************************** from .profile import ProfileSerializer from django.conf import settings from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import ValidationError from zibanu.django.auth.models import UserProfile class UserSerializer(serializers.ModelSerializer): """ Serializer class for Django user entity, including user profile, permissions and roles (groups). """ full_name = serializers.SerializerMethodField(default="Guest") profile = ProfileSerializer(required=True, read_only=False) roles = serializers.SerializerMethodField(default=[]) permissions = serializers.SerializerMethodField(default=[]) def get_permissions(self, instance) -> list: """ Method to get permission list from User object. Parameters ---------- instance: User object instance Returns ------- permissions: Permission list """ permissions = [] if self.context.get("load_permissions", settings.ZB_AUTH_INCLUDE_PERMISSIONS): for permission in instance.user_permissions.all(): permissions.append(permission.name) return permissions def get_roles(self, instance) -> list: """ Method to get groups list from User object Parameters ---------- instance: User object instance Returns ------- groups: Group list """ roles = [] if self.context.get("load_roles", settings.ZB_AUTH_INCLUDE_GROUPS): for group in instance.groups.all(): roles.append(group.name) return roles def get_full_name(self, instance) -> str: """ Method to get full name from user object instance Parameters ---------- instance: User object instance Returns ------- full_name: String with user full name """ return instance.get_full_name() def create(self, validated_data) -> object: """ Create a user object including its user profile. Parameters ---------- validated_data: Validated data dictionary from serializer Returns ------- use_object: User object created if successfully """ email = validated_data.pop("email") user_object = self.Meta.model.objects.filter(email__exact=email).first() if user_object is None: if "password" not in validated_data.keys(): raise ValidationError(_("The password is required."), "create_user") password = validated_data.pop("password") username = validated_data.pop("username") profile_data = validated_data.pop("profile") user_object = self.Meta.model.objects.create_user(username=username, email=email, password=password, **validated_data) # Create profile user_profile = UserProfile(user=user_object, **profile_data) user_profile.save() else: raise ValidationError(_("Email is already registered in our database.")) return user_object class Meta: """ UserSerializer metaclass """ model = get_user_model() fields = ("email", "full_name", "last_login", "is_staff", "is_superuser", "is_active", "profile", "roles", "first_name", "last_name", "permissions", "username", "password") class UserListSerializer(serializers.ModelSerializer): """ User entity list serializer """ full_name = serializers.SerializerMethodField(default="Guest") class Meta: """ UserListSerializer metaclass """ fields = ("full_name", "email", "last_login", "username", "is_staff", "is_superuser") model = get_user_model() def get_full_name(self, instance) -> str: """ Method to get full name from user object instance Parameters ---------- instance: User object instance Returns ------- full_name: String with user full name """ return instance.get_full_name() class UserTokenSerializer(UserSerializer): """ Class inherited from UserSerializer to only use in the TokenSerializer for the authentication process. """ class Meta: model = get_user_model() fields = ("email", "is_staff", "is_superuser", "username", "profile", "roles", "permissions")
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/api/serializers/user.py
user.py
import smtplib from django.apps import apps from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from django.core.cache import cache from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError as CoreValidationError from django.db.models import ProtectedError from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy as _ from rest_framework import status from rest_framework.permissions import AllowAny from rest_framework.response import Response from zibanu.django.auth.api import serializers from zibanu.django.auth.lib.signals import on_change_password, on_request_password from zibanu.django.auth.lib.utils import get_user, get_cache_key from zibanu.django.utils import get_user from zibanu.django.utils import Email from zibanu.django.utils import ErrorMessages from zibanu.django.utils import CodeGenerator from zibanu.django.rest_framework.exceptions import APIException from zibanu.django.rest_framework.exceptions import ValidationError from zibanu.django.rest_framework.decorators import permission_required from zibanu.django.rest_framework.viewsets import ModelViewSet, ViewSet class UserService(ModelViewSet): """ Set of REST Services for django User model """ model = get_user_model() serializer_class = serializers.UserListSerializer request_password_template = settings.ZB_AUTH_REQUEST_PASSWORD_TEMPLATE change_password_template = settings.ZB_AUTH_CHANGE_PASSWORD_TEMPLATE def __send_mail(self, subject: str, to: list, template: str, context: dict) -> None: """ Private method to send mail Parameters ---------- subject to template context Returns ------- """ try: email = Email(subject=subject, to=to, context=context) email.set_text_template(template=template) email.set_html_template(template=template) email.send() except smtplib.SMTPException: pass def get_permissions(self): """ Override method to get permissions for allow on_request_password action. Returns ------- response: Response object with HTTP status (200 if success) and list of permissions dataset. """ if self.action == "request_password": permission_classes = [AllowAny] else: permission_classes = self.permission_classes.copy() return [permission() for permission in permission_classes] @method_decorator(permission_required("auth.view_user")) def list(self, request, *args, **kwargs) -> Response: """ REST service to get list of users. Add a filter to get only active users. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status (200 if success) and list of users dataset. """ kwargs = dict({"order_by": "first_name", "is_active__exact": True}) return super().list(request, *args, **kwargs) @method_decorator(permission_required(["auth.add_user", "zb_auth.add_userprofile"])) def create(self, request, *args, **kwargs) -> Response: """ REST service to create user with its profile. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status (200 if success). """ try: if request.data is not None and len(request.data) > 0: roles_data = request.data.pop("groups", []) permissions_data = request.data.pop("permissions", []) try: transaction.set_autocommit(False) serializer = serializers.UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): created_user = serializer.create(validated_data=serializer.validated_data) if created_user is not None: if len(roles_data) > 0: # If user has roles to add created_user.groups.set(roles_data) if len(permissions_data) > 0: # If user has permissions to add created_user.user_permissiones.set(permissions_data) data_return = self.get_serializer(created_user).data except ValidationError: transaction.rollback() raise except CoreValidationError: transaction.rollback() raise except Exception as exc: transaction.rollback() raise APIException(ErrorMessages.NOT_CONTROLLED, str(exc), status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: transaction.commit() finally: transaction.set_autocommit(True) else: raise ValidationError(ErrorMessages.DATA_REQUEST_NOT_FOUND, "data_request_error") except ValidationError as exc: if isinstance(exc.detail, dict): if "profile" in exc.detail: message = exc.detail["profile"]["avatar"][0] else: message = str(exc) else: message = exc.detail[0] raise APIException(msg=message, error="add_user", http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except CoreValidationError as exc: raise APIException(msg=exc.message, error=exc.code, http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc else: return Response(status=status.HTTP_201_CREATED) @method_decorator(permission_required(["auth.change_user", "zb_auth.change_userprofile"])) def update(self, request, *args, **kwargs) -> Response: """ REST service to update user, including profile, groups and permissions. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status (200 if success). """ try: if "email" in request.data: try: try: transaction.set_autocommit(False) user = self.model.objects.get(email__exact=request.data.get("email")) if "first_name" in request.data: user.first_name = request.data.get("first_name") if "last_name" in request.data: user.last_name = request.data.get("last_name") if "is_staff" in request.data: user.is_staff = request.data.get("is_staff") if "is_active" in request.data: user.is_active = request.data.get("is_active") if "profile" in request.data: user.profile.set(request.data.get("profile")) if "groups" in request.data: user.groups.set(request.data.get("groups")) if "permissions" in request.data: user.user_permissions.set(request.data.get("permissions")) user.save() except ObjectDoesNotExist as exc: raise APIException(msg=ErrorMessages.NOT_FOUND, error="user_not_exists", http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except Exception as exc: transaction.rollback() raise APIException(msg=ErrorMessages.NOT_CONTROLLED, error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: transaction.commit() finally: transaction.set_autocommit(True) except self.model.DoesNotExist as exc: raise ValidationError(_("User does not exists."), "user_not_exists") else: raise ValidationError(ErrorMessages.DATA_REQUEST_NOT_FOUND, "data_request_error") except ValidationError as exc: raise APIException(msg=exc.detail[0], error=exc.detail[0].code, http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc else: return Response(status=status.HTTP_200_OK) @method_decorator(permission_required(["auth.delete_user", "zb_auth.delete_userprofile"])) def destroy(self, request, *args, **kwargs) -> Response: """ REST service to delete one user object. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status (200 if success). """ try: if "email" in request.data: request_user = get_user(request.user) user = self.model.objects.get(email__exact=request.data.get("email")) if user.email != request_user.email: user.delete() else: raise ValidationError(_("Cannot delete yourself."), "delete_user_error") else: raise ValidationError(ErrorMessages.DATA_REQUEST_NOT_FOUND, "data_request_error") except ObjectDoesNotExist as exc: raise APIException(msg=ErrorMessages.NOT_FOUND, error="user_not_exists", http_status=status.HTTP_404_NOT_FOUND) from exc except ProtectedError as exc: raise APIException(msg=_("User has protected child records. Cannot delete."), error="delete_user_error", http_status=status.HTTP_403_FORBIDDEN) from exc except ValidationError as exc: raise APIException(msg=exc.detail[0], error=exc.detail[0].code, http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except Exception as exc: raise APIException(msg=str(exc), error="not_controlled_exception", http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(status=status.HTTP_200_OK) def change_password(self, request, *args, **kwargs) -> Response: """ REST service to change the user's password. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status (200 if success). """ try: user = get_user(request.user) if {"old_password", "new_password"} <= request.data.keys(): if user.check_password(request.data.get("old_password")): user.set_password(request.data.get("new_password")) user.save() context = { "user": user } if apps.is_installed("zibanu.django"): self.__send_mail(subject=_("Password change"), to=[user.email], template=self.change_password_template, context=context) on_change_password.send(sender=self.__class__, user=user, request=request) else: raise ValidationError(_("Old password does not match.")) else: raise ValidationError(_("Old/New password are required.")) except ValidationError as exc: raise APIException(msg=exc.detail[0], error="validation_error", http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(status=status.HTTP_200_OK) def request_password(self, request, *args, **kwargs) -> Response: """ REST service to request password and send through email. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status (200 if success). """ try: if "email" in request.data: user = get_user_model().objects.filter(email__exact=request.data.get("email")).first() if hasattr(user, "profile"): secure_password = user.profile.secure_password else: secure_password = False if user is not None: code_gen = CodeGenerator(action="on_request_password", code_length=12) if secure_password: new_password = code_gen.get_secure_code() else: new_password = code_gen.get_alpha_numeric_code() user.set_password(new_password) user.save() context = { "user": user, "new_password": new_password } if apps.is_installed("zibanu.django"): self.__send_mail(subject=_("Request password."), to=[user.email], template=self.request_password_template, context=context) on_request_password.send(sender=self.__class__, user=user, request=request) else: raise ValidationError(_("Email is not registered.")) else: raise ValidationError(ErrorMessages.DATA_REQUEST_NOT_FOUND) except ValidationError as exc: raise APIException(msg=exc.detail[0], error="validation_error", http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(status=status.HTTP_200_OK) class LogoutUser(ViewSet): """ ViewSet to perform logout actions and remove cached tokens. """ def logout(self, request, *args, **kwargs) -> Response: user = get_user(request.user) if not user.profile.multiple_login: cache_key = get_cache_key(request, user) token = cache.get(cache_key, None) if token is not None: token.blacklist() cache.delete(cache_key) return Response(status=status.HTTP_200_OK)
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/api/services/user.py
user.py
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 19/06/23 14:29 # Project: Zibanu - Django # Module Name: profile # Description: # **************************************************************** from django.core.exceptions import ValidationError as CoreValidationError from rest_framework import status from rest_framework.response import Response from zibanu.django.auth.api.serializers import ProfileSerializer from zibanu.django.auth.models import UserProfile from zibanu.django.rest_framework.exceptions import ValidationError, APIException from zibanu.django.rest_framework.viewsets import ModelViewSet from zibanu.django.utils.error_messages import ErrorMessages from zibanu.django.utils.user import get_user class ProfileService(ModelViewSet): """ Set of REST services for UserProfile model """ model = UserProfile serializer_class = ProfileSerializer def update(self, request, *args, **kwargs) -> Response: """ REST service to update UserProfile model Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of parameters Returns ------- response: Response object with HTTP status. 200 if success. """ try: if request.data is not None: user = get_user(request.user) if hasattr(user, "profile"): user.profile.set(fields=request.data) else: raise ValidationError(ErrorMessages.NOT_FOUND, "user_profile_not_found") else: raise ValidationError(ErrorMessages.DATA_REQUEST_NOT_FOUND, "data_request_error") except ValidationError as exc: raise APIException(msg=exc.detail[0], error=exc.detail[0].code, http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except CoreValidationError as exc: raise APIException(msg=exc.message, error=exc.code, http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except Exception as exc: raise APIException(msg=str(exc), error="not_controlled_exception", http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(status=status.HTTP_200_OK)
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/api/services/profile.py
profile.py
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 13/05/23 11:59 # Project: Zibanu - Django # Module Name: signals # Description: # **************************************************************** """ Signal definitions for associate to events """ from django import dispatch from django.apps import apps from django.contrib.auth.signals import user_logged_in, user_login_failed from django.dispatch import receiver from typing import Any from zibanu.django.utils import get_ip_address on_change_password = dispatch.Signal() on_request_password = dispatch.Signal() @receiver(on_change_password, dispatch_uid="on_change_password") @receiver(on_request_password, dispatch_uid="on_request_password") @receiver(user_logged_in, dispatch_uid="on_user_logged_in") @receiver(user_login_failed, dispatch_uid="on_user_login_failed") def auth_event(sender: Any, user: Any = None, **kwargs) -> None: """ Signal for change password or request password events Parameters ---------- sender: Sender class of signal user: User object to get data kwargs: Dictionary with fields and parametes Returns ------- None """ # Set detail field detail = kwargs.get("detail", "") if kwargs.get("credentials", None) is not None: detail = kwargs.get("credentials").get("username", "") if isinstance(sender, str): class_name = sender else: class_name = sender.__name__ ip_address = get_ip_address(kwargs.get("request", None)) # Try to capture receiver name from receivers pool. try: receivers = kwargs.get("signal").receivers receiver_id = receivers[len(receivers)-1][0][0] if isinstance(receiver_id, str): action = receiver_id else: action = "zb_auth_event" # If username context var exists. except: action = "zb_auth_event" if apps.is_installed("zibanu.django.logging"): from zibanu.django.logging.models import Log log = Log(user=user, sender=class_name, action=action, ip_address=ip_address, detail=detail) log.save()
zibanu-django-auth
/zibanu-django-auth-1.1.0.tar.gz/zibanu-django-auth-1.1.0/zibanu/django/auth/lib/signals.py
signals.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2022. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2022. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 10/12/22 10:27 AM # Project: Zibanu Django Project # Module Name: models # Description: # **************************************************************** from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as _ from zibanu.django.db import models class Log(models.DatedModel): action = models.CharField(max_length=100, blank=False, null=False, verbose_name=_("Action")) sender = models.CharField(max_length=100, blank=False, null=False, verbose_name=_("Sender object method")) detail = models.CharField(max_length=200, blank=True, null=False, default="", verbose_name=_("Log detail")) ip_address = models.GenericIPAddressField(blank=True, null=True, verbose_name=_("IP Address")) user = models.ForeignKey(get_user_model(), null=True, blank=False, verbose_name=_("User"), on_delete=models.CASCADE) class Meta: indexes = [ models.Index(fields=("user", ), name="IDX_logging_log_user"), models.Index(fields=("action", ), name="IDX_logging_log_action") ] class MailLog(models.Model): log = models.OneToOneField(Log, blank=False, null=False, on_delete=models.PROTECT, verbose_name=_("Log")) mail_from = models.CharField(max_length=250, blank=False, null=False, verbose_name=_("Mail From")) mail_to = models.CharField(max_length=250, blank=False, null=False, verbose_name=_("Mail To")) subject = models.CharField(max_length=250, blank=False, null=False, verbose_name=_("Subject")) smtp_code = models.IntegerField(blank=False, null=False, verbose_name=_("SMTP Code"), default=0) smtp_error = models.CharField(max_length=250, blank=False, null=True, verbose_name=_("SMTP Error"))
zibanu-django-logging
/zibanu_django_logging-1.1.0-py3-none-any.whl/zibanu/django/logging/models.py
models.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2023. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2023. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 2/02/23 16:27 # Project: Zibanu Django Project # Module Name: document_generator # Description: # **************************************************************** import os import uuid from datetime import date, datetime from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError from django.template.exceptions import TemplateDoesNotExist from django.template.exceptions import TemplateSyntaxError from django.template.loader import get_template from django.utils.translation import gettext_lazy as _ from xhtml2pdf import pisa from zibanu.django.db.models import QuerySet from zibanu.django.utils import CodeGenerator from zibanu.django.repository.models import Document class DocumentGenerator: """ Class to generate a new document PDF document from django template definition. """ def __init__(self, template_prefix: str, custom_dir: str = None, file_uuid: str = None) -> None: """ Class constructor Parameters ---------- template_prefix: Path template prefix custom_dir: Custom dir for save pdf document file_uuid: UUID to assign to the document. """ self.__custom_dir = custom_dir self.__template_prefix = template_prefix self.__description = "" self.__generated = None if not template_prefix.endswith("/"): self.__template_prefix += "/" if template_prefix.startswith("/"): self.__template_prefix = self.__template_prefix[1:] if hasattr(settings, "MEDIA_ROOT"): self.__directory = self.__get_directory() else: raise ValueError(_("The 'MEDIA_ROOT' setting has not been defined.")) @property def description(self) -> str: """ Property with document's description. Returns ------- description: String with document's description. """ return self.__description @property def generated_at(self) -> datetime: """ Property to get the field "generated_at" from document. Returns ------- generated_at: DateTime value from document's generated_at field. """ return self.__generated def __get_directory(self, **kwargs) -> str: """ Private method to get the full path from document, year and month parameters in **kwargs Parameters ---------- **kwargs: Dictionary with parameters. The valid parameters are, document, year and month. Returns ------- path: String with representative path. """ year = date.today().year month = date.today().month if hasattr(settings, "MEDIA_ROOT"): if self.__custom_dir is None: directory = os.path.join(settings.MEDIA_ROOT, settings.ZB_REPOSITORY_DIRECTORY) else: directory = os.path.join(settings.MEDIA_ROOT, self.__custom_dir) else: raise ValueError(_("The 'MEDIA_ROOT' setting has not been defined.")) if kwargs is not None: if "document" in kwargs and isinstance(kwargs.get("document"), Document): document = kwargs.get("document") year = document.generated_at.year month = document.generated_at.month elif {"year", "month"} <= kwargs.keys(): year = kwargs.get("year") month = kwargs.get("month") directory = os.path.join(directory, str(year)) directory = os.path.join(directory, str(month)) return directory def __get_qs(self, kwargs) -> QuerySet: """ Private method to construct a query set filtered by uuid or code. Parameters ---------- **kwargs: Dictionary with keys uuid or code for construct the filter. Returns ------- queryset: Queryset from document model """ if "uuid" in kwargs: document_qs = Document.objects.get_by_uuid(kwargs.get("uuid")) elif "code" in kwargs: document_qs = Document.objects.get_by_code(kwargs.get("code")) else: raise ValueError(_("Key to get document does not found.")) return document_qs def generate_from_template(self, template_name: str, context: dict, **kwargs) -> str: """ Method to generate a document from django template. Parameters ---------- template_name: Template name to construct the pdf document. context: Context dictionary to override context constructor. **kwargs: Dictionary with vars to template like "description", "request", "key" and "user". User is mandatory. Returns ------- hex: String with hex uuid from generated document. """ try: # Load vars from kwargs description = kwargs.get("description", "") request = kwargs.get("request", None) key = kwargs.get("key", "code") if request is None: user = kwargs.get("user") if user is None: raise ValueError(_("Request or user are required")) else: user = request.user # Created directory if it does not exist directory = self.__get_directory() if not os.path.exists(directory): os.makedirs(directory) # Get validation code from key or create it # Modified by macercha at 2023/06/03 if key in context: validation_code = context.get(key) else: code_generator = CodeGenerator(action="rep_doc_generator") validation_code = code_generator.get_alpha_numeric_code(length=10) # Set uuid for filename and uuid file file_uuid = uuid.uuid4() # Set filename with path and uuid and create it file_name = os.path.join(self.__get_directory(), file_uuid.hex + ".pdf") #TODO: Validate template name # Load template and render it template_name = self.__template_prefix + template_name template = get_template(template_name) rendered = template.render(context=context, request=request) # Generate pdf file_handler = open(file_name, "w+b") pisa_status = pisa.CreatePDF(rendered, file_handler) if not pisa_status.err: document = Document(code=validation_code, uuid=file_uuid, owner=user, description=description) document.save() file_handler.close() else: file_handler.close() os.remove(file_name) raise Exception(_("Error generating pdf file")) except OSError: raise OSError(_("The file cannot be created.")) except TemplateDoesNotExist: raise TemplateDoesNotExist(_("Template %s does not exist." % template_name)) except TemplateSyntaxError: raise TemplateSyntaxError(_("Syntax error in the template %s") % template_name) else: return file_uuid.hex def get_file(self, user, **kwargs) -> str: """ Get a file pathname of document filtering from user (mandatory) and uuid or code values. Parameters ---------- user: User object to get the document. **kwargs: Dictionary with "uuid" or "code" keys to get the right document. Returns ------- path_filename: Document path filename """ if user is None: raise ValueError(_("User is required")) document_qs = self.__get_qs(kwargs) if document_qs.count() > 0: document = document_qs.first() self.__description = document.description self.__generated = document.generated_at if user == document.owner: path_filename = os.path.join(self.__get_directory(document=document), document.uuid.hex + '.pdf') if not os.path.exists(path_filename): raise ObjectDoesNotExist(_("Document file does not exist.")) else: raise ValidationError(_("User does not have permissions to get this document.")) else: raise ObjectDoesNotExist(_("Document does not exist.")) return path_filename def get_document(self, **kwargs) -> Document: """ Get a document from defined filters in **kwargs Parameters ---------- **kwargs: Dictionary with keys and values for filter construct. Returns ------- document: Document object that matches the filter. """ return self.__get_qs(kwargs).first()
zibanu-django-repository
/zibanu_django_repository-1.0.1-py3-none-any.whl/zibanu/django/repository/lib/utils/document_generator.py
document_generator.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2023. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2023. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 28/01/23 15:33 # Project: Zibanu Django Project # Module Name: static_uri # Description: # **************************************************************** from django import template from django.conf import settings from django.utils.translation import gettext_lazy as _ register = template.Library() class StaticNodeUri(template.Node): """ Inherited class from django.template.Node to allow the use of template tag "static_uri" in django templates. """ def __init__(self, uri_string: str): """ Constructor method. Parameters ---------- uri_string : URI string received from template """ self._static_uri = uri_string def render(self, context): """ Override method to render the tag in template. Parameters ---------- context : Context dictionary object from template Returns ------- uri: String to render in template """ if hasattr(context, "request"): request = context.get("request") if hasattr(settings, "STATIC_URL"): uri = request.build_absolute_uri(settings.STATIC_URL) uri = uri + self._static_uri else: raise template.TemplateSyntaxError(_("'STATIC_URL' setting is not defined.")) else: raise template.TemplateSyntaxError(_("Tag 'static_uri' requires 'request' var in context.")) return uri @register.tag("static_uri") def static_uri(parse, token): """ Function to register tag in template Parameters ---------- parse : Parse object from template token : Token object from template Returns ------- StaticNodeUri class to be called from template and render it. """ try: tag_name, uri_string = token.split_contents() except ValueError: raise template.TemplateSyntaxError("") return StaticNodeUri(uri_string[1:-1])
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/template/templatetags/static_uri.py
static_uri.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2023. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2023. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 16/02/23 9:03 # Project: Zibanu Django Project # Module Name: subtotal_dict # Description: # **************************************************************** from django import template from django.utils.translation import gettext_lazy as _ register = template.Library() @register.simple_tag def subtotal_dict(source_list: list, key_control: str, *args) -> list: """ Template tag to get a subtotal from a list of dictionary records. Parameters ---------- source_list : List with all data dictionary. key_control : Key use to index and make the breaks for subtotals. args : Tuple with list of key names to get the subtotals. Returns ------- return_list: List with a data dictionary with the keys "control", "totals" and data", which contains the subtotals like this: control -> Value from source_list for key_control key. totals -> Total for key_control data -> list with data from source_list with a key different from key_control param value. """ if args is not None: key_value = None return_list = [] item_dict = { "control": None, "totals": dict(), "data": [] } for record in source_list: data_dict = dict() if key_value is None or key_value != record[key_control]: # Add Control var and dict if key_value is not None: return_list.append(item_dict) key_value = record[key_control] # Init vars on change key_value item_dict = { "control": record[key_control], "totals": dict(), "data": [] } for param in args: item_dict["totals"][param] = 0 for key_item in record.keys(): if key_item != key_control: data_dict[key_item] = record.get(key_item) if key_item in item_dict.get("totals").keys(): item_dict["totals"][key_item] += record[key_item] item_dict["data"].append(data_dict) return_list.append(item_dict) else: raise template.TemplateSyntaxError(_("The keys for subtotals are required.")) return return_list
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/template/templatetags/subtotal_dict.py
subtotal_dict.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2023. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2023. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 10/01/23 1:47 PM # Project: Zibanu Django Project # Module Name: code_generator # Description: # **************************************************************** import os import string import secrets from django.utils.translation import gettext_lazy as _ from uuid import SafeUUID, UUID class CodeGenerator: """ Class to generate different types of codes randomly. """ def __init__(self, action: str, is_safe: bool = True, code_length: int = 6): """ Constructor method Parameters ---------- action : Code of action to reference it at cache if needed. is_safe : Flag to indicate if it uses UUID safe mode. code_length : Length of generated code """ self.__action = action self._uuid_safe = SafeUUID.safe if is_safe else SafeUUID.unsafe self.__code_length = code_length self.__code = None self.__uuid = None @property def is_safe(self): """ Property getter for _uuid_safe value Returns ------- Boolean value: True if UUID uses safe mode, otherwise False """ return self._uuid_safe == SafeUUID.safe @is_safe.setter def is_safe(self, value: bool): """ Property setter for _uuid_safe value Parameters ---------- value : Boolean parameter to set SafeUUID.safe if True, else set SafeUUID.unsafe """ self._uuid_safe = SafeUUID.safe if value else SafeUUID.unsafe @property def code(self) -> str: """ Property getter for __code value Returns ------- String value with generated code """ return self.__code @property def action(self) -> str: """ Property getter for __action value Returns ------- String value with action description """ return self.__action def get_numeric_code(self, length: int = None) -> str: """ Get a numeric code with the length defined in the constructor or received in the parameter "length" of this method. Parameters ---------- length : Length of generated code. Override length defined in the class. Returns ------- String with numeric code """ if length is not None: self.__code_length = length self.__code = "".join(secrets.choice(string.digits) for i in range(self.__code_length)) return self.code def get_alpha_numeric_code(self, length: int = None) -> str: """ Get an alphanumeric code with the length defined in the constructor or received in the parameter "length" of this method. Parameters ---------- length : Length of generated code. This parameter override length defined in the class. Returns ------- String with numeric code """ if length is not None: self.__code_length = length self.__code = "".join(secrets.choice(string.digits + string.ascii_letters) for i in range(self.__code_length)) return self.code def get_secure_code(self, length: int = None) -> str: """ Get a secure code with the length defined in the constructor or received in the parameter "length" of this method. Parameters ---------- length : Length of generated code. This parameter override length defined in the class. Returns ------- String with numeric code """ if length is not None: self.__code_length = length self.__code = "".join(secrets.choice(string.digits + string.ascii_letters + string.punctuation) for i in range(self.__code_length)) return self.code def generate_uuid(self) -> bool: """ Method to generate a UUID in safe mode, depending on the parameter set in the constructor Returns ------- True if successfully, otherwise False. """ try: self.__uuid = UUID(bytes=os.urandom(16), version=4, is_safe=self._uuid_safe) except Exception: return False else: return True def generate_dict(self, is_numeric: bool = True) -> dict: """ Method to generate a dictionary with uuid, code and action. Parameters ---------- is_numeric : Flag to indicate if generated code is numeric or alphanumeric. Returns ------- Dictionary with uuid, code and action keys. """ if is_numeric: self.get_numeric_code() else: self.get_alpha_numeric_code() if self.generate_uuid(): return {"uuid": self.__uuid, "code": self.code, "action": self.action} else: raise ValueError(_("The generated values are invalid."))
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/utils/code_generator.py
code_generator.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2022. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2022. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 20/12/22 2:35 PM # Project: Zibanu Django Project # Module Name: mail # Description: # **************************************************************** import smtplib from django.apps import apps from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.template.exceptions import TemplateSyntaxError from django.template.exceptions import TemplateDoesNotExist from django.template.loader import get_template from django.utils import timezone from django.utils.translation import gettext_lazy as _ from typing import Any from uuid import uuid4 class Email(EmailMultiAlternatives): """ Inherited EmailMultiAlternatives class for create an email from html template and html text. """ def __init__(self, subject: str = "", body: str = "", from_email: str = None, to: list = None, bcc: list = None, connection: Any = None, attachments: list = None, headers: dict = None, cc: list = None, reply_to: list = None, context: dict = None): """ Class constructor to override and delegate super constructor class setting some auxiliary attributes. Parameters ---------- subject : Subject for email. body : Body text for email. from_email : From email address to : List or tuple of recipient addresses. bcc : A list or tuple of addresses used in the “Bcc” header when sending the email. connection : Email backend connection instance. attachments : List of attachment files. headers : A dictionary of extra headers to put on the message. The keys are the header name, values are the header values. cc : A list or tuple of recipient address used in the "Cc" header when sending the email. reply_to : A list or tuple of recipient addresses used in the "Reply-To" header when sending the email. context : Context dictionary for some extra vars. """ # Define message id for unique id self.__text_content = None self.__html_content = None self.__message_id = uuid4().hex self.__context = context # Set default values from_email = from_email if from_email is not None else settings.ZB_MAIL_DEFAULT_FROM reply_to = reply_to if reply_to is not None else [settings.ZB_MAIL_REPLY_TO] # Analyze errors cc = cc if cc is not None else [] if headers is None: headers = { "Message-ID": self.__message_id } else: headers["Message-ID"] = self.__message_id super().__init__(subject=subject, body=body, from_email=from_email, to=to, bcc=bcc, connection=connection, attachments=attachments, headers=headers, cc=cc, reply_to=reply_to) def __get_template_content(self, template: str, context: dict = None) -> Any: """ Return template content after render with context values if exists. Parameters ---------- template : Full path and file name of template. context : Context dictionary with extra values. Returns ------- template_content: String with rendered template. """ try: if context is None: context = dict() if "email_datetime" not in context: context["email_datetime"] = timezone.now().astimezone(tz=timezone.get_default_timezone()).strftime( "%Y-%m-%d %H:%M:%S") if "email_id" not in context: context["email_id"] = str(uuid4()) template = get_template(template_name=template) template_content = template.render(context) except TemplateSyntaxError: raise TemplateSyntaxError(_("Syntax error loading template '{}'").format(template)) except TemplateDoesNotExist: raise TemplateDoesNotExist(_("Template '{}' does not exist.").format(template)) else: return template_content def set_text_template(self, template: str, context: dict = None): """ Set a text template for body email. Parameters ---------- template : Full path and file name of template. context : Context dictionary with extra vars. """ if not template.lower().endswith(".txt"): template = template + ".txt" if context is not None: self.__context = context self.body = self.__get_template_content(template=template, context=self.__context) def set_html_template(self, template: str, context: dict = None): """ Set html template for body email construction. Parameters ---------- template : Full path and file name of template. context : Context dictionary with extra vars. """ if not template.lower().endswith(".html"): template = template+ ".html" if context is not None: self.__context = context self.attach_alternative(self.__get_template_content(template=template, context=self.__context), "text/html") def send(self, fail_silently=False): """ Override method to send email message. Parameters ---------- fail_silently : Flag to determine if an error is caught or not """ smtp_code = 0 smtp_error = None try: super().send(fail_silently=fail_silently) except smtplib.SMTPResponseException as exc: smtp_code = exc.smtp_code smtp_error = exc.smtp_error except smtplib.SMTPException as exc: smtp_code = exc.errno smtp_error = exc.strerror except ConnectionRefusedError as exc: smtp_code = exc.errno smtp_error = exc.strerror finally: # Send signal if zibanu.django.logging is installed. if apps.is_installed("zibanu.django.logging"): from zibanu.django.logging.lib.signals import send_mail send_mail.send(sender=self.__class__, mail_from=self.from_email, mail_to=self.to, subject=self.subject, smtp_error=smtp_error, smtp_code=smtp_code) if smtp_code != 0: raise smtplib.SMTPException(_("Error sending email."))
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/utils/mail.py
mail.py
# **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 27/04/23 9:57 # Project: Zibanu - Django # Module Name: decorators # Description: # **************************************************************** from django.contrib.auth.decorators import user_passes_test from django.core.exceptions import PermissionDenied from django.utils.translation import gettext_lazy as _ from typing import Any from zibanu.django.utils import get_user_object def permission_required(permissions: Any, raise_exception=True): """ Decorator to validate permissions from django auth structure. SimpleJWT compatible. Parameters ---------- permissions: permission name or tuple with permissions list. Mandatory raise_exception: True if you want to raise PermissionDenied exception, otherwise False. Default: True Returns ------- b_return: True if successfully authorized, otherwise False. """ def check_perms(user): """ Internal function to check permission from master function Parameters ---------- user: User object to validate. Returns ------- b_return: True if permissions check success, otherwise False. """ b_return = False is_staff = False local_user = get_user_object(user) # Build perms list if permissions is not None: if isinstance(permissions, str): perms = (permissions,) else: perms = permissions else: raise ValueError(_("Permission name or tuple is required.")) if "is_staff" in perms: is_staff = True perms = tuple([perm for perm in perms if perm != "is_staff"]) if (len(perms) > 0 and local_user.has_perms(perms)) or (is_staff and local_user.is_staff) or local_user.is_superuser: b_return = True elif raise_exception: raise PermissionDenied(_("You do not have permission to perform this action."), "not_authorized") return b_return return user_passes_test(check_perms)
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/rest_framework/decorators.py
decorators.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2022. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2022. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 19/12/22 3:18 PM # Project: Zibanu Django Project # Module Name: model_viewset # Description: # **************************************************************** import logging from django.db import DatabaseError from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from rest_framework import authentication from rest_framework import permissions from rest_framework import status from rest_framework.generics import QuerySet from rest_framework.viewsets import ModelViewSet as RestModelViewSet from rest_framework.response import Response from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication from zibanu.django.rest_framework.exceptions import APIException from zibanu.django.rest_framework.exceptions import ValidationError from zibanu.django.utils import ErrorMessages from typing import Any class ModelViewSet(RestModelViewSet): """ Inherited class from rest_framework.viewsets.ModelViewSet to override """ logger = logging.getLogger(__name__) model = None http_method_names = ["post"] permission_classes = [permissions.IsAuthenticated] authentication_classes = [JWTTokenUserAuthentication] if settings.DEBUG: authentication_classes.append(authentication.TokenAuthentication) @staticmethod def _get_pk(request) -> Any: """ Get PK value from received request data dictionary. Parameters ---------- request: Request object from HTTP Returns ------- pk_value: Value obtained from request.data """ if request.data is not None: if "pk" in request.data.keys(): pk_value = request.data.get("pk", None) elif "id" in request.data.keys(): pk_value = request.data.get("id", None) else: raise APIException(ErrorMessages.DATA_REQUIRED, "get_pk", status.HTTP_406_NOT_ACCEPTABLE) else: raise APIException(ErrorMessages.DATA_REQUIRED, "get_pk", status.HTTP_406_NOT_ACCEPTABLE) return pk_value def get_queryset(self, **kwargs) -> QuerySet: """ Get a queryset from model from **kwargs parameters. If you want queryset pk based on, send "pk" key in kwargs. Parameters ---------- **kwargs: Dictionary with key, value parameters. Returns ------- qs: Queryset object from model """ pk = kwargs.get("pk", None) qs = self.model.objects.get_queryset() if pk is not None: qs = qs.filter(pk=pk) elif len(kwargs) > 0: qs = qs.filter(**kwargs) else: qs = qs.all() return qs def list(self, request, *args, **kwargs) -> Response: """ REST service to get a list of records from class defined model. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters **kwargs: Dictionary of key, value parameters. Returns ------- response: Response object with status and dataset list. status -> 200 if data exists status -> 204 if empty data """ try: # Get Order by order_by = None if "order_by" in kwargs.keys(): order_by = kwargs.pop("order_by") qs = self.get_queryset(**kwargs) # Set Order by if order_by is not None: qs = qs.order_by(order_by) serializer = self.get_serializer(instance=qs, many=True) data_return = serializer.data status_return = status.HTTP_200_OK if len(data_return) > 0 else status.HTTP_204_NO_CONTENT data_return = data_return except APIException as exc: raise APIException(msg=exc.detail.get("message"), error=exc.detail.get("detail"), http_status=exc.status_code) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(data=data_return, status=status_return) def retrieve(self, request, *args, **kwargs) -> Response: """ REST service to get a record filtered by pk. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters values **kwargs: Dictionary with key, value parameter Returns ------- response: Response object with status 200 if record exists and data record. If record does not exist, an exception is launched. """ try: pk = self._get_pk(request) data_record = self.get_queryset(pk=pk).get() data_return = self.get_serializer(data_record).data status_return = status.HTTP_200_OK except ObjectDoesNotExist as exc: raise APIException(ErrorMessages.NOT_FOUND, str(exc), http_status=status.HTTP_404_NOT_FOUND) from exc except APIException as exc: raise APIException(exc.detail.get("message"), exc.detail.get("detail"), exc.status_code) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(status=status_return, data=data_return) def create(self, request, *args, **kwargs) -> Response: """ REST service for create a model record. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters values **kwargs: Dictionary with key, value parameter Returns ------- response: Response object with status 201 if successfully and record created from model object. """ try: data_return = [] status_return = status.HTTP_400_BAD_REQUEST request_data = request.data if len(request_data) > 0: serializer = self.get_serializer(data=request_data) if serializer.is_valid(raise_exception=True): created_record = serializer.create(validated_data=serializer.validated_data) if created_record is not None: data_return = self.get_serializer(created_record).data status_return = status.HTTP_201_CREATED else: raise ValidationError(ErrorMessages.CREATE_ERROR, "create_object") else: raise APIException(ErrorMessages.DATA_REQUIRED, "data_required") except DatabaseError as exc: raise APIException(ErrorMessages.DATABASE_ERROR, str(exc)) from exc except ValidationError as exc: raise APIException(error=str(exc.detail[0]), http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except APIException as exc: raise APIException(exc.detail.get("message"), exc.detail.get("detail"), exc.status_code) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(status=status_return, data=data_return) def update(self, request, *args, **kwargs) -> Response: """ REST service to update an existent record from model. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters values **kwargs: Dictionary with key, value parameter Returns ------- response: Response object with status 200 if successfully and record updated from model object. """ try: pk = self._get_pk(request) data_record = self.get_queryset(pk=pk).get() serializer = self.get_serializer(data_record, data=request.data) if serializer.instance and serializer.is_valid(raise_exception=True): updated = serializer.update(instance=serializer.instance, validated_data=serializer.validated_data) if updated is not None: data_return = self.get_serializer(updated).data status_return = status.HTTP_200_OK else: raise APIException(ErrorMessages.UPDATE_ERROR, "update", status.HTTP_418_IM_A_TEAPOT) else: raise APIException(ErrorMessages.NOT_FOUND, "update", status.HTTP_404_NOT_FOUND) except ObjectDoesNotExist as exc: raise APIException(ErrorMessages.NOT_FOUND, "update", status.HTTP_404_NOT_FOUND) from exc except DatabaseError as exc: raise APIException(ErrorMessages.UPDATE_ERROR, str(exc)) from exc except ValidationError as exc: raise APIException(error=str(exc.detail), http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except APIException as exc: raise APIException(exc.detail.get("message"), exc.detail.get("detail"), exc.status_code) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(data=data_return, status=status_return) def destroy(self, request, *args, **kwargs) -> Response: """ REST service to delete a record from model. Parameters ---------- request: Request object from HTTP *args: Tuple of parameters values **kwargs: Dictionary with key, value parameter Returns ------- response: Response object with status 200 if successfully. """ try: pk = self._get_pk(request) data_record = self.get_queryset(pk=pk) if data_record: data_record.delete() status_return = status.HTTP_200_OK else: raise APIException(ErrorMessages.DELETE_ERROR, "delete", status.HTTP_404_NOT_FOUND) except DatabaseError as exc: raise APIException(ErrorMessages.UPDATE_ERROR, str(exc)) from exc except ValidationError as exc: raise APIException(error=str(exc.detail), http_status=status.HTTP_406_NOT_ACCEPTABLE) from exc except APIException as exc: raise APIException(exc.detail.get("message"), exc.detail.get("detail"), exc.status_code) from exc except Exception as exc: raise APIException(error=str(exc), http_status=status.HTTP_500_INTERNAL_SERVER_ERROR) from exc else: return Response(status=status_return)
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/rest_framework/viewsets/model_viewset.py
model_viewset.py
# Developed by CQ Inversiones SAS. Copyright ©. 2019 - 2022. All rights reserved. # Desarrollado por CQ Inversiones SAS. Copyright ©. 2019 - 2022. Todos los derechos reservado # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 14/12/22 4:14 AM # Project: Zibanu Django Project # Module Name: api_exception # Description: # **************************************************************** from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import APIException as SourceException from rest_framework import status class APIException(SourceException): """ Inherited class from rest_framework.exceptions.ApiException """ __default_messages = { "304": _("Object has not been created."), "400": _("Generic error."), "401": _("You are not authorized for this resource."), "403": _("You do not have permission to perform this action."), "404": _("Object does not exists."), "406": _("Data validation error."), "412": _("Data required not found."), "500": _("Not controlled exception error."), } def __init__(self, msg: str = None, error: str = None, http_status: int = status.HTTP_400_BAD_REQUEST) -> None: """ Constructor method Parameters ---------- msg: Message to send trough exception. error: Error code or long description. http_status: HTTP status code """ str_status = str(http_status) # Define default messages if args not passed error = error if error is not None else _("Generic error.") msg = msg if msg is not None else self.__default_messages.get(str_status, _("Generic error.")) # Create detail dictionary detail = { "message": msg, "detail": error } if http_status is not None: self.status_code = http_status super().__init__(detail)
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/rest_framework/exceptions/api_exception.py
api_exception.py
import base64 import io # **************************************************************** # IDE: PyCharm # Developed by: macercha # Date: 12/08/23 17:11 # Project: Zibanu - Django # Module Name: hybrid_image # Description: # **************************************************************** from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from drf_extra_fields.fields import HybridImageField as SourceHybridImageField from drf_extra_fields.fields import Base64FieldMixin, ImageField from typing import Any class HybridImageField(SourceHybridImageField): """ Inherited class from drf_extra_fields.field.HybridImageField to allow size validation and implement the use image format and size validation """ INVALID_FILE_SIZE = _("The width or height of the file is invalid.") def __init__(self, *args: Any, **kwargs: Any) -> None: """ HybridImageField class constructor Parameters ---------- *args: Tuple with parameters values **kwargs: Parameter dictionary with key/values """ self.max_image_width = kwargs.pop("image_width", 0) self.max_image_height = kwargs.pop("image_height", 0) super().__init__(*args, **kwargs) def to_internal_value(self, data): """ Override method to process internal data from serializer Parameters ---------- data: Data received from serializer (raw post data) Returns ------- Python data compatible """ if self.represent_in_base64: if self.max_image_width > 0 and self.max_image_height > 0: width, height = self.__get_file_size(data) if width > self.max_image_width or height > self.max_image_height: raise ValidationError(self.INVALID_FILE_SIZE) image_field = Base64FieldMixin.to_internal_value(self, data) else: image_field = ImageField.to_internal_value(self, data) return image_field def __get_file_size(self, data: str) -> tuple: """ Get the file size from base64 encoded bytes Parameters ---------- base64_data: Base64 encoded bytes Returns ------- width, height: Tuple with width and height values """ try: from PIL import Image base64_data = base64.b64decode(data) image = Image.open(io.BytesIO(base64_data)) except (ImportError, OSError): raise ValidationError(self.INVALID_FILE_MESSAGE) else: width, height = image.size return width, height
zibanu-django
/zibanu_django-1.3.1-py3-none-any.whl/zibanu/django/rest_framework/fields/hybrid_image.py
hybrid_image.py
__all__ = ['Player'] import pygst pygst.require('0.10') import gst import gobject, sys from thread import start_new_thread from time import time class Player(object): _finished = True def __init__(self): self.p = None self.respawn() # FIXME: THIS IS A WORKAROUND SINCE on_message stuff is not working... self.last_position = 0 self.last_position_ts = 0 def set_cache(self, val): """ Sets the cache value in kilobytes """ pass def volume(self, val): """ Sets volume [0-100] """ self.p.props.volume = val/10.0 def seek(self, val): """ Seeks specified number of seconds (positive or negative) """ if self.p: pos = self._nano_pos + long(val)*1000000000 self.p.seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE, gst.SEEK_TYPE_SET, pos, gst.SEEK_TYPE_NONE, 0) @property def paused(self): return gst.STATE_PAUSED in self.p.get_state()[1:] def pause(self): """ Toggles pause mode """ if self.p: if self.paused: self.p.set_state(gst.STATE_PLAYING) else: self.p.set_state(gst.STATE_PAUSED) def respawn(self): """ Restarts the player """ if self.p: self.p.set_state(gst.STATE_READY) self.p = gst.element_factory_make("playbin", "player") self.bus = self.p.get_bus() self.bus.connect('message', self.on_message) self.bus.add_signal_watch() def on_message(self, bus, message): t = message.type print repr(t) if t == gst.MESSAGE_ERROR: self._finished = True elif t == gst.MESSAGE_EOS: self._finished = True # elif t == gst.MESSAGE_STATE_CHANGED: # old, new, pending = message.parse_state_changed() # if old == gst.STATE_PLAYING: # self._finished = True # elif new == gst.STATE_PLAYING: # self._finished = False def load(self, uri): """ Loads the specified URI """ if uri.startswith('/'): uri = 'file://%s'%uri self.p.set_state(gst.STATE_READY) self.p.set_property('uri', uri) self.p.set_state(gst.STATE_PLAYING) self._finished = False def quit(self): """ De-initialize player and wait for it to shut down """ if self.p: try: self.p.set_state(gst.STATE_READY) self.p = None except Exception, e: print "E: %s"%e finally: gobject.MainLoop().quit() @property def position(self): """ returns the stream position, in seconds or None if not playing anymore """ if self.p: if self._finished: return None try: p = int(self._nano_pos/1000000000.0 + 0.5) t = time() if p == self.last_position: if self.last_position_ts + 2 < t: if not self.paused: return None else: self.last_position = p self.last_position_ts = t return p except: return None @property def _nano_pos(self): return self.p.query_position(gst.FORMAT_TIME)[0]
zicbee-gst
/zicbee-gst-0.6.1.tar.gz/zicbee-gst-0.6.1/zicbee_gst/core.py
core.py
__all__ = ['DEBUG', 'debug_enabled', 'log', 'nop', 'set_trace', 'traced'] import os import logging import traceback from logging import getLogger from zicbee_lib.config import config #: general logger log = getLogger('zicbee') def nop(*args): """ Don't do anything """ return try: # tells if debug is enabled or not debug_enabled = (str(config.debug).lower()[:1] not in 'fn') if config.debug else False # disable if "false" or "no" except: debug_enabled = False #try: # from pudb import set_trace as _strace #except ImportError: from pdb import set_trace as _strace def set_trace(): """ Breaks into a debugger prompt, should run pdb. """ try: _strace() except : print "Exception in stread, can't step into!" # environment overrides if not debug_enabled and os.environ.get('DEBUG'): debug_enabled = os.environ['DEBUG'] != '0' def traced(fn): """ Decorator that calls :func:`DEBUG` in case of exception """ def _get_decorator(decorated): def _decorator(*args, **kw): try: return decorated(*args, **kw) except: DEBUG() return _decorator return _get_decorator(fn) def DEBUG(trace=True): """ Prints a traceback + exception, optionally breaks into a debugger. :param bool trace: if True, breaks into a debugger after showing infos. :returns: None """ traceback.print_stack() traceback.print_exc() if trace: set_trace() if debug_enabled: default_formatter = logging.Formatter('[%(threadName)s %(relativeCreated)d] %(module)s %(funcName)s:%(lineno)s %(message)s') try: LOGFILENAME='zicbee.log' file(LOGFILENAME, 'a').close() except Exception: LOGFILENAME=None handlers = [ logging.StreamHandler() ] # first is stderr if LOGFILENAME: handlers.append( logging.FileHandler(LOGFILENAME) ) # add handlers for h in handlers: log.addHandler(h) h.setFormatter( default_formatter ) try: val = int(os.environ.get('DEBUG', 1))*10 except ValueError: val = logging.DEBUG log.setLevel(val) else: globals()['DEBUG'] = nop log.setLevel(logging.FATAL)
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/debug.py
debug.py
import os from time import time import ConfigParser __all__ = ['DB_DIR', 'defaults_dict', 'config', 'aliases', 'shortcuts'] #: database directory DB_DIR = os.path.expanduser(os.getenv('ZICDB_PATH') or '~/.zicdb') #: valid extensions VALID_EXTENSIONS = ['mp3', 'ogg', 'mp4', 'aac', 'vqf', 'wmv', 'wma', 'm4a', 'asf', 'oga', 'flac', 'mpc', 'spx'] def get_list_from_str(s): """ Converts a comma-separated string to a list :arg str s: the string with possible commas :returns: a list of string, without commas :rtype: str """ return [c.strip() for c in s.split(',')] class _Aliases(dict): """ Alias handling internal class """ def __init__(self, name): dict.__init__(self) self._db_dir = os.path.join(DB_DIR, '%s.txt'%name) try: self._read() except IOError: self._write() def __delitem__(self, name): dict.__delitem__(self, name) self._write() def __setitem__(self, name, address): dict.__setitem__(self, name, address) self._write() def _read(self): self.update(dict((s.strip() for s in l.split(None, 1)) for l in file(self._db_dir))) def _write(self): f = file(self._db_dir, 'w') for k, v in self.iteritems(): f.write('%s %s\n'%(k,v)) f.close() try: # Ensure personal dir exists os.mkdir(DB_DIR) except: pass try: from win32com.shell import shell, shellcon TMP_DIR = shell.SHGetPathFromIDList ( shell.SHGetSpecialFolderLocation(0, (shellcon.CSIDL_DESKTOP, shellcon.CSIDL_COMMON_DESKTOPDIRECTORY)[0]) ) except ImportError: # sane environment ;) #: default temporary folder TMP_DIR=r"/tmp" #: Dictionary with default configuration defaults_dict = { 'streaming_file' : os.path.join(TMP_DIR, 'zsong'), 'download_dir' : TMP_DIR, 'db_host' : 'localhost:9090', 'player_host' : 'localhost:9090', 'debug' : '', 'default_search' : '', 'history_size' : 50, 'default_port': '9090', 'web_skin' : 'default', 'fork': 'no', 'allow_remote_admin': 'yes', 'socket_timeout': '30', 'enable_history': 'yes', 'custom_extensions': 'mpg,mp2', 'players' : 'vlc,gst,mplayer', 'music_folder' : '', 'notify' : 'yes', 'loop': 'yes', 'localhost': '', 'autoshuffle': 'yes', } #: Filename for the config file config_filename = os.path.join(DB_DIR, 'config.ini') class _ConfigObj(object): """ Configuration object """ _cfg = ConfigParser.ConfigParser(defaults_dict) def _refresh(self): t = int(time()+0.5) if self._lastcheck + 1 < t: self._lastcheck = t st = os.stat(config_filename) st = max(st.st_mtime, st.st_ctime) if self._mtime < st: self._mtime = st self._cfg.read(config_filename) def __init__(self): self._mtime = 0 # last mtime of the file self._lastcheck = 0 # os.stat flood protection try: self._refresh() except OSError: self._cfg.write(file(config_filename, 'w')) def __setattr__(self, name, val): if name in ('_lastcheck', '_mtime'): return object.__setattr__(self, name, val) self._refresh() if name.endswith('_host'): ref = self[name] if val[0] in '+-': if val[0] == '+': mode = 'a' else: mode = 'd' val = val[1:].strip() else: mode = 'w' if isinstance(val, basestring): val = (v.strip() for v in val.split(',')) vals = (aliases[v] if v in aliases else v for v in val) vals = ('%s:%s'%( v, self.default_port ) if ':' not in v else v for v in vals) if mode != 'w': if mode == 'a': ref.extend(vals) elif mode == 'd': for v in vals: ref.remove(v) vals = ref val = ','.join(vals) elif val.lower() in ('off', 'no'): val = '' val = self._cfg.set('DEFAULT', name, val) config._cfg.write(file(config_filename, 'w')) return val def __getattr__(self, name): self._refresh() v = self._cfg.get('DEFAULT', name) if name in ('db_host', 'player_host', 'custom_extensions', 'players', 'allow_remote_admin'): return [s.strip() for s in v.split(',')] return v __setitem__ = __setattr__ __getitem__ = __getattr__ def __iter__(self): for k in defaults_dict: yield (k, self[k]) #: Config object, supports dots. and brackets[] config = _ConfigObj() # Dictionary-like of host-alias: expanded_value aliases = _Aliases('aliases') # Dictionary-like of shortcut-command: full_command shortcuts = _Aliases('shortcuts') class _DefaultDict(dict): def __init__(self, default, a, valid_keys=None): dict.__init__(self, a) self._default = default if valid_keys: self.valid_keys = valid_keys else: self.valid_keys = None def keys(self): k = dict.keys(self) if self.valid_keys: k = set(k) k.update(self.valid_keys) return k def __getitem__(self, val): try: return dict.__getitem__(self, val) except KeyError: return self._default #: List of valid extensions VALID_EXTENSIONS.extend(config.custom_extensions) #: media-specific configuration media_config = _DefaultDict( {'player_cache': 128, 'init_chunk_size': 2**18, 'chunk_size': 2**14}, { 'flac' : {'player_cache': 4096, 'init_chunk_size': 2**22, 'chunk_size': 2**20}, 'm4a' : {'player_cache': 4096, 'init_chunk_size': 2**22, 'chunk_size': 2**20, 'cursed': True}, }, valid_keys = VALID_EXTENSIONS)
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/config.py
config.py
__all__ = ['memory', 'iter_webget', 'get_infos'] from time import time try: import urllib as urllib2 except ImportError: # Compatibility with python3 import urllib2 # WARNING: urllib2 makes IncompleteRead sometimes... observed with python2.x from .config import config, DB_DIR from itertools import chain def get_infos(): """ Returns informations about the current track. :return: keys/values with all track infos :rtype: dict """ d = {} for line in iter_webget('/infos'): line = line.strip() if line: k, v = line.split(':', 1) v = v.lstrip() d[k] = v memory[k] = v return d def _safe_webget_iter(uri): site = urllib2.urlopen(uri) while True: try: l = site.readline() except Exception, e: print "ERR:", e break else: if l: yield l.strip() else: break def iter_webget(uri): """ Yield results of some HTTP request :type uri: str :param uri: the URI corresponding to your request :return: result, line by line :rtype: iterator """ if not '://' in uri: if 'db' in uri.split('/', 4)[:-1]: hosts = config['db_host'] else: hosts = config['player_host'] uri = uri.lstrip('/') return chain(*(_safe_webget_iter('http://%s/%s'%(host, uri)) for host in hosts)) try: return _safe_webget_iter(uri) uri = [uri] except IOError, e: print "webget(%s): %s"%(uri, e) class _LostMemory(dict): amnesiacs = ( 'album', 'song_position', 'title', 'artist', 'uri', 'pls_position', 'paused', 'length', 'score', 'id', 'pls_size', 'tags') def __init__(self): self._tss = dict() dict.__init__(self) def __getitem__(self, idx): if self._is_recent(idx): return dict.__getitem__(self, idx) def _is_recent(self, idx): if idx not in self.amnesiacs: return True DURATION=1 t = time() return self._tss.get(idx, t-(2*DURATION))+DURATION > t def __setitem__(self, itm, val): self._tss[itm] = time() dict.__setitem__(self, itm, val) def __delitem__(self, slc): del self._tss[slc] dict.__delitem__(self, slc) def get(self, idx, default=None): """ Gets the data, if not recent enough refresh infos """ if not self._is_recent(idx): get_infos() return dict.get(self, idx, default) def clear(self): dict.clear(self) self._tss.clear() #: persistant values, kept across cmdline calls memory = _LostMemory()
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/core.py
core.py
__all__ = ['jdump', 'jload', 'clean_path', 'safe_path', 'duration_tidy', 'get_help_from_func', 'dump_data_as_text', 'get_index_or_slice', 'compact_int', 'uncompact_int'] import inspect import itertools from types import GeneratorType import os from os.path import abspath, expanduser, expandvars from zicbee_lib.debug import log # Filename path cleaner def clean_path(path): """ Expands a path with variables & user alias :param str path: a path containing shell-like shortcuts :returns: A normalized path. :rtype: str """ return expanduser(abspath(expandvars(path))) def safe_path(path): """ Avoids path separators in the path :param str path: the possible unsafe path :returns: A string without separator :rtype: str """ return path.replace(os.path.sep, ' ') # int (de)compacter [int <> small str convertors] # convert to base62... #: conversion base base = 62 #: available characters chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] def compact_int(ival): """ Makes an int compact :param int ival: the integer value you want to shorten :returns: A string equivalent to the integer but with a more compact representation :rtype: str """ result = [] rest = ival b = base while True: int_part, rest = divmod(rest, b) result.append(chars[rest]) if not int_part: break rest = int_part result = "".join(reversed(result)) log.info('compact(%s) = %s', ival, result) return result def uncompact_int(str_val): """ Makes an int from a compact string :param str str_val: The string representing a compact integer value :returns: The integer value :rtype: int """ # int(x, base) not used because it's limited to base 36 unit = 1 result = 0 for char in reversed(str_val): result += chars.index(char) * unit unit *= base log.info('uncompact(%s) = %s', str_val, result) return result def get_index_or_slice(val): """ Converts a string representing an index into an int or a slice :param str val: string like ``4`` or ``1:10`` :raises: :exc:`ValueError` :returns: :keyword:`int` or :keyword:`slice` corresponding to the given string """ try: i = int(val) except ValueError: if ':' in val: vals = [int(x) if x else 0 for x in val.split(':')] if vals[1] > 0: vals[1] += 1 i = slice(*vals) else: raise return i ################################################################################ # # Try to get the most performant json backend # # cjson: # 10 loops, best of 3: 226 msec per loop # simplejson: # 1 loops, best of 3: 10.3 sec per loop # demjson: # 1 loops, best of 3: 65.2 sec per loop # json_engine = None try: from json import dumps as jdump, loads as jload json_engine = "python's built-in" except ImportError: try: from cjson import encode as jdump, decode as jload json_engine = 'cjson' except ImportError: try: from simplejson import dumps as jdump, loads as jload json_engine = 'simplejson' except ImportError: from demjson import encode as jdump, decode as jload json_engine = 'demjson' log.info("using %s engine."%json_engine) ################################################################################ def dump_data_as_text(d, format): """ Dumps simple types (dict, iterable, float, int, unicode) as: json or plain text (compromise between human readable and parsable form) :param str format: value in "html", "json" or "txt" :returns: an iterator returning text """ if format == "json": if isinstance(d, GeneratorType): d = list(d) yield jdump(d) elif format == "html": yield "<html><body>" if isinstance(d, dict): for k, v in d.iteritems(): yield '<b>%s</b>: %s<br/>\n'%(k, v) else: # assume iterable yield "<ul>" for elt in d: yield "<li>%r</li>\n"%elt yield "</ul>" yield "</body></html>" else: # assume "txt" if isinstance(d, dict): for k, v in d.iteritems(): yield '%s: %s\n'%(k, v) else: # assume iterable for elt in d: if isinstance(elt, (list, tuple)): yield " | ".join(str(e) for e in elt) + "\n" else: yield "%s\n"%elt ################################################################################ _plur = lambda val: 's' if val > 1 else '' def duration_tidy(orig): """ Pretty formats an integer duration :param orig: the value you want to pretty-print :type orig: int or float :returns: A string representing the given duration :rtype: :keyword:`str` """ minutes, seconds = divmod(orig, 60) if minutes > 60: hours, minutes = divmod(minutes, 60) if hours > 24: days, hours = divmod(hours, 24) return '%d day%s, %d hour%s %d min %02.1fs.'%(days, _plur(days), hours, _plur(hours), minutes, seconds) else: return '%d hour%s %d min %02.1fs.'%(hours, 's' if hours>1 else '', minutes, seconds) else: return '%d min %02.1fs.'%(minutes, seconds) if minutes > 60: hours = int(minutes/60) minutes -= hours*60 if hours > 24: days = int(hours/24) hours -= days*24 return '%d days, %d:%d.%ds.'%(days, hours, minutes, seconds) return '%d:%d.%ds.'%(hours, minutes, seconds) return '%d.%02ds.'%(minutes, seconds) ################################################################################ # documents a function automatically def get_help_from_func(cmd): """ Returns a pretty-string from a function. :arg callable cmd: the fonction/method you want to get documentation from :Returns: (:keyword:`str` tidy doc, :keyword:`bool` is_remote) from a function :rtype: :keyword:`tuple` """ arg_names, not_used, neither, dflt_values = inspect.getargspec(cmd) is_remote = any(h for h in arg_names if h.startswith('host') or h.endswith('host')) if cmd.__doc__: if dflt_values is None: dflt_values = [] else: dflt_values = list(dflt_values) # Ensure they have the same length if len(dflt_values) < len(arg_names): dflt_values = [None] * (len(dflt_values) - len(arg_names)) doc = '::'.join('%s%s'%(arg_name, '%s'%('='+str(arg_val) if arg_val is not None else '')) for arg_name, arg_val in itertools.imap(None, arg_names, dflt_values)) return ("%s\n%s\n"%( ("%s[::%s]"%(cmd.func_name[3:], doc) if len(doc) > 1 else cmd.func_name[3:]), # title '\n'.join(' %s'%l for l in cmd.__doc__.split('\n') if l.strip()), # body ), is_remote) else: return (cmd.func_name[3:], is_remote)
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/formats.py
formats.py
""" Parser module for tag: <value>-like patterns, you probably just want to use :func:`string2python` """ from __future__ import absolute_import, with_statement __all__ = ['tokens2python', 'parse_string', 'string2python', 'tokens2string'] import re from zicbee_lib.formats import compact_int, uncompact_int # decodes packed "id" keyword + generates varnames from zicbee_lib.remote_apis import ASArtist class VarCounter(object): """ Variable counter, used to increment count and get variables name in an abstract way """ @property def varname(self): v = self.count self.count = v+1 return "v"+compact_int(v) def __enter__(self, *a): self.count = 0 return self def __exit__(self, *a): pass class Node(object): """ Any language keyword is a :class:`Node` """ def __init__(self, name): """ :arg str name: :class:`Node` name""" self.name = name def __repr__(self, *unused): return "%s"%self.name python = __repr__ def isa(self, other): """ Test if that node is of the same type as another :arg other: the other node to test """ return self.__class__ == other.__class__ and self.name == getattr(other, 'name', None) def __eq__(self, other): return self.name == getattr(other, 'name', None) if other else False class Not(Node): """ Negation node - like python's "not" """ def python(self, cnt): """ Returns python representation """ return "not" class Tag(Node): """ A generic tag node """ def __init__(self, name): Node.__init__(self, name) self.substr = [] def __eq__(self, other): if not other: return False return self.name == getattr(other, 'name', None) and self.substr == getattr(other, 'substr', []) def __add__(self, other): assert isinstance(other, basestring) if not self.is_sensitive(): other = other.lower() self.substr.append(other.strip()) return self def from_name(self, name=None): """ Returns a new node of the same type from a node name :arg str name: :class:`Node` name """ return self.__class__(name or self.name) def is_sensitive(self): """ Is that node case-sensitive ? :rtype: bool """ return self.name[0].isupper() def python(self, cnt): """ Python reprensentation of the :class:`Node` """ name = self.name.strip(':').lower() if not self.is_sensitive(): name += ".lower()" prefix, val = self.split_value() if prefix == "in": return ("%r in %s"%(val, name), {}) else: varname = cnt.varname var = {varname: val} return ("%s == %s"%(name, varname), var) def split_value(self): v = self.value if v[0] in '<>=': if v[1] == '=': prefix = v[:2] v = v[2:] else: prefix = v[:1] v = v[1:] if prefix == '=': prefix = '==' else: prefix = 'in' return (prefix, v) @property def value(self): return (' '.join(self.substr)).strip() def __repr__(self): if self.value: return "%s %s"%(self.name, self.value) else: return self.name class NumTag(Tag): """ Numeric node """ def is_sensitive(self): return True def python(self, cnt): val = self.value name = self.name.strip(':') if val[0] in '<>=': varname = cnt.varname if val[0] == '=': expr = ("%s == %s"%(name, varname), {varname: int(val[1:].strip())}) else: if val[1] == '=': expr = ("%s %s %s"%(name, val[:2], varname), {varname: int(val[2:].strip())}) else: expr = ("%s %s %s"%(name, val[:1], varname), {varname: int(val[1:].strip())}) else: # default a_varname = cnt.varname b_varname = cnt.varname var = {a_varname: int(val)-1, b_varname: int(val)+1} expr = ("%s <= %s <= %s"%(a_varname, name, b_varname), var) return expr class Index(Tag): """ "id" node """ def is_sensitive(self): return True def python(self, cnt): val = self.value varname = cnt.varname return ("__id__ == %s"%(varname), {varname: uncompact_int(val)}) @property def value(self): if len(self.substr) != 1: return 'N/A' return (' '.join(self.substr)).strip() class Special(Tag): """ Special (no python meaning) node """ preserve_suffix = True def __eq__(self, other): return self.name == getattr(other, 'name', None) if other else False def __repr__(self): if self.preserve_suffix: name = self.name else: name = self.name[:-1] if self.value: return "%s %s"%(name, self.value) else: return name def python(self, cnt): return '' # Not applicable # Recognised infos is here: #: Regex for tags TAG_RE = re.compile(r'([A-Za-z][a-z_-]*:)') #: Regex for operators OP_RE = re.compile(r'(?<!\w)(and|or|!)(?=\W)') #: Regex for groups GRP_RE = re.compile(r'(?<!\\)([()])') #: Regex for ( OPEN = Node('(') #: Regex for ) CLOSE = Node(')') #: "or" node OR = Node('or') #: "and" node AND = Node('and') #: "not" node NOT = Not('!') #: "id": node ID = Index('id:') #: "artist" node ARTIST = Tag('artist:') #: "album" node ALBUM = Tag('album:') #: "title" node TITLE = Tag('title:') #: "tags" node TAG = Tag('tags:') #: "Artist" node CS_ARTIST = Tag('Artist:') #: "Album" node CS_ALBUM = Tag('Album:') #: "Title" node CS_TITLE = Tag('Title:') #: "length" node LENGTH = NumTag('length:') #: "score" node SCORE = NumTag('score:') #: "pls" node PLAYLIST = Special('pls:') #: "auto" node AUTO = Special('auto:') #: operators in form {name: :class:`Node`} OP_by_name = {'and': AND, 'or': OR, '!': NOT} #: operators node list OPERATORS = OP_by_name.values() #: tags nodes list TAGS = (ARTIST, ALBUM, TITLE, LENGTH, SCORE, PLAYLIST, AUTO, ID, CS_ARTIST, CS_ALBUM, CS_TITLE) def parse_string(st): """ Parses a string :arg str st: The string you want to parse """ # minor sanity check, allowing people to use !artist: syntax (instead of ! artist:) st = re.sub('!(\S)', r'! \1', st) # handle () st = GRP_RE.split(st) for i, sub in enumerate(st): for tag in OPEN, CLOSE: if tag.name == sub: st[i] = tag break # handle or, and # print "* groups:", st for i, sub in reversed(list(enumerate(st))): if isinstance(sub, basestring): subs = OP_RE.split(sub) if len(subs) > 1: st[i:i+1] = subs st = [temp for temp in st if temp] # clean things a little # print "* pre-operators:", st for i, sub in enumerate(st): tag = OP_by_name.get(sub) if tag: st[i] = tag # print "* operators:", st # handle tags for i, sub in reversed(list(enumerate(st))): if isinstance(sub, basestring): subs = TAG_RE.split(sub) if len(subs) > 1: st[i:i+1] = subs for i, sub in enumerate(st): for tag in TAGS: if tag.name == sub: st[i] = tag.from_name(tag.name) # tags are UNIQUE break #print "* tags:", st # cleaning up res = [] infos = {'tag': None} for token in st: if isinstance(token, basestring) and not token.strip(): continue if isinstance(token, basestring): if not infos['tag']: res.append(token) else: infos['tag'] += token else: if isinstance(token, Tag): infos['tag'] = token else: infos['tag'] = None res.append(token) skip_count = 0 for i, r in reversed(list(enumerate(res))): if skip_count: skip_count -= 1 continue if isinstance(r, basestring): if i > 1 and res[i-1] in OPERATORS and isinstance(res[i-2], Tag): res[i-2] += res[i-1].name res[i-2] += r res[i-1:i+1] = [] skip_count += 2 else: res[i] = Node(r.strip()) # Inserts missing operators i = enumerate(res) prev = None prev_prev = None while True: try: idx, tok = i.next() except StopIteration: break if isinstance(prev, Tag) and isinstance(tok, Tag) and not isinstance(tok, Special) and not\ (isinstance(prev, Special) and (prev_prev is None or isinstance(prev_prev, Special))): res[idx:idx] = [AND] i.next() # skip the newly added token elif prev == CLOSE and tok == OPEN: # ... ) ( ... => ...) or (... res[idx:idx] = [OR] i.next() prev_prev = prev prev = tok # converts tag:, ( ,str1 , op1, str2, op2, str3, ) # to: ( ,tag-str1, op1, tag-str2, op2, tag-str3, ) i = enumerate(res) prev = None while True: try: idx, tok = i.next() except StopIteration: break if isinstance(prev, Tag) and tok == OPEN: # looks-up the associated ")" while sorting operators and values concerned_tag = prev start_idx = idx count = 1 operators = [] values = [] loc_prev = None while True: idx, tok = i.next() if tok == OPEN: count += 1 elif tok == CLOSE: count -= 1 else: prev_is_txt = isinstance(loc_prev, basestring) cur_is_txt = isinstance(tok, basestring) if tok in OPERATORS: operators.append(tok) elif cur_is_txt: if prev_is_txt: loc_prev = "%s %s"%(loc_prev, tok) else: values.append(tok) if count == 0: break loc_prev = tok ops = iter(operators) replaces = [OPEN] for n in values: t = Tag(concerned_tag.name) # naked tag t += n.name replaces.append(t) try: replaces.append(ops.next()) except StopIteration: continue replaces.append(CLOSE) res[start_idx-1:idx+1] = replaces prev = tok if len(res) == 1 and type(res[0]) == Node: val = res[0].name res = [ARTIST.from_name() + val, OR, ALBUM.from_name() + val, OR, TITLE.from_name() + val] return res def tokens2python(tokens): """ Convert a list of tokens into python code :arg tokens: the list of tokens you want to convert :type tokens: (:keyword:`list` of :class:`Node`) :returns: the python code + variables dictionnary :rtype: :keyword:`tuple`(:keyword:`str`, :keyword:`dict`) """ with VarCounter() as vc: ret = [] d = {} for tok in tokens: r = tok.python(vc) if isinstance(r, tuple): d.update(r[1]) ret.append(r[0]) else: ret.append(r) return (' '.join(ret), d) def tokens2string(tokens): """ Convert a list of tokens to a simple string :arg tokens: the list of tokens you want to convert :type tokens: (:keyword:`list` of :class:`Node`) :rtype: str """ return ' '.join(str(t) for t in tokens) def string2python(st): """ Converts a string into python code :arg str st: the string (pattern) you want to convert :returns: the same as :func:`tokens2python` """ toks = parse_string(st) if AUTO in toks: max_vals = int(toks[toks.index(AUTO)].value or 10) it = enumerate(list(toks)) offset = 0 while True: try: i, tok = it.next() except StopIteration: break if tok.name == ARTIST.name: ext_list = [OPEN, tok] v = tok.value if v[0] in '=<>': prefix = v[0] v = v[1:] else: prefix = '' similar_artists = ASArtist(v).getSimilar()[:max_vals] for artist in similar_artists: ext_list.extend((OR, ARTIST.from_name(tok.name)+(prefix+artist[1]))) ext_list.append(CLOSE) toks[i+offset:i+offset+1] = ext_list offset += len(ext_list)-1 return tokens2python(toks) def _string2python(st): return tokens2python(parse_string(st)) if __name__ == '__main__': def to(st): print "-"*80 print st print string2python(st)[0] to("artist: (Bob marley and the wa or tricky)") to("artist: bob marley and the waillers") raise SystemExit() to("artist: cool and the gang") to("artist: wax tailor") to("artist: wax tailor and ! title: foo") to("artist: björk or artist: foobar auto:") to("artist: (björk or foobar) auto:") to("auto: artist: (björk or foobar)") to("auto: 20 artist: (toto or björk or foobar)") tst_str = [ 'artist: Björk or artist: toto', 'artist: metallica album: black', 'artist:(noir or toto)', 'artist: ( noir or toto ) ', 'something else', 'artist: the blues bro and (title: sal or title: good)', 'artist: the blues bro and title: (sal or good)', 'artist:toto and(album: rorot or title: za andva ti)', 'artist:toto and(album: =rorot or title: za andva ti)', ] print string2python("artist: joe title: sub marine") for st in tst_str: print "-"*80 print st ps = parse_string(st) print ps print tokens2python(ps) while True: line = raw_input('pattern: ') ps = parse_string(line) print ps print tokens2python(ps)
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/parser.py
parser.py
import os import sys import time from zicbee_lib.core import urllib2 from zicbee_lib.formats import duration_tidy from itertools import chain from weakref import WeakKeyDictionary def DownloadGenerator(uri): """ Gets some uri :param uri: uri and output filename :type uri: tuple(str, str) :returns: an iterator that will download the uri to the filename """ uri, filename = uri if os.path.exists(filename): return site = urllib2.urlopen(uri) out_file = file(filename, 'w') BUF_SZ = 2**16 try: total_size = int(site.info().getheader('Content-Length')) except TypeError: total_size = None actual_size = 0 progress_p = 0 while True: data = site.read(BUF_SZ) if not data: out_file.close() break out_file.write(data) actual_size += len(data) if total_size: percent = total_size/actual_size else: percent = actual_size if percent != progress_p: yield percent progress_p = percent else: yield '.' class Downloader(object): """ A nice downloader class with pretty user output (stdout) just call :meth:`run` with a list of uris you want to fetch """ def __init__(self, nb_dl=2): """ :param int nb_dl: number of downloads to do in parallel """ self._nb_dl = nb_dl self._last_display = time.time() def run(self, uri_list): """ Takes a list of uri and returns when they are downloaded :param iterable uri_list: a list of uris (str) :returns: None """ downloaders = [] # Generators to handle in_queue = [] # List of "TODO" uris _download_infos = dict(count=0, start_ts = time.time()) percent_memory = WeakKeyDictionary() write_out = sys.stdout.write def _download(): for dl in downloaders: try: ret = dl.next() except StopIteration: downloaders.remove(dl) _download_infos['count'] += 1 else: if isinstance(ret, int): percent_memory[dl] = ret # Display things t = time.time() if self._last_display + 0.1 < t: self._last_display = t sumup = ', '.join('%3d%%'%(val if int(val)<=100 else 0) for val in percent_memory.itervalues()) write_out(' [ %s ] %d \r'%(sumup, _download_infos['count'])) sys.stdout.flush() for uri in chain( uri_list, in_queue ): if len(downloaders) < self._nb_dl: try: dg = DownloadGenerator(uri) dg.next() # start the pump downloaders.append( dg ) except StopIteration: pass else: in_queue.append(uri) # Later please ! # iterate _download() # Terminate the job while downloaders: _download() t = time.time() - _download_infos['start_ts'] write_out(" \nGot %d files in %s. Enjoy ;)\n"%( _download_infos['count'], duration_tidy(t)))
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/downloader.py
downloader.py
import os import readline from cmd import Cmd from functools import partial from zicbee_lib.commands import commands, execute from zicbee_lib.resources import set_proc_title from zicbee_lib.config import config, DB_DIR from zicbee_lib.debug import DEBUG def complete_command(name, completer, cur_var, line, s, e): """ Generic completion helper """ ret = completer(cur_var, line.split()) return [cur_var+h[e-s:] for h in ret if h.startswith(cur_var)] class Shell(Cmd): """ Wasp shell :) """ #: default prompt prompt = "Wasp> " def __init__(self): self._history = os.path.join(DB_DIR, 'wasp_history.txt') self._last_line = None try: readline.read_history_file(self._history) except IOError: 'First time you launch Wasp! type "help" to get a list of commands.' for cmd, infos in commands.iteritems(): try: completer = commands[cmd][2]['complete'] except (IndexError, KeyError): pass # no completor else: setattr(self, 'complete_%s'%cmd, partial(complete_command, cmd, completer)) Cmd.__init__(self) print "Playing on http://%s songs from http://%s/db"%(config['player_host'][0], config['db_host'][0]) self.names = ['do_%s'%c for c in commands.keys()] + ['do_help'] set_proc_title('wasp') def onecmd(self, line): """ Executes one line :arg str line: the line to execute """ try: cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if cmd == '': ret = self.default(line) else: ret = execute(cmd, arg) except Exception, e: print "Err: %s"%e DEBUG() except KeyboardInterrupt: print "Interrupted!" else: print "." return ret def get_names(self): """ Returns the list of commands """ return self.names def do_EOF(self, line): """ Handles EOF user-event """ try: readline.set_history_length(int(config['history_size'])) except: pass readline.write_history_file(self._history) raise SystemExit() do_exit = do_quit = do_bye = do_EOF
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/wasp/core.py
core.py
__all__ = [ 'modify_move', 'modify_show', 'set_variables', 'tidy_show', 'inject_playlist', 'hook_next', 'hook_prev', 'complete_set', 'complete_alias', 'set_alias', 'set_grep_pattern', 'apply_grep_pattern', 'set_shortcut'] import ConfigParser from zicbee_lib.config import config, aliases, shortcuts from zicbee_lib.core import get_infos, memory, iter_webget from zicbee_lib.formats import get_index_or_slice from urllib import quote def complete_set(cur_var, params): """ "set" command completion """ if len(params) <= 2 and cur_var: # complete variables ret = (k for k, a in config if k.startswith(cur_var)) elif len(params) >= 2: data = dict(config) # complete values if '_host' in params[1]: data.update(('___'+v, v) for v in aliases) ret = [v for v in data.itervalues()] for r in list(ret): if isinstance(r, (list, tuple)): ret.remove(r) ret.extend(r) ret.append('localhost') ret = set(r for r in ret if r.startswith(cur_var)) return ret def hook_next(output): """ "next" command hook """ if 'pls_position' in memory: del memory['pls_position'] return '/next' def hook_prev(output): """ "prev" command hook """ if 'pls_position' in memory: del memory['pls_position'] return '/prev' def set_grep_pattern(output, *pat): """ remembers the "grep" pattern """ memory['grep'] = ' '.join(pat) return '/playlist' def apply_grep_pattern(it): """ apply the "grep" pattern to the given iterator """ # TODO: optimize pat = memory['grep'].lower() grep_idx = [] for i, line in enumerate(it): if pat in line.lower(): grep_idx.append(i) yield "%3d %s"%(i, ' | '.join(line.split(' | ')[:4])) memory['grepped'] = grep_idx def inject_playlist(output, symbol): """ Play (inject in current playlist) the last "search" result """ uri = memory.get('last_search') if not uri: print "Do a search first !" return pattern = uri[0].split('pattern=', 1)[1] # the pattern should be the same for anybody # crazy escaping substr = ("%s%%20pls%%3A%%20%s%%23"%(pattern, quote(symbol))).replace('%', '%%') v = "/search?host=%(db_host)s&pattern="+substr return v def set_shortcut(output, name=None, *args): """ Sets some shortcut """ if args: value = ' '.join(args) else: value = None try: if name is None: for varname, varval in shortcuts.iteritems(): output(["%s = %s"%(varname, varval)]) elif value: if value.lower() in ('no', 'off', 'false'): del shortcuts[name] else: shortcuts[name] = value output(["%s = %s"%(name, shortcuts[name])]) else: output(["%s = %s"%(name, shortcuts[name])]) except KeyError: print "invalid option." def set_alias(output, name=None, value=None): """ Sets some alias """ try: if name is None: for varname, varval in aliases.iteritems(): output(["%s = %s"%(varname, varval)]) elif value: if value.lower() in ('no', 'off', 'false'): del aliases[name] else: aliases[name] = value output(["%s = %s"%(name, aliases[name])]) else: output(["%s = %s"%(name, aliases[name])]) except KeyError: print "invalid option." def complete_alias(cur_var, params): """ Completes the "alias" command """ if len(params) <= 2 and cur_var: # complete variables ret = (k for k in aliases.iterkeys() if k.startswith(cur_var)) elif len(params) >= 2: ret = (v for v in aliases.itervalues() if v.startswith(cur_var)) return ret def set_variables(output, name=None, value=None, *args): """ Set some variable """ CST = ' ,=' if name: if '=' in name: nargs = (n.strip() for n in name.split('=') if n.strip()) name = nargs.next() args = tuple(nargs) + args name = name.strip(CST) if args: value = ("%s,%s"%(value.strip(CST), ','.join(a.strip(CST) for a in args))).strip(CST) try: def _out(k, v): return output(["%s = %s"%(k, ', '.join(v) if isinstance(v, list) else v )]) if name is None: for varname, v in config: _out(varname, v or 'off') else: if value is not None: config[name] = value v = config[name] _out(name, v) except ConfigParser.NoOptionError: output(["invalid option."]) def modify_delete(output, songid): """ hook for the "delete" command """ if songid == 'grep': return ('/delete?idx=%s'%(i-idx) for idx, i in enumerate(memory['grepped'])) else: return '/delete?idx=%s'%songid def modify_move(output, songid, where=None): """ Hook for the "move" command """ if where is None: infos = get_infos() where = int(infos['pls_position'])+1 if songid == 'grep': return ('/move?s=%s&d=%s'%(i, where+idx) for idx, i in enumerate(memory['grepped'])) else: return '/move?s=%s&d=%s'%(songid, where) def random_command(output, what='artist'): """ executes the "random" command Fills the playlist with a random artist (or album) """ dbh = config.db_host[0] arg = iter_webget('http://%s/db/random?what=%s'%(dbh, what)).next() return '/search?%s&host=%s'%(arg, dbh) def show_random_result(it): """ displays the "random" command result """ uri = modify_show(None) return ('-'.join(r.split('|')[1:4]) for r in iter_webget(uri)) def modify_show(output, answers=10): """ Hook for the "show" command """ answers = get_index_or_slice(answers) if isinstance(answers, slice): memory['show_offset'] = answers.start results = 0 if answers.stop <= 0 else answers.stop - answers.start return '/playlist?res=%s&start=%s'%(results, answers.start) else: pos = memory.get('pls_position') if pos is None: return '' try: position = int(pos) except TypeError: position = -1 if position >= 0: memory['show_offset'] = position return '/playlist?res=%s&start=%s'%(answers, position) else: memory['show_offset'] = 0 return '/playlist?res=%s'%(answers) def tidy_show(it): """ Improve the "show" output """ offs = memory['show_offset'] now = int(memory.get('pls_position', -1)) for i, line in enumerate(it): idx = offs+i yield '%3s %s'%(idx if idx != now else ' >> ', ' | '.join(line.split(' | ')[:4]))
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/commands/command_misc.py
command_misc.py
ALLOW_ASYNC = True from itertools import chain try: from itertools import izip_longest def unroll(i): """ unrolls a list of iterators, following the longest chain returns an interator """ return chain(*izip_longest(*i)) except ImportError: # python < 2.6 def unroll(i): l = list(i) while True: for i in l: try: yield i.next() except StopIteration: l.remove(i) if not l: break # map(lambda *a: [a for a in a if a is not None], xrange(3), xrange(5)) import sys import thread from urllib import quote from functools import partial from types import GeneratorType from zicbee_lib.core import memory, config, iter_webget from zicbee_lib.debug import debug_enabled from zicbee_lib.config import shortcuts from .command_get import get_last_search from .command_misc import complete_alias, complete_set, hook_next, hook_prev, set_shortcut from .command_misc import inject_playlist, modify_move, modify_show, set_alias, modify_delete from .command_misc import set_variables, tidy_show, apply_grep_pattern, set_grep_pattern from .command_misc import random_command, show_random_result def complete_cd(cw, args): """ completor function for "cd" command """ a = ' '.join(args[1:]) word = len(args)-2 # remove last (index starts to 0, and first item doesn't count) if not cw: word += 1 # we are already on next word if not memory.get('path'): # nothing in memory lls = ['artist', 'album'] else: lls = memory.get('last_ls') if lls: riri = [w.split() for w in lls if w.startswith(a)] if len(riri) > 1: return (w[word] for w in riri) else: return [' '.join(riri[0][word:])] def remember_ls_results(r): """ stores results into memory """ ret = [] for res in r: if not res.startswith('http://'): ret.append(res) yield res memory['last_ls'] = ret def ls_command(out, *arg): """ ls command implementation Allow someone to list artists, albums and songs """ path = memory.get('path', []) arg = ' '.join(arg) if len(path) == 0: out(['artists', 'albums']) return if len(path) == 2 or arg: return ('/db/search?fmt=txt&host=%(db_host)s&pattern='+quote('artist:%(args)s' if arg else ":".join(path)).replace('%', r'%%')) elif len(path) == 1: if path[0].startswith('ar'): return '/db/artists' else: return '/db/albums' def pwd_command(out): """ shows the current working directory """ path = memory.get('path', []) out(['/'+('/'.join(path))]) def cd_command(out, *arg): """ Changes the current directory """ path = memory.get('path', []) arg = ' '.join(arg) if arg == '..': if path: path.pop(-1) elif arg == '/' or not arg: path = [] else: if 0 == len(path): if arg.startswith('ar'): path.append('artist') else: path.append('album') elif 1 == len(path): path.append(arg) elif path[0].startswith('artist') and len(path) == 2: path = ['album', arg] out(['Changed path to album/%s'%arg]) else: out(["Can't go that far ! :)"]) memory['path'] = path #: remembers the last search result remember_results = partial(memory.__setitem__, 'last_search') #: forget last search result forget_results = lambda uri: memory.__delitem__('last_search') #: this dict stores all the available commands commands = { # 'freeze': (dump_home, 'Dumps a minimalistic python environment'), 'play': ('/search?host=%(db_host)s&pattern=%(args)s', 'Play a song', dict(threaded=True)), 'search': ('/db/search?fmt=txt&pattern=%(args)s', 'Query the database', dict(uri_hook=remember_results)), 'as': (partial(inject_playlist, symbol='>'), 'Appends last search to current playlist'), 'is': (partial(inject_playlist, symbol='+'), 'Inserts last search to current playlist (after the current song)'), 'm3u': ('/db/search?fmt=m3u&pattern=%(args)s', 'Query the database, request m3u format'), 'version': ('/db/version', 'Show DB version'), 'db_tag': ('/db/tag/%s/%s', 'Associates a tag to a song (params: Id, Tag)'), 'artists': ('/db/artists', 'Show list of artists'), 'albums': ('/db/albums', 'Show list of albums'), 'genres': ('/db/genres', 'Show list of genres'), 'kill': ('/db/kill', 'Power down'), 'get': (get_last_search, 'Download results of last search or play command'), 'set': (set_variables, 'List or set application variables, use "off" or "no" to disable an option.', dict(complete=complete_set)), 'host_alias': (set_alias, 'List or set hosts aliases', dict(complete=complete_alias)), 'alias': (set_shortcut, 'Lists or set al custom commands (shortcuts)'), # complete_set': (lambda: [v[0] for v in config], lambda: set(v[1] for v in config)) 'stfu': ('/close', 'Kill player host'), 'pause': ('/pause', 'Toggles pause'), 'next': (hook_next, 'Zap current track'), 'prev': (hook_prev, 'Go back to last song'), 'infos': ('/infos', 'Display player status'), 'meta': ('/db/infos?id=%s', 'Display metadatas of a song giving his id'), 'delete': (modify_delete, "Remove player's song at given position, if not given a position, removes a named playlist"), 'move': (modify_move, "Move a song from a position to another\n\t(if none given, adds just next current song)"), 'swap': ('/swap?i1=%s&i2=%s', "Swap two songs"), 'append': ('/append?name=%s', "Append a named playlist to the current playlist"), 'load': ('/copy?name=%s', "Loads the specified playlist"), 'inject': ('/inject?name=%s', "Inserts the specified playlist to current one"), 'save': ('/save?name=%s', "Saves the current playlist to given name"), 'volume': ('/volume?val=%s', "Changes the volume"), 'playlist': ('/playlist', "Shows the entire playlist (Might be SLOW!)"), 'grep': (set_grep_pattern, "Grep (search for a pattern) in the playlist", dict(display_modifier=apply_grep_pattern)), 'playlists': ('/playlists', "Shows all your saved playlists"), 'show': (modify_show, "Shows N elements after the current song,\n\tif you set a slice (ex.: show 3:10) then it shows the selected range.", dict(display_modifier=tidy_show)), 'guess': ('/guess/%(args)s', "Tells if you are right (blind mode)"), 'shuffle': ('/shuffle', "Shuffles the playlist"), 'tag': ('/tag/%s', "Set a tag on current song"), 'random': (random_command, "Picks a random artist and play it (random album if 'album' is the parameter", dict(display_modifier=show_random_result)), 'rate': ('/rate/%s', "Rate current song"), 'clear': ('/clear', "Flushes the playlist"), 'seek': ('/seek/%s', "Seeks on current song"), 'ls': (ls_command, "List current path content", dict(uri_hook=remember_results, display_modifier=remember_ls_results)), 'cd': (cd_command, "Change current directory (use '..' to go to parent directory)", dict(uri_hook=forget_results, complete=complete_cd)), 'pwd': (pwd_command, "Print current directory path"), } # execution code possible_commands = commands.keys() possible_commands.append('help') possible_commands.extend(shortcuts.keys()) def write_lines(lines): """ write lines on stdout """ sys.stdout.writelines(l+'\n' for l in lines) def execute(name=None, line=None, output=write_lines): """ Executes any command :param str name: the name of the command to execute :param str line: the rest of the command arguments :param callable output: the output function, taking a `str` as the only parameter. .. note:: `line` can be omitted, in that case, all informations must be passed to the `name` variable. """ # real alias support (not host alias, full command) if name in shortcuts: name = shortcuts[name] if ' ' in name: name, rest = name.split(None, 1) if not line: line = rest else: line = "%s %s"%(rest, line) if not line: args = name.split() name = args.pop(0) else: args = line.split() if name not in possible_commands: # abbreviations support possible_keys = [k for k in possible_commands if k.startswith(name)] if len(possible_keys) == 1: name = possible_keys[0] elif not possible_keys: if name in ('EOF', 'exit', 'bye'): raise SystemExit print 'Unknwown command: "%s"'%name return elif name not in possible_keys: print "Ambiguous: %s"%(', '.join(possible_keys)) return if name == 'help': if args: try: print commands[args[0]][1] except KeyError: if args[0] not in commands: print '"%s" is not recognised.'%args[0] else: print "No help for that command." finally: return for cmd, infos in commands.iteritems(): print "%s : %s"%(cmd, infos[1]) print """ Syntax quick sheet Tags: * id (compact style) * genre * artist * album * title * track * filename * score * tags * length Playlists (only with play command): use "pls: <name>" to store the request as "<name>" The name can receive special prefix from this list: ">" to append instead of replacing "+" inserts just next current playing song Note that "#" is a special name to point "current" playlist Numerics (length, track, score) have rich operators, default is "==" for equality length: >= 60*5 length: < 60*3+30 length: >100 score: 5 """ return try: pat, doc = commands[name] extras = {} except ValueError: pat, doc, extras = commands[name] if callable(pat): try: pat = pat(output, *args) except TypeError, e: print "Wrong arguments, %s%s"%(name, e.args[0].split(')', 1)[1]) return if not pat: return args = [quote(a) for a in args] if not isinstance(pat, (list, tuple, GeneratorType)): pat = [pat] uris = [] for pattern in pat: if '%s' in pattern: expansion = tuple(args) else: expansion = dict(args = '%20'.join(args)) try: if '_host)s' in pattern: # assumes expansion is dict... # WARNINGS: # * mixing args & kwargs is not supported) # * can't use both hosts in same request !! if pattern.startswith('/db'): base_hosts = config['db_host'] else: base_hosts = config['player_host'] prefixes = [ 'http://%s'%h for h in base_hosts ] if '%(player_host)s' in pattern: for player_host in config['player_host']: expansion['player_host'] = player_host for p in prefixes: try: uris.append( p + (pattern%expansion) ) except TypeError: print "Wrong number of arguments" return elif '%(db_host)s' in pattern: for db_host in config['db_host']: expansion['db_host'] = db_host for p in prefixes: try: uris.append( p + (pattern%expansion) ) except TypeError: print "Wrong number of arguments" return else: try: uris = [pattern%expansion] except TypeError: print "Wrong number of arguments" return except Exception, e: print "Invalid arguments: %s"%e if extras.get('uri_hook'): extras['uri_hook'](uris) r = unroll(iter_webget(uri) for uri in uris) if r: def _finish(r, out=None): if extras.get('display_modifier'): r = extras['display_modifier'](r) if out: out(r) else: if debug_enabled: for l in r: out(r) else: for l in r: pass if ALLOW_ASYNC and extras.get('threaded', False): thread.start_new(_finish, (r,)) else: _finish(r, output) def _safe_execute(what, output, *args, **kw): i = what(*args, **kw) if hasattr(i, 'next'): output(i)
zicbee-lib
/zicbee-lib-0.7.3.tar.bz2/zicbee-lib-0.7.3/zicbee_lib/commands/__init__.py
__init__.py
import os import select import subprocess class_code = """# Access MPlayer from python import os import select import subprocess DEBUG = bool(os.environ.get('DEBUG_MPLAYER', False)) class MPlayer(object): ''' A class to access a slave mplayer process you may also want to use command(name, args*) directly Exemples: mp.command('loadfile', '/desktop/funny.mp3') mp.command('pause') mp.command('quit') Or: mp.loadfile('/desktop/funny.mp3') mp.pause() mp.quit() ''' exe_name = 'mplayer' if os.sep == '/' else 'mplayer.exe' def __init__(self, cache=128): self._spawn(cache) def wait(self): self._mplayer.wait() def respawn(self): self._mplayer.stdin.write('quit\n') self._mplayer.wait() self._spawn(self._cache) def _spawn(self, cache): self._mplayer = subprocess.Popen( [self.exe_name, '-cache', '%s'cache, '-slave', '-quiet', '-idle'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1) self._cache = cache self._readlines() def set_cache(cache): if cache != self._cache: self._spawn(cache) def __del__(self): self._mplayer.stdin.write('quit\\n') def _readlines(self, timeout=0.4): ret = [] while any(select.select([self._mplayer.stdout.fileno()], [], [], timeout)): ret.append( self._mplayer.stdout.readline() ) return ret def _get_meta(self): try: meta = self.prop_metadata.split(',') except AttributeError: return None else: return dict(zip(meta[::2], meta[1::2])) meta = property(_get_meta, doc="Get metadatas as a dict"); del _get_meta def command(self, name, *args): ''' Very basic interface Sends command 'name' to process, with given args ''' ret = self._readlines(0.01) # Flush if DEBUG: print "FLUSH LINES:", ret cmd = 'pausing_keep %s%s%s\\n'%(name, ' ' if args else '', ' '.join(repr(a) for a in args) ) if DEBUG: print "CMD:", cmd try: self._mplayer.stdin.write(cmd) except IOError: self._spawn() self._mplayer.stdin.write(cmd) if name == 'quit': return ret = self._readlines() if DEBUG: print "READ LINES:", ret if not ret: return None else: ret = ret[-1] if ret.startswith('ANS'): val = ret.split('=', 1)[1].rstrip() try: return eval(val) except: return val return ret """ exe_name = 'mplayer' if os.sep == '/' else 'mplayer.exe' mplayer = subprocess.Popen([exe_name, '-input', 'cmdlist'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) def args_pprint(txt): lc = txt.lower() if lc[0] == '[': return '%s=None'%lc[1:-1] return lc _slave_txt = None def _find_doc_for(name): global _slave_txt if _slave_txt is None: import urllib uri = 'slave.txt' if os.path.isfile('slave.txt') else 'http://www.mplayerhq.hu/DOCS/tech/slave.txt' _slave_txt = urllib.urlopen(uri).readlines() actual_doc = None for line in _slave_txt: if actual_doc: if line.strip(): actual_doc += line else: break elif line.endswith('properties:\n'): break elif line.startswith(name): actual_doc = line return actual_doc while True: line = mplayer.stdout.readline() if not line: break if line[0].isupper(): continue args = line.split() cmd_name = args.pop(0) arguments = ', '.join(args_pprint(a) for a in args) doc = _find_doc_for(cmd_name) or '%s(%s)'%(cmd_name, arguments) minargc = len([a for a in args if a[0] != '[']) func_str = ''' def %(name)s(self, *args): """ %(doc)s """ if %(condition)s: raise TypeError('%(name)s takes %(argc)d arguments (%%d given)'%%len(args)) return self.command('%(name)s', *args)\n\n'''%dict( doc = doc, condition = ('len(args) != %d'%len(args)) if len(args) == minargc else ('not (%d <= len(args) <= %d)'%(minargc, len(args))), argc = len(args), name = cmd_name, ) class_code += func_str _not_properties = True name = None for line in _slave_txt: if _not_properties: if line.startswith('==================='): _not_properties = False class_code += '#Properties\n' else: if line[0].isalpha(): if name is not None and name[-1] != '*': class_code += """ prop_%(name)s = property( lambda self: self.get_property("%(name)s"), %(setter)s, doc = %(doc)s) """%dict( name = name, doc = ("'''%s'''"%('\n'.join(comments))) if any(comments) else 'None', setter = 'None' if ro else 'lambda self, val: self.set_property("%s", val)'%name ) ridx = line.rindex('X') idx = line.index('X') try: name, p_type, limits = line[:idx].split(None, 2) except ValueError: # No limits name, p_type = line[:idx].split(None) limits = None permissions = len(line[idx:ridx+1]) comments = [line[ridx+1:].strip()] ro = permissions < 2 elif name is not None: comments.append(line.strip()) print class_code
zicbee-mplayer
/zicbee-mplayer-0.9.1.tar.gz/zicbee-mplayer-0.9.1/zicbee_mplayer/_mpgen.py
_mpgen.py
import os import select import subprocess DEBUG = bool(os.environ.get('DEBUG_MPLAYER', False)) class MPlayer(object): ''' A class to access a slave mplayer process you may also want to use command(name, args*) directly Exemples: mp.command('loadfile', '/desktop/funny.mp3') mp.command('pause') mp.command('quit') Or: mp.loadfile('/desktop/funny.mp3') mp.pause() mp.quit() ''' exe_name = 'mplayer' if os.sep == '/' else 'mplayer.exe' def __init__(self, cache=128): self._spawn(cache) def wait(self): self._mplayer.wait() def respawn(self): self._mplayer.stdin.write('quit\n') self._mplayer.wait() self._spawn(self._cache) def _spawn(self, cache): self._mplayer = subprocess.Popen( [self.exe_name, '-cache', '%s'%cache, '-slave', '-quiet', '-idle'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1) self._cache = cache self._readlines() def set_cache(self, cache): if cache != self._cache: self._spawn(cache) def __del__(self): self._mplayer.stdin.write('quit\n') def _readlines(self, timeout=0.4): ret = [] while any(select.select([self._mplayer.stdout.fileno()], [], [], timeout)): ret.append( self._mplayer.stdout.readline() ) return ret def _get_meta(self): try: meta = self.prop_metadata.split(',') except AttributeError: return None else: return dict(zip(meta[::2], meta[1::2])) meta = property(_get_meta, doc="Get metadatas as a dict"); del _get_meta def command(self, name, *args): ''' Very basic interface Sends command 'name' to process, with given args ''' ret = self._readlines(0.01) # Flush if DEBUG: print "FLUSH LINES:", ret cmd = 'pausing_keep %s%s%s\n'%(name, ' ' if args else '', ' '.join(repr(a) for a in args) ) if DEBUG: print "CMD:", cmd try: self._mplayer.stdin.write(cmd) except IOError: self._spawn() self._mplayer.stdin.write(cmd) if name == 'quit': return ret = self._readlines() if DEBUG: print "READ LINES:", ret if not ret: return None else: ret = ret[-1] if ret.startswith('ANS'): val = ret.split('=', 1)[1].rstrip() try: return eval(val) except: return val return ret def radio_step_channel(self, *args): """ radio_step_channel <-1|1> Step forwards (1) or backwards (-1) in channel list. Works only when the 'channels' radio parameter was set. """ if len(args) != 1: raise TypeError('radio_step_channel takes 1 arguments (%d given)'%len(args)) return self.command('radio_step_channel', *args) def radio_set_channel(self, *args): """ radio_set_channel <channel> Switch to <channel>. The 'channels' radio parameter needs to be set. """ if len(args) != 1: raise TypeError('radio_set_channel takes 1 arguments (%d given)'%len(args)) return self.command('radio_set_channel', *args) def radio_set_freq(self, *args): """ radio_set_freq <frequency in MHz> Set the radio tuner frequency. """ if len(args) != 1: raise TypeError('radio_set_freq takes 1 arguments (%d given)'%len(args)) return self.command('radio_set_freq', *args) def radio_step_freq(self, *args): """ radio_step_freq <value> Tune frequency by the <value> (positive - up, negative - down). """ if len(args) != 1: raise TypeError('radio_step_freq takes 1 arguments (%d given)'%len(args)) return self.command('radio_step_freq', *args) def seek(self, *args): """ seek <value> [type] Seek to some place in the movie. 0 is a relative seek of +/- <value> seconds (default). 1 is a seek to <value> % in the movie. 2 is a seek to an absolute position of <value> seconds. """ if not (1 <= len(args) <= 2): raise TypeError('seek takes 2 arguments (%d given)'%len(args)) return self.command('seek', *args) def edl_mark(self, *args): """ edl_mark Write the current position into the EDL file. """ if len(args) != 0: raise TypeError('edl_mark takes 0 arguments (%d given)'%len(args)) return self.command('edl_mark', *args) def audio_delay(self, *args): """ audio_delay <value> [abs] Set/adjust the audio delay. If [abs] is not given or is zero, adjust the delay by <value> seconds. If [abs] is nonzero, set the delay to <value> seconds. """ if not (1 <= len(args) <= 2): raise TypeError('audio_delay takes 2 arguments (%d given)'%len(args)) return self.command('audio_delay', *args) def speed_incr(self, *args): """ speed_incr <value> Add <value> to the current playback speed. """ if len(args) != 1: raise TypeError('speed_incr takes 1 arguments (%d given)'%len(args)) return self.command('speed_incr', *args) def speed_mult(self, *args): """ speed_mult <value> Multiply the current speed by <value>. """ if len(args) != 1: raise TypeError('speed_mult takes 1 arguments (%d given)'%len(args)) return self.command('speed_mult', *args) def speed_set(self, *args): """ speed_set <value> Set the speed to <value>. """ if len(args) != 1: raise TypeError('speed_set takes 1 arguments (%d given)'%len(args)) return self.command('speed_set', *args) def quit(self, *args): """ quit [value] Quit MPlayer. The optional integer [value] is used as the return code for the mplayer process (default: 0). """ if not (0 <= len(args) <= 1): raise TypeError('quit takes 1 arguments (%d given)'%len(args)) return self.command('quit', *args) def pause(self, *args): """ pause Pause/unpause the playback. """ if len(args) != 0: raise TypeError('pause takes 0 arguments (%d given)'%len(args)) return self.command('pause', *args) def frame_step(self, *args): """ frame_step Play one frame, then pause again. """ if len(args) != 0: raise TypeError('frame_step takes 0 arguments (%d given)'%len(args)) return self.command('frame_step', *args) def pt_step(self, *args): """ pt_step <value> [force] Go to the next/previous entry in the playtree. The sign of <value> tells the direction. If no entry is available in the given direction it will do nothing unless [force] is non-zero. """ if not (1 <= len(args) <= 2): raise TypeError('pt_step takes 2 arguments (%d given)'%len(args)) return self.command('pt_step', *args) def pt_up_step(self, *args): """ pt_up_step <value> [force] Similar to pt_step but jumps to the next/previous entry in the parent list. Useful to break out of the inner loop in the playtree. """ if not (1 <= len(args) <= 2): raise TypeError('pt_up_step takes 2 arguments (%d given)'%len(args)) return self.command('pt_up_step', *args) def alt_src_step(self, *args): """ alt_src_step <value> (ASX playlist only) When more than one source is available it selects the next/previous one. """ if len(args) != 1: raise TypeError('alt_src_step takes 1 arguments (%d given)'%len(args)) return self.command('alt_src_step', *args) def loop(self, *args): """ loop <value> [abs] Adjust/set how many times the movie should be looped. -1 means no loop, and 0 forever. """ if not (1 <= len(args) <= 2): raise TypeError('loop takes 2 arguments (%d given)'%len(args)) return self.command('loop', *args) def sub_delay(self, *args): """ sub_delay <value> [abs] Adjust the subtitle delay by +/- <value> seconds or set it to <value> seconds when [abs] is nonzero. """ if not (1 <= len(args) <= 2): raise TypeError('sub_delay takes 2 arguments (%d given)'%len(args)) return self.command('sub_delay', *args) def sub_step(self, *args): """ sub_step <value> Step forward in the subtitle list by <value> steps or backwards if <value> is negative. """ if not (1 <= len(args) <= 2): raise TypeError('sub_step takes 2 arguments (%d given)'%len(args)) return self.command('sub_step', *args) def osd(self, *args): """ osd [level] Toggle OSD mode or set it to [level] when [level] >= 0. """ if not (0 <= len(args) <= 1): raise TypeError('osd takes 1 arguments (%d given)'%len(args)) return self.command('osd', *args) def osd_show_text(self, *args): """ osd_show_text <string> [duration] [level] Show <string> on the OSD. """ if not (1 <= len(args) <= 3): raise TypeError('osd_show_text takes 3 arguments (%d given)'%len(args)) return self.command('osd_show_text', *args) def osd_show_property_te(self, *args): """ osd_show_property_text <string> [duration] [level] Show an expanded property string on the OSD, see -playing-msg for a description of the available expansions. If [duration] is >= 0 the text is shown for [duration] ms. [level] sets the minimum OSD level needed for the message to be visible (default: 0 - always show). """ if not (1 <= len(args) <= 3): raise TypeError('osd_show_property_te takes 3 arguments (%d given)'%len(args)) return self.command('osd_show_property_te', *args) def volume(self, *args): """ volume <value> [abs] Increase/decrease volume or set it to <value> if [abs] is nonzero. """ if not (1 <= len(args) <= 2): raise TypeError('volume takes 2 arguments (%d given)'%len(args)) return self.command('volume', *args) def balance(self, *args): """ balance(float, integer=None) """ if not (1 <= len(args) <= 2): raise TypeError('balance takes 2 arguments (%d given)'%len(args)) return self.command('balance', *args) def use_master(self, *args): """ use_master Switch volume control between master and PCM. """ if len(args) != 0: raise TypeError('use_master takes 0 arguments (%d given)'%len(args)) return self.command('use_master', *args) def mute(self, *args): """ mute [value] Toggle sound output muting or set it to [value] when [value] >= 0 (1 == on, 0 == off). """ if not (0 <= len(args) <= 1): raise TypeError('mute takes 1 arguments (%d given)'%len(args)) return self.command('mute', *args) def contrast(self, *args): """ contrast(integer, integer=None) """ if not (1 <= len(args) <= 2): raise TypeError('contrast takes 2 arguments (%d given)'%len(args)) return self.command('contrast', *args) def gamma(self, *args): """ gamma(integer, integer=None) """ if not (1 <= len(args) <= 2): raise TypeError('gamma takes 2 arguments (%d given)'%len(args)) return self.command('gamma', *args) def brightness(self, *args): """ brightness(integer, integer=None) """ if not (1 <= len(args) <= 2): raise TypeError('brightness takes 2 arguments (%d given)'%len(args)) return self.command('brightness', *args) def hue(self, *args): """ hue(integer, integer=None) """ if not (1 <= len(args) <= 2): raise TypeError('hue takes 2 arguments (%d given)'%len(args)) return self.command('hue', *args) def saturation(self, *args): """ saturation(integer, integer=None) """ if not (1 <= len(args) <= 2): raise TypeError('saturation takes 2 arguments (%d given)'%len(args)) return self.command('saturation', *args) def frame_drop(self, *args): """ frame_drop [value] Toggle/set frame dropping mode. """ if not (0 <= len(args) <= 1): raise TypeError('frame_drop takes 1 arguments (%d given)'%len(args)) return self.command('frame_drop', *args) def sub_pos(self, *args): """ sub_pos <value> [abs] Adjust/set subtitle position. """ if not (1 <= len(args) <= 2): raise TypeError('sub_pos takes 2 arguments (%d given)'%len(args)) return self.command('sub_pos', *args) def sub_alignment(self, *args): """ sub_alignment [value] Toggle/set subtitle alignment. 0 top alignment 1 center alignment 2 bottom alignment """ if not (0 <= len(args) <= 1): raise TypeError('sub_alignment takes 1 arguments (%d given)'%len(args)) return self.command('sub_alignment', *args) def sub_visibility(self, *args): """ sub_visibility [value] Toggle/set subtitle visibility. """ if not (0 <= len(args) <= 1): raise TypeError('sub_visibility takes 1 arguments (%d given)'%len(args)) return self.command('sub_visibility', *args) def sub_load(self, *args): """ sub_load <subtitle_file> Loads subtitles from <subtitle_file>. """ if len(args) != 1: raise TypeError('sub_load takes 1 arguments (%d given)'%len(args)) return self.command('sub_load', *args) def sub_remove(self, *args): """ sub_remove [value] If the [value] argument is present and non-negative, removes the subtitle file with index [value]. If the argument is omitted or negative, removes all subtitle files. """ if not (0 <= len(args) <= 1): raise TypeError('sub_remove takes 1 arguments (%d given)'%len(args)) return self.command('sub_remove', *args) def vobsub_lang(self, *args): """ vobsub_lang This is a stub linked to sub_select for backwards compatibility. """ if not (0 <= len(args) <= 1): raise TypeError('vobsub_lang takes 1 arguments (%d given)'%len(args)) return self.command('vobsub_lang', *args) def sub_select(self, *args): """ sub_select [value] Display subtitle with index [value]. Turn subtitle display off if [value] is -1 or greater than the highest available subtitle index. Cycle through the available subtitles if [value] is omitted or less than -1. Supported subtitle sources are -sub options on the command line, VOBsubs, DVD subtitles, and Ogg and Matroska text streams. This command is mainly for cycling all subtitles, if you want to set a specific subtitle, use sub_file, sub_vob, or sub_demux. """ if not (0 <= len(args) <= 1): raise TypeError('sub_select takes 1 arguments (%d given)'%len(args)) return self.command('sub_select', *args) def sub_log(self, *args): """ sub_log Logs the current or last displayed subtitle together with filename and time information to ~/.mplayer/subtitle_log. Intended purpose is to allow convenient marking of bogus subtitles which need to be fixed while watching the movie. """ if len(args) != 0: raise TypeError('sub_log takes 0 arguments (%d given)'%len(args)) return self.command('sub_log', *args) def sub_scale(self, *args): """ sub_scale <value> [abs] Adjust the subtitle size by +/- <value> or set it to <value> when [abs] is nonzero. """ if not (1 <= len(args) <= 2): raise TypeError('sub_scale takes 2 arguments (%d given)'%len(args)) return self.command('sub_scale', *args) def get_percent_pos(self, *args): """ get_percent_pos Print out the current position in the file, as integer percentage [0-100). """ if len(args) != 0: raise TypeError('get_percent_pos takes 0 arguments (%d given)'%len(args)) return self.command('get_percent_pos', *args) def get_time_pos(self, *args): """ get_time_pos Print out the current position in the file in seconds, as float. """ if len(args) != 0: raise TypeError('get_time_pos takes 0 arguments (%d given)'%len(args)) return self.command('get_time_pos', *args) def get_time_length(self, *args): """ get_time_length Print out the length of the current file in seconds. """ if len(args) != 0: raise TypeError('get_time_length takes 0 arguments (%d given)'%len(args)) return self.command('get_time_length', *args) def get_file_name(self, *args): """ get_file_name Print out the name of the current file. """ if len(args) != 0: raise TypeError('get_file_name takes 0 arguments (%d given)'%len(args)) return self.command('get_file_name', *args) def get_video_codec(self, *args): """ get_video_codec Print out the video codec name of the current file. """ if len(args) != 0: raise TypeError('get_video_codec takes 0 arguments (%d given)'%len(args)) return self.command('get_video_codec', *args) def get_video_bitrate(self, *args): """ get_video_bitrate Print out the video bitrate of the current file. """ if len(args) != 0: raise TypeError('get_video_bitrate takes 0 arguments (%d given)'%len(args)) return self.command('get_video_bitrate', *args) def get_video_resolution(self, *args): """ get_video_resolution Print out the video resolution of the current file. """ if len(args) != 0: raise TypeError('get_video_resolution takes 0 arguments (%d given)'%len(args)) return self.command('get_video_resolution', *args) def get_audio_codec(self, *args): """ get_audio_codec Print out the audio codec name of the current file. """ if len(args) != 0: raise TypeError('get_audio_codec takes 0 arguments (%d given)'%len(args)) return self.command('get_audio_codec', *args) def get_audio_bitrate(self, *args): """ get_audio_bitrate Print out the audio bitrate of the current file. """ if len(args) != 0: raise TypeError('get_audio_bitrate takes 0 arguments (%d given)'%len(args)) return self.command('get_audio_bitrate', *args) def get_audio_samples(self, *args): """ get_audio_samples Print out the audio frequency and number of channels of the current file. """ if len(args) != 0: raise TypeError('get_audio_samples takes 0 arguments (%d given)'%len(args)) return self.command('get_audio_samples', *args) def get_meta_title(self, *args): """ get_meta_title Print out the 'Title' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_title takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_title', *args) def get_meta_artist(self, *args): """ get_meta_artist Print out the 'Artist' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_artist takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_artist', *args) def get_meta_album(self, *args): """ get_meta_album Print out the 'Album' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_album takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_album', *args) def get_meta_year(self, *args): """ get_meta_year Print out the 'Year' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_year takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_year', *args) def get_meta_comment(self, *args): """ get_meta_comment Print out the 'Comment' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_comment takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_comment', *args) def get_meta_track(self, *args): """ get_meta_track Print out the 'Track Number' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_track takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_track', *args) def get_meta_genre(self, *args): """ get_meta_genre Print out the 'Genre' metadata of the current file. """ if len(args) != 0: raise TypeError('get_meta_genre takes 0 arguments (%d given)'%len(args)) return self.command('get_meta_genre', *args) def switch_audio(self, *args): """ switch_audio [value] (currently MPEG*, AVI, Matroska and streams handled by libavformat) Switch to the audio track with the ID [value]. Cycle through the available tracks if [value] is omitted or negative. """ if not (0 <= len(args) <= 1): raise TypeError('switch_audio takes 1 arguments (%d given)'%len(args)) return self.command('switch_audio', *args) def tv_start_scan(self, *args): """ tv_start_scan Start automatic TV channel scanning. """ if len(args) != 0: raise TypeError('tv_start_scan takes 0 arguments (%d given)'%len(args)) return self.command('tv_start_scan', *args) def tv_step_channel(self, *args): """ tv_step_channel <channel> Select next/previous TV channel. """ if len(args) != 1: raise TypeError('tv_step_channel takes 1 arguments (%d given)'%len(args)) return self.command('tv_step_channel', *args) def tv_step_norm(self, *args): """ tv_step_norm Change TV norm. """ if len(args) != 0: raise TypeError('tv_step_norm takes 0 arguments (%d given)'%len(args)) return self.command('tv_step_norm', *args) def tv_step_chanlist(self, *args): """ tv_step_chanlist Change channel list. """ if len(args) != 0: raise TypeError('tv_step_chanlist takes 0 arguments (%d given)'%len(args)) return self.command('tv_step_chanlist', *args) def tv_set_channel(self, *args): """ tv_set_channel <channel> Set the current TV channel. """ if len(args) != 1: raise TypeError('tv_set_channel takes 1 arguments (%d given)'%len(args)) return self.command('tv_set_channel', *args) def tv_last_channel(self, *args): """ tv_last_channel Set the current TV channel to the last one. """ if len(args) != 0: raise TypeError('tv_last_channel takes 0 arguments (%d given)'%len(args)) return self.command('tv_last_channel', *args) def tv_set_freq(self, *args): """ tv_set_freq <frequency in MHz> Set the TV tuner frequency. """ if len(args) != 1: raise TypeError('tv_set_freq takes 1 arguments (%d given)'%len(args)) return self.command('tv_set_freq', *args) def tv_step_freq(self, *args): """ tv_step_freq <frequency offset in MHz> Set the TV tuner frequency relative to current value. """ if len(args) != 1: raise TypeError('tv_step_freq takes 1 arguments (%d given)'%len(args)) return self.command('tv_step_freq', *args) def tv_set_norm(self, *args): """ tv_set_norm <norm> Set the TV tuner norm (PAL, SECAM, NTSC, ...). """ if len(args) != 1: raise TypeError('tv_set_norm takes 1 arguments (%d given)'%len(args)) return self.command('tv_set_norm', *args) def tv_set_brightness(self, *args): """ tv_set_brightness <-100 - 100> [abs] Set TV tuner brightness or adjust it if [abs] is set to 0. """ if not (1 <= len(args) <= 2): raise TypeError('tv_set_brightness takes 2 arguments (%d given)'%len(args)) return self.command('tv_set_brightness', *args) def tv_set_contrast(self, *args): """ tv_set_contrast <-100 -100> [abs] Set TV tuner contrast or adjust it if [abs] is set to 0. """ if not (1 <= len(args) <= 2): raise TypeError('tv_set_contrast takes 2 arguments (%d given)'%len(args)) return self.command('tv_set_contrast', *args) def tv_set_hue(self, *args): """ tv_set_hue <-100 - 100> [abs] Set TV tuner hue or adjust it if [abs] is set to 0. """ if not (1 <= len(args) <= 2): raise TypeError('tv_set_hue takes 2 arguments (%d given)'%len(args)) return self.command('tv_set_hue', *args) def tv_set_saturation(self, *args): """ tv_set_saturation <-100 - 100> [abs] Set TV tuner saturation or adjust it if [abs] is set to 0. """ if not (1 <= len(args) <= 2): raise TypeError('tv_set_saturation takes 2 arguments (%d given)'%len(args)) return self.command('tv_set_saturation', *args) def forced_subs_only(self, *args): """ forced_subs_only [value] Toggle/set forced subtitles only. """ if not (0 <= len(args) <= 1): raise TypeError('forced_subs_only takes 1 arguments (%d given)'%len(args)) return self.command('forced_subs_only', *args) def dvb_set_channel(self, *args): """ dvb_set_channel <channel_number> <card_number> Set DVB channel. """ if len(args) != 2: raise TypeError('dvb_set_channel takes 2 arguments (%d given)'%len(args)) return self.command('dvb_set_channel', *args) def switch_ratio(self, *args): """ switch_ratio [value] Change aspect ratio at runtime. [value] is the new aspect ratio expressed as a float (e.g. 1.77778 for 16/9). There might be problems with some video filters. """ if not (0 <= len(args) <= 1): raise TypeError('switch_ratio takes 1 arguments (%d given)'%len(args)) return self.command('switch_ratio', *args) def vo_fullscreen(self, *args): """ vo_fullscreen [value] Toggle/set fullscreen mode. """ if not (0 <= len(args) <= 1): raise TypeError('vo_fullscreen takes 1 arguments (%d given)'%len(args)) return self.command('vo_fullscreen', *args) def vo_ontop(self, *args): """ vo_ontop [value] Toggle/set stay-on-top. """ if not (0 <= len(args) <= 1): raise TypeError('vo_ontop takes 1 arguments (%d given)'%len(args)) return self.command('vo_ontop', *args) def file_filter(self, *args): """ file_filter(integer) """ if len(args) != 1: raise TypeError('file_filter takes 1 arguments (%d given)'%len(args)) return self.command('file_filter', *args) def vo_rootwin(self, *args): """ vo_rootwin [value] Toggle/set playback on the root window. """ if not (0 <= len(args) <= 1): raise TypeError('vo_rootwin takes 1 arguments (%d given)'%len(args)) return self.command('vo_rootwin', *args) def vo_border(self, *args): """ vo_border [value] Toggle/set borderless display. """ if not (0 <= len(args) <= 1): raise TypeError('vo_border takes 1 arguments (%d given)'%len(args)) return self.command('vo_border', *args) def screenshot(self, *args): """ screenshot <value> Take a screenshot. Requires the screenshot filter to be loaded. 0 Take a single screenshot. 1 Start/stop taking screenshot of each frame. """ if not (0 <= len(args) <= 1): raise TypeError('screenshot takes 1 arguments (%d given)'%len(args)) return self.command('screenshot', *args) def panscan(self, *args): """ panscan <-1.0 - 1.0> | <0.0 - 1.0> <abs> Increase or decrease the pan-and-scan range by <value>, 1.0 is the maximum. Negative values decrease the pan-and-scan range. If <abs> is != 0, then the pan-and scan range is interpreted as an absolute range. """ if not (1 <= len(args) <= 2): raise TypeError('panscan takes 2 arguments (%d given)'%len(args)) return self.command('panscan', *args) def switch_vsync(self, *args): """ switch_vsync [value] Toggle vsync (1 == on, 0 == off). If [value] is not provided, vsync status is inverted. """ if not (0 <= len(args) <= 1): raise TypeError('switch_vsync takes 1 arguments (%d given)'%len(args)) return self.command('switch_vsync', *args) def loadfile(self, *args): """ loadfile <file|url> <append> Load the given file/URL, stopping playback of the current file/URL. If <append> is nonzero playback continues and the file/URL is appended to the current playlist instead. """ if not (1 <= len(args) <= 2): raise TypeError('loadfile takes 2 arguments (%d given)'%len(args)) return self.command('loadfile', *args) def loadlist(self, *args): """ loadlist <file> <append> Load the given playlist file, stopping playback of the current file. If <append> is nonzero playback continues and the playlist file is appended to the current playlist instead. """ if not (1 <= len(args) <= 2): raise TypeError('loadlist takes 2 arguments (%d given)'%len(args)) return self.command('loadlist', *args) def run(self, *args): """ run <value> Run <value> as shell command. In OSD menu console mode stdout and stdin are through the video output driver. """ if len(args) != 1: raise TypeError('run takes 1 arguments (%d given)'%len(args)) return self.command('run', *args) def change_rectangle(self, *args): """ change_rectangle <val1> <val2> Change the position of the rectangle filter rectangle. <val1> Must be one of the following: 0 = width 1 = height 2 = x position 3 = y position <val2> If <val1> is 0 or 1: Integer amount to add/subtract from the width/height. Positive values add to width/height and negative values subtract from it. If <val1> is 2 or 3: Relative integer amount by which to move the upper left rectangle corner. Positive values move the rectangle right/down and negative values move the rectangle left/up. """ if len(args) != 2: raise TypeError('change_rectangle takes 2 arguments (%d given)'%len(args)) return self.command('change_rectangle', *args) def teletext_add_dec(self, *args): """ teletext_add_dec(string) """ if len(args) != 1: raise TypeError('teletext_add_dec takes 1 arguments (%d given)'%len(args)) return self.command('teletext_add_dec', *args) def teletext_go_link(self, *args): """ teletext_go_link <1-6> Follow given link on current teletext page. """ if len(args) != 1: raise TypeError('teletext_go_link takes 1 arguments (%d given)'%len(args)) return self.command('teletext_go_link', *args) def menu(self, *args): """ menu <command> Execute an OSD menu command. up Move cursor up. down Move cursor down. ok Accept selection. cancel Cancel selection. hide Hide the OSD menu. """ if len(args) != 1: raise TypeError('menu takes 1 arguments (%d given)'%len(args)) return self.command('menu', *args) def set_menu(self, *args): """ set_menu <menu_name> Display the menu named <menu_name>. """ if not (1 <= len(args) <= 2): raise TypeError('set_menu takes 2 arguments (%d given)'%len(args)) return self.command('set_menu', *args) def help(self, *args): """ help Displays help text, currently empty. """ if len(args) != 0: raise TypeError('help takes 0 arguments (%d given)'%len(args)) return self.command('help', *args) def exit(self, *args): """ exit Exits from OSD menu console. Unlike 'quit', does not quit MPlayer. """ if len(args) != 0: raise TypeError('exit takes 0 arguments (%d given)'%len(args)) return self.command('exit', *args) def hide(self, *args): """ hide Hides the OSD menu console. Clicking a menu command unhides it. Other keybindings act as usual. """ if not (0 <= len(args) <= 1): raise TypeError('hide takes 1 arguments (%d given)'%len(args)) return self.command('hide', *args) def get_vo_fullscreen(self, *args): """ get_vo_fullscreen Print out fullscreen status (1 == fullscreened, 0 == windowed). """ if len(args) != 0: raise TypeError('get_vo_fullscreen takes 0 arguments (%d given)'%len(args)) return self.command('get_vo_fullscreen', *args) def get_sub_visibility(self, *args): """ get_sub_visibility Print out subtitle visibility (1 == on, 0 == off). """ if len(args) != 0: raise TypeError('get_sub_visibility takes 0 arguments (%d given)'%len(args)) return self.command('get_sub_visibility', *args) def key_down_event(self, *args): """ key_down_event <value> Inject <value> key code event into MPlayer. """ if len(args) != 1: raise TypeError('key_down_event takes 1 arguments (%d given)'%len(args)) return self.command('key_down_event', *args) def set_property(self, *args): """ set_property <property> <value> Set a property. """ if len(args) != 2: raise TypeError('set_property takes 2 arguments (%d given)'%len(args)) return self.command('set_property', *args) def get_property(self, *args): """ get_property <property> Print out the current value of a property. """ if len(args) != 1: raise TypeError('get_property takes 1 arguments (%d given)'%len(args)) return self.command('get_property', *args) def step_property(self, *args): """ step_property <property> [value] [direction] Change a property by value, or increase by a default if value is not given or zero. The direction is reversed if direction is less than zero. """ if not (1 <= len(args) <= 3): raise TypeError('step_property takes 3 arguments (%d given)'%len(args)) return self.command('step_property', *args) def seek_chapter(self, *args): """ seek_chapter <value> [type] Seek to the start of a chapter. 0 is a relative seek of +/- <value> chapters (default). 1 is a seek to chapter <value>. """ if not (1 <= len(args) <= 2): raise TypeError('seek_chapter takes 2 arguments (%d given)'%len(args)) return self.command('seek_chapter', *args) def set_mouse_pos(self, *args): """ set_mouse_pos <x> <y> Tells MPlayer the coordinates of the mouse in the window. This command doesn't move the mouse! """ if len(args) != 2: raise TypeError('set_mouse_pos takes 2 arguments (%d given)'%len(args)) return self.command('set_mouse_pos', *args) #Properties prop_osdlevel = property( lambda self: self.get_property("osdlevel"), lambda self, val: self.set_property("osdlevel", val), doc = '''as -osdlevel''') prop_speed = property( lambda self: self.get_property("speed"), lambda self, val: self.set_property("speed", val), doc = '''as -speed''') prop_loop = property( lambda self: self.get_property("loop"), lambda self, val: self.set_property("loop", val), doc = '''as -loop''') prop_pause = property( lambda self: self.get_property("pause"), None, doc = '''1 if paused, use with pausing_keep_force''') prop_filename = property( lambda self: self.get_property("filename"), None, doc = '''file playing wo path''') prop_path = property( lambda self: self.get_property("path"), None, doc = '''file playing''') prop_demuxer = property( lambda self: self.get_property("demuxer"), None, doc = '''demuxer used''') prop_stream_pos = property( lambda self: self.get_property("stream_pos"), lambda self, val: self.set_property("stream_pos", val), doc = '''position in stream''') prop_stream_start = property( lambda self: self.get_property("stream_start"), None, doc = '''start pos in stream''') prop_stream_end = property( lambda self: self.get_property("stream_end"), None, doc = '''end pos in stream''') prop_stream_length = property( lambda self: self.get_property("stream_length"), None, doc = '''(end - start)''') prop_chapter = property( lambda self: self.get_property("chapter"), lambda self, val: self.set_property("chapter", val), doc = '''select chapter''') prop_chapters = property( lambda self: self.get_property("chapters"), None, doc = '''number of chapters''') prop_angle = property( lambda self: self.get_property("angle"), lambda self, val: self.set_property("angle", val), doc = '''select angle''') prop_length = property( lambda self: self.get_property("length"), None, doc = '''length of file in seconds''') prop_percent_pos = property( lambda self: self.get_property("percent_pos"), lambda self, val: self.set_property("percent_pos", val), doc = '''position in percent''') prop_time_pos = property( lambda self: self.get_property("time_pos"), lambda self, val: self.set_property("time_pos", val), doc = '''position in seconds''') prop_metadata = property( lambda self: self.get_property("metadata"), None, doc = '''list of metadata key/value''') prop_volume = property( lambda self: self.get_property("volume"), lambda self, val: self.set_property("volume", val), doc = '''change volume''') prop_balance = property( lambda self: self.get_property("balance"), lambda self, val: self.set_property("balance", val), doc = '''change audio balance''') prop_mute = property( lambda self: self.get_property("mute"), lambda self, val: self.set_property("mute", val), doc = None) prop_audio_delay = property( lambda self: self.get_property("audio_delay"), lambda self, val: self.set_property("audio_delay", val), doc = None) prop_audio_format = property( lambda self: self.get_property("audio_format"), None, doc = None) prop_audio_codec = property( lambda self: self.get_property("audio_codec"), None, doc = None) prop_audio_bitrate = property( lambda self: self.get_property("audio_bitrate"), None, doc = None) prop_samplerate = property( lambda self: self.get_property("samplerate"), None, doc = None) prop_channels = property( lambda self: self.get_property("channels"), None, doc = None) prop_switch_audio = property( lambda self: self.get_property("switch_audio"), lambda self, val: self.set_property("switch_audio", val), doc = '''select audio stream''') prop_switch_angle = property( lambda self: self.get_property("switch_angle"), lambda self, val: self.set_property("switch_angle", val), doc = '''select DVD angle''') prop_switch_title = property( lambda self: self.get_property("switch_title"), lambda self, val: self.set_property("switch_title", val), doc = '''select DVD title''') prop_fullscreen = property( lambda self: self.get_property("fullscreen"), lambda self, val: self.set_property("fullscreen", val), doc = None) prop_deinterlace = property( lambda self: self.get_property("deinterlace"), lambda self, val: self.set_property("deinterlace", val), doc = None) prop_ontop = property( lambda self: self.get_property("ontop"), lambda self, val: self.set_property("ontop", val), doc = None) prop_rootwin = property( lambda self: self.get_property("rootwin"), lambda self, val: self.set_property("rootwin", val), doc = None) prop_border = property( lambda self: self.get_property("border"), lambda self, val: self.set_property("border", val), doc = None) prop_framedropping = property( lambda self: self.get_property("framedropping"), lambda self, val: self.set_property("framedropping", val), doc = '''1 = soft, 2 = hard''') prop_gamma = property( lambda self: self.get_property("gamma"), lambda self, val: self.set_property("gamma", val), doc = None) prop_brightness = property( lambda self: self.get_property("brightness"), lambda self, val: self.set_property("brightness", val), doc = None) prop_contrast = property( lambda self: self.get_property("contrast"), lambda self, val: self.set_property("contrast", val), doc = None) prop_saturation = property( lambda self: self.get_property("saturation"), lambda self, val: self.set_property("saturation", val), doc = None) prop_hue = property( lambda self: self.get_property("hue"), lambda self, val: self.set_property("hue", val), doc = None) prop_panscan = property( lambda self: self.get_property("panscan"), lambda self, val: self.set_property("panscan", val), doc = None) prop_vsync = property( lambda self: self.get_property("vsync"), lambda self, val: self.set_property("vsync", val), doc = None) prop_video_format = property( lambda self: self.get_property("video_format"), None, doc = None) prop_video_codec = property( lambda self: self.get_property("video_codec"), None, doc = None) prop_video_bitrate = property( lambda self: self.get_property("video_bitrate"), None, doc = None) prop_width = property( lambda self: self.get_property("width"), None, doc = '''"display" width''') prop_height = property( lambda self: self.get_property("height"), None, doc = '''"display" height''') prop_fps = property( lambda self: self.get_property("fps"), None, doc = None) prop_aspect = property( lambda self: self.get_property("aspect"), None, doc = None) prop_switch_video = property( lambda self: self.get_property("switch_video"), lambda self, val: self.set_property("switch_video", val), doc = '''select video stream''') prop_switch_program = property( lambda self: self.get_property("switch_program"), lambda self, val: self.set_property("switch_program", val), doc = '''(see TAB default keybind)''') prop_sub = property( lambda self: self.get_property("sub"), lambda self, val: self.set_property("sub", val), doc = '''select subtitle stream''') prop_sub_source = property( lambda self: self.get_property("sub_source"), lambda self, val: self.set_property("sub_source", val), doc = '''select subtitle source''') prop_sub_file = property( lambda self: self.get_property("sub_file"), lambda self, val: self.set_property("sub_file", val), doc = '''select file subtitles''') prop_sub_vob = property( lambda self: self.get_property("sub_vob"), lambda self, val: self.set_property("sub_vob", val), doc = '''select vobsubs''') prop_sub_demux = property( lambda self: self.get_property("sub_demux"), lambda self, val: self.set_property("sub_demux", val), doc = '''select subs from demux''') prop_sub_delay = property( lambda self: self.get_property("sub_delay"), lambda self, val: self.set_property("sub_delay", val), doc = None) prop_sub_pos = property( lambda self: self.get_property("sub_pos"), lambda self, val: self.set_property("sub_pos", val), doc = '''subtitle position''') prop_sub_alignment = property( lambda self: self.get_property("sub_alignment"), lambda self, val: self.set_property("sub_alignment", val), doc = '''subtitle alignment''') prop_sub_visibility = property( lambda self: self.get_property("sub_visibility"), lambda self, val: self.set_property("sub_visibility", val), doc = '''show/hide subtitles''') prop_sub_forced_only = property( lambda self: self.get_property("sub_forced_only"), lambda self, val: self.set_property("sub_forced_only", val), doc = None) prop_sub_scale = property( lambda self: self.get_property("sub_scale"), lambda self, val: self.set_property("sub_scale", val), doc = '''subtitles font size''') prop_tv_brightness = property( lambda self: self.get_property("tv_brightness"), lambda self, val: self.set_property("tv_brightness", val), doc = None) prop_tv_contrast = property( lambda self: self.get_property("tv_contrast"), lambda self, val: self.set_property("tv_contrast", val), doc = None) prop_tv_saturation = property( lambda self: self.get_property("tv_saturation"), lambda self, val: self.set_property("tv_saturation", val), doc = None) prop_tv_hue = property( lambda self: self.get_property("tv_hue"), lambda self, val: self.set_property("tv_hue", val), doc = None) prop_teletext_page = property( lambda self: self.get_property("teletext_page"), lambda self, val: self.set_property("teletext_page", val), doc = None) prop_teletext_subpage = property( lambda self: self.get_property("teletext_subpage"), lambda self, val: self.set_property("teletext_subpage", val), doc = None) prop_teletext_mode = property( lambda self: self.get_property("teletext_mode"), lambda self, val: self.set_property("teletext_mode", val), doc = '''0 - off, 1 - on''') prop_teletext_format = property( lambda self: self.get_property("teletext_format"), lambda self, val: self.set_property("teletext_format", val), doc = '''0 - opaque, 1 - transparent, 2 - opaque inverted, 3 - transp. inv.''')
zicbee-mplayer
/zicbee-mplayer-0.9.1.tar.gz/zicbee-mplayer-0.9.1/zicbee_mplayer/mp.py
mp.py
__all__ = ['Player'] import gobject gobject.threads_init() from dbus import glib glib.init_threads() import mprisremote as MPRIS import sys class Player(object): _finished = False def __init__(self): #player_name = os.environ.get('MPRIS_REMOTE_PLAYER', '*') player_name = '*' self.mpris = MPRIS.MPRISRemote() try: self.mpris.find_player(player_name) except MPRIS.RequestedPlayerNotRunning, e: print >>sys.stderr, 'Player "%s" is not running, but the following players were found:' % player_name for n in self.mpris.players_running: print >>sys.stderr, " %s" % n.replace("org.mpris.", "") print >>sys.stderr, 'If you meant to use one of those players, ' \ 'set $MPRIS_REMOTE_PLAYER accordingly.' raise ValueError("Can't set selected backend") except MPRIS.NoPlayersRunning: print >>sys.stderr, "No MPRIS-compliant players found running." raise RuntimeError("No MPRIS player is running.") def set_cache(self, val): """ Sets the cache value in kilobytes """ pass def volume(self, val): """ Sets volume [0-100] """ self.mpris.player.VolumeSet(int(val)) return self.mpris.player.VolumeGet().real def seek(self, val): """ Seeks specified number of seconds (positive or negative) """ self.mpris.player.PositionSet(int(val)) def pause(self): """ Toggles pause mode """ self.mpris.player.Pause() def respawn(self): """ Restarts the player """ self.quit() # self.mpris.root.Quit() def load(self, uri): """ Loads the specified URI """ if uri[0] == '/': uri = 'file://'+uri try: self.mpris.player.Stop() for i in range(self.mpris.tracklist.GetLength()): self.mpris.tracklist.DelTrack(0) except Exception, e: print "ERR", repr(e) self.mpris.tracklist.AddTrack(uri, True) def quit(self): """ De-initialize player and wait for it to shut down """ self.mpris.player.Stop() for i in range(self.mpris.tracklist.GetLength()): self.mpris.tracklist.DelTrack(0) @property def position(self): """ returns the stream position, in seconds """ if self.mpris.player.GetStatus()[0].real == 2: # stopped return None return self.mpris.player.PositionGet().real if __name__ == '__main__': p = Player() p.load('http://172.16.41.222:9090/db/get/song.mp3?id=5ZR')
zicbee-mpris
/zicbee-mpris-1.0.tar.gz/zicbee-mpris-1.0/zicbee_mpris/core.py
core.py
usage = """ mpris-remote, written by Nick Welch <[email protected]> in 2008-2011. Homepage: http://incise.org/mpris-remote.html No copyright. This work is dedicated to the public domain. For full details, see http://creativecommons.org/publicdomain/zero/1.0/ USAGE: mpris-remote [command [args to command]] COMMANDS: [no command] prints a display of current player status, song playing, etc. prev[ious] go to previous track next go to next track stop stop playback play start playback pause pause playback trackinfo print metadata for current track trackinfo <track#> print metadata for given track trackinfo '*' print metadata for all tracks volume print volume volume <0..100> set volume repeat <true|false> set current track repeat on or off loop prints whether or not player will loop track list at end loop <true|false> sets whether or not player will loop track list at end random prints whether or not player will play randomly/shuffle random <true|false> sets whether or not player will play randomly/shuffle addtrack <uri> add track at specified uri (valid file types/protocols dependent on player) addtrack <uri> true add track at specified uri and start playing it now a uri can also be "-" which will read in filenames on stdin, one per line. (this applies to both variants of addtrack. the "playnow" variant will add+play the first track and continue adding the rest.) deltrack <track#> delete specified track clear clear playlist position print position within current track seek <time> seek to position in current track supported time formats: hh:mm:ss.ms | mm:ss.ms | ss | ss.ms | .ms hh:mm:ss | hh:mm | x% | x.x[x[x]...]% all are negatable to compute from end of track, e.g. -1:00. the "ss" format can be >60 and the ".ms" format can be >1000. <actually all of that is a lie -- right now you can only pass in an integer as milliseconds> tracknum print track number of current track numtracks print total number of tracks in track list playstatus print whether the player is playing, paused, or stopped, and print the random, repeat, and loop settings identity print identity of player (e.g. name and version) quit cause player to exit ENVIRONMENT VARIABLES: MPRIS_REMOTE_PLAYER If unset or set to "*", mpris-remote will communicate with the first player it finds registered under "org.mpris.*" through D-BUS. If you only have one MPRIS-compliant player running, then this will be fine. If you have more than one running, you will want to set this variable to the name of the player you want to connect to. For example, if set to foo, it will try to communicate with the player at "org.mpris.foo" and will fail if nothing exists at that name. NOTES: track numbers when used or displayed by commands always begin at zero, but the informational display when mpris-remote is called with no arguments starts them at one. (track "1/2" being the last track would make no sense.) """ import os, sys, re, time, urllib2, dbus org_mpris_re = re.compile('^org\.mpris\.([^.]+)$') class BadUserInput(Exception): pass # argument type/content validity checkers class is_int(object): @staticmethod def type_desc(remote): return 'an integer' def __init__(self, remote, arg): int(arg) class is_boolean(object): @staticmethod def type_desc(remote): return 'a boolean' def __init__(self, remote, arg): if arg not in ('true', 'false'): raise ValueError class is_zero_to_100(object): @staticmethod def type_desc(remote): return 'an integer within [0..100]' def __init__(self, remote, arg): if not 0 <= int(arg) <= 100: raise ValueError class is_track_num(object): @staticmethod def type_desc(remote): if remote.tracklist_len > 0: return 'an integer within [0..%d] (current playlist size is %d)' % (remote.tracklist_len-1, remote.tracklist_len) elif remote.tracklist_len == 0: return 'an integer within [0..<tracklist length>], ' \ 'although the current track list is empty, so ' \ 'no track number would currently be valid' else: return 'an integer within [0..<tracklist length>] (current tracklist length is unavailable)' def __init__(self, remote, arg): int(arg) if remote.tracklist_len == -1: return # not much we can do; just assume it's okay to pass along if not 0 <= int(arg) <= remote.tracklist_len-1: raise ValueError class is_track_num_or_star(object): @staticmethod def type_desc(remote): return is_track_num.type_desc(remote) + "\n\nOR a '*' to indicate all tracks" def __init__(self, remote, arg): if arg != '*': is_track_num(remote, arg) class is_valid_uri(object): @staticmethod def type_desc(remote): return 'a valid URI (media file, playlist file, stream URI, or directory)' def __init__(self, remote, arg): if arg.startswith('file://'): arg = urllib2.unquote(arg.partition('file://')[2]) # arbitrary uri, don't wanna hardcode possible protocols if re.match(r'\w+://.*', arg): return if os.path.isfile(arg) or os.path.isdir(arg) or arg == '-': return raise ValueError # wrong argument(s) explanation decorators def explain_numargs(*forms): def wrapper(meth): def new(self, *args): if len(args) not in forms: s = ' or '.join(map(str, forms)) raise BadUserInput("%s takes %s argument(s)." % (meth.func_name, s)) return meth(self, *args) new.func_name = meth.func_name return new return wrapper def explain_argtype(i, typeclass, optional=False): def wrapper(meth): def new(remote_self, *args): if not optional or len(args) > i: try: typeclass(remote_self, args[i]) except: raise BadUserInput("argument %d to %s must be %s." % (i+1, meth.func_name, typeclass.type_desc(remote_self))) return meth(remote_self, *args) new.func_name = meth.func_name return new return wrapper # and the core def format_time(rawms): min = rawms / 1000 / 60 sec = rawms / 1000 % 60 ms = rawms % 1000 return "%d:%02d.%03d" % (min, sec, ms) def playstatus_from_int(n): return ['playing', 'paused', 'stopped'][n] class NoTrackCurrentlySelected(Exception): pass def format_metadata(dct): lines = [] for k in sorted(dct.keys()): v = dct[k] if k == 'audio-bitrate': v = float(v) / 1000 if v % 1 < 0.01: v = int(v) else: v = "%.3f" % v if k == 'time': v = "%s (%s)" % (v, format_time(int(v) * 1000).split('.')[0]) if k == 'mtime': v = "%s (%s)" % (v, format_time(int(v))) lines.append("%s: %s" % (k, v)) return '\n'.join(lines) + '\n' class RequestedPlayerNotRunning(Exception): pass class NoPlayersRunning(Exception): pass class MPRISRemote(object): def __init__(self): self.bus = dbus.SessionBus() self.players_running = [ name for name in self.bus.list_names() if org_mpris_re.match(name) ] def find_player(self, requested_player_name): if not self.players_running: raise NoPlayersRunning() if requested_player_name == '*': self.player_name = org_mpris_re.match(self.players_running[0]).group(1) else: if 'org.mpris.%s' % requested_player_name not in self.players_running: raise RequestedPlayerNotRunning() self.player_name = requested_player_name root_obj = self.bus.get_object('org.mpris.%s' % self.player_name, '/') player_obj = self.bus.get_object('org.mpris.%s' % self.player_name, '/Player') tracklist_obj = self.bus.get_object('org.mpris.%s' % self.player_name, '/TrackList') self.root = dbus.Interface(root_obj, dbus_interface='org.freedesktop.MediaPlayer') self.player = dbus.Interface(player_obj, dbus_interface='org.freedesktop.MediaPlayer') self.tracklist = dbus.Interface(tracklist_obj, dbus_interface='org.freedesktop.MediaPlayer') try: self.tracklist_len = self.tracklist.GetLength() except dbus.exceptions.DBusException: # GetLength() not supported by player (BMPx for example) self.tracklist_len = -1 def _possible_names(self): return [ name for name in self.bus.list_names() if org_mpris_re.match(name) ] # commands # root @explain_numargs(0) def identity(self): print self.root.Identity() @explain_numargs(0) def quit(self): self.root.Quit() # player @explain_numargs(0) def prev(self): self.player.Prev() @explain_numargs(0) def previous(self): self.player.Prev() @explain_numargs(0) def next(self): self.player.Next() @explain_numargs(0) def stop(self): self.player.Stop() @explain_numargs(0) def play(self): self.player.Play() @explain_numargs(0) def pause(self): self.player.Pause() @explain_numargs(0, 1) @explain_argtype(0, is_zero_to_100, optional=True) def volume(self, vol=None): if vol is not None: self.player.VolumeSet(int(vol)) else: print self.player.VolumeGet() @explain_numargs(0) def position(self): print format_time(self.player.PositionGet()) @explain_numargs(1) @explain_argtype(0, is_int) def seek(self, pos): self.player.PositionSet(int(pos)) @explain_numargs(1) @explain_argtype(0, is_boolean) def repeat(self, on): if on == 'true': self.player.Repeat(True) elif on == 'false': self.player.Repeat(False) @explain_numargs(0) def playstatus(self): status = self.player.GetStatus() yield ("playing: %s\n" % playstatus_from_int(status[0]) + "random/shuffle: %s\n" % ("true" if status[1] else "false") + "repeat track: %s\n" % ("true" if status[2] else "false") + "repeat list: %s\n" % ("true" if status[3] else "false")) @explain_numargs(0, 1) @explain_argtype(0, is_track_num_or_star, optional=True) def trackinfo(self, track=None): if track == '*': for i in range(self.tracklist_len): meta = self.tracklist.GetMetadata(i) if meta is not None: yield format_metadata(self.tracklist.GetMetadata(i)) yield '\n' else: if track is not None: meta = self.tracklist.GetMetadata(int(track)) else: meta = self.player.GetMetadata() if meta is None: raise NoTrackCurrentlySelected() yield format_metadata(meta) # tracklist @explain_numargs(0) def clear(self): self.player.Stop() for i in range(self.tracklist.GetLength()): self.tracklist.DelTrack(0) @explain_numargs(1) @explain_argtype(0, is_track_num) def deltrack(self, pos): self.tracklist.DelTrack(int(pos)) @explain_numargs(1, 2) @explain_argtype(0, is_valid_uri) @explain_argtype(1, is_boolean, optional=True) def addtrack(self, uri, playnow='false'): playnow = playnow == 'true' if uri == '-': for i, line in enumerate(sys.stdin): path = line.rstrip('\r\n') if not path.strip(): continue if not (os.path.isfile(path) or os.path.isdir(path)): raise BadUserInput('not a file or directory: %s' % path) if playnow and i == 0: self.tracklist.AddTrack(path, True) else: self.tracklist.AddTrack(path, False) else: self.tracklist.AddTrack(uri, playnow) @explain_numargs(0) def tracknum(self): yield str(self.tracklist.GetCurrentTrack()) + '\n' @explain_numargs(0) def numtracks(self): yield str(self.tracklist.GetLength()) + '\n' @explain_numargs(0, 1) @explain_argtype(0, is_boolean, optional=True) def loop(self, on=None): if on == 'true': self.tracklist.SetLoop(True) elif on == 'false': self.tracklist.SetLoop(False) else: try: status = self.player.GetStatus() except dbus.exceptions.DBusException: print >>sys.stderr, "Player does not support checking loop status." else: yield ("true" if status[3] else "false") + '\n' @explain_numargs(0, 1) @explain_argtype(0, is_boolean, optional=True) def random(self, on=None): if on == 'true': self.tracklist.SetRandom(True) elif on == 'false': self.tracklist.SetRandom(False) else: try: status = self.player.GetStatus() except dbus.exceptions.DBusException: print >>sys.stderr, "Player does not support checking random status." else: yield ("true" if status[1] else "false") + '\n' def verbose_status(self): # to be compatible with a wide array of implementations (some very # incorrect/incomplete), we have to do a LOT of extra work here. output = '' try: status = self.player.GetStatus() except dbus.exceptions.DBusException: status = None try: status[0] # dragon player returns a single int, which is wrong except TypeError: status = None try: curtrack = self.tracklist.GetCurrentTrack() except dbus.exceptions.DBusException: curtrack = None try: pos = self.player.PositionGet() except dbus.exceptions.DBusException: pos = None try: meta = self.player.GetMetadata() meta = dict(meta) if meta else {} except dbus.exceptions.DBusException: meta = {} if 'mtime' in meta: mtime = int(meta['mtime']) if abs(mtime - time.time()) < 60*60*24*365*5: # if the mtime is within 5 years of right now, which would mean the # song is thousands of hours long, then i'm gonna assume that the # player is incorrectly using this field for the file's mtime, not # the song length. (bmpx does this as of january 2008) del meta['mtime'] # and also, if we know it's bmp, then we can swipe the time field if self.player_name == 'bmp': meta['mtime'] = meta['time'] * 1000 have_status = (status is not None) have_curtrack = (curtrack is not None) have_listlen = (self.tracklist_len >= 0) have_player_info = (have_status or have_curtrack or have_listlen) have_pos = (pos is not None) have_mtime = ('mtime' in meta) have_tracknum = ('tracknumber' in meta) have_song_info = (have_pos or have_mtime or have_tracknum) ## if have_player_info: output += '[' if have_status: output += "%s" % playstatus_from_int(status[0]) if have_curtrack: output += ' ' if have_curtrack: output += str(curtrack+1) if have_listlen: output += '/' if have_listlen: output += str(self.tracklist_len) if have_player_info: output += ']' ## if have_player_info and have_song_info: output += ' ' ## if have_pos or have_mtime: output += '@ ' if have_pos: output += format_time(pos).split('.')[0] elif have_mtime: output += '?' if have_mtime: output += '/' output += format_time(meta['mtime']).split('.')[0] if have_tracknum: output += ' - #%s' % meta['tracknumber'] if have_player_info or have_song_info: output += '\n' ## if 'artist' in meta: output += ' artist: ' + meta['artist'] + '\n' if 'title' in meta: output += ' title: ' + meta['title'] + '\n' if 'album' in meta: output += ' album: ' + meta['album'] + '\n' if have_status: output += '[repeat %s] [random %s] [loop %s]\n' % ( "on" if status[2] else "off", "on" if status[1] else "off", "on" if status[3] else "off", ) return output if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] in ('-h', '--help', '-?'): print usage raise SystemExit(0) player_name = os.environ.get('MPRIS_REMOTE_PLAYER', '*') remote = MPRISRemote() try: remote.find_player(player_name) except RequestedPlayerNotRunning, e: print >>sys.stderr, 'Player "%s" is not running, but the following players were found:' % player_name for n in remote.players_running: print >>sys.stderr, " %s" % n.replace("org.mpris.", "") print >>sys.stderr, 'If you meant to use one of those players, ' \ 'set $MPRIS_REMOTE_PLAYER accordingly.' raise SystemExit(1) except NoPlayersRunning: print >>sys.stderr, "No MPRIS-compliant players found running." raise SystemExit(1) import locale encoding = sys.stdout.encoding or locale.getpreferredencoding() or 'ascii' if len(sys.argv) == 1: method_name = 'verbose_status' args = [] else: method_name = sys.argv[1] args = sys.argv[2:] try: output_generator = getattr(remote, method_name)(*args) or [] for chunk in output_generator: sys.stdout.write(chunk.encode(encoding, 'replace')) except BadUserInput, e: print >>sys.stderr, e raise SystemExit(1) except NoTrackCurrentlySelected: print >>sys.stderr, "No track is currently selected." except KeyboardInterrupt: raise SystemExit(2)
zicbee-mpris
/zicbee-mpris-1.0.tar.gz/zicbee-mpris-1.0/zicbee_mpris/mprisremote.py
mprisremote.py
# # Python ctypes bindings for VLC # Copyright (C) 2009 the VideoLAN team # $Id: $ # # Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr> # # 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. # """This module provides bindings for the U{libvlc<http://wiki.videolan.org/ExternalAPI>} and U{MediaControl<http://wiki.videolan.org/MediaControlAPI>} APIs. You can find documentation at U{http://www.advene.org/download/python-ctypes/}. Basically, the most important class is L{Instance}, which is used to create a libvlc Instance. From this instance, you can then create L{MediaPlayer} and L{MediaListPlayer} instances. """ import logging import ctypes import sys build_date="Fri Sep 11 15:21:38 2009" # Used for win32 and MacOS X detected_plugin_path=None if sys.platform == 'linux2': try: dll=ctypes.CDLL('libvlc.so') except OSError: for n in reversed(xrange(3)): try: dll=ctypes.CDLL('libvlc.so.%d'%n) break except OSError: pass else: raise OSError('Unable to find libvlc.so') elif sys.platform == 'win32': import ctypes.util import os detected_plugin_path=None path=ctypes.util.find_library('libvlc.dll') if path is None: # Try to use registry settings import _winreg detected_plugin_path_found = None subkey, name = 'Software\\VideoLAN\\VLC','InstallDir' for hkey in _winreg.HKEY_LOCAL_MACHINE, _winreg.HKEY_CURRENT_USER: try: reg = _winreg.OpenKey(hkey, subkey) detected_plugin_path_found, type_id = _winreg.QueryValueEx(reg, name) _winreg.CloseKey(reg) break except _winreg.error: pass if detected_plugin_path_found: detected_plugin_path = detected_plugin_path_found else: # Try a standard location. p='c:\\Program Files\\VideoLAN\\VLC\\libvlc.dll' if os.path.exists(p): detected_plugin_path=os.path.dirname(p) os.chdir(detected_plugin_path) # If chdir failed, this will not work and raise an exception path='libvlc.dll' else: detected_plugin_path=os.path.dirname(path) dll=ctypes.CDLL(path) elif sys.platform == 'darwin': # FIXME: should find a means to configure path d='/Applications/VLC.app' import os if os.path.exists(d): dll=ctypes.CDLL(d+'/Contents/MacOS/lib/libvlc.2.dylib') detected_plugin_path=d+'/Contents/MacOS/modules' else: # Hope some default path is set... dll=ctypes.CDLL('libvlc.2.dylib') # # Generated enum types. # class EventType(ctypes.c_ulong): """ libvlc_core LibVLC Available Events """ _names={ 1: 'MediaSubItemAdded', 2: 'MediaDurationChanged', 3: 'MediaPreparsedChanged', 4: 'MediaFreed', 5: 'MediaStateChanged', 6: 'MediaPlayerNothingSpecial', 7: 'MediaPlayerOpening', 8: 'MediaPlayerBuffering', 9: 'MediaPlayerPlaying', 10: 'MediaPlayerPaused', 11: 'MediaPlayerStopped', 12: 'MediaPlayerForward', 13: 'MediaPlayerBackward', 14: 'MediaPlayerEndReached', 15: 'MediaPlayerEncounteredError', 16: 'MediaPlayerTimeChanged', 17: 'MediaPlayerPositionChanged', 18: 'MediaPlayerSeekableChanged', 19: 'MediaPlayerPausableChanged', 20: 'MediaListItemAdded', 21: 'MediaListWillAddItem', 22: 'MediaListItemDeleted', 23: 'MediaListWillDeleteItem', 24: 'MediaListViewItemAdded', 25: 'MediaListViewWillAddItem', 26: 'MediaListViewItemDeleted', 27: 'MediaListViewWillDeleteItem', 28: 'MediaListPlayerPlayed', 29: 'MediaListPlayerNextItemSet', 30: 'MediaListPlayerStopped', 31: 'MediaDiscovererStarted', 32: 'MediaDiscovererEnded', 33: 'MediaPlayerTitleChanged', 34: 'MediaPlayerSnapshotTaken', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) EventType.MediaSubItemAdded=EventType(1) EventType.MediaDurationChanged=EventType(2) EventType.MediaPreparsedChanged=EventType(3) EventType.MediaFreed=EventType(4) EventType.MediaStateChanged=EventType(5) EventType.MediaPlayerNothingSpecial=EventType(6) EventType.MediaPlayerOpening=EventType(7) EventType.MediaPlayerBuffering=EventType(8) EventType.MediaPlayerPlaying=EventType(9) EventType.MediaPlayerPaused=EventType(10) EventType.MediaPlayerStopped=EventType(11) EventType.MediaPlayerForward=EventType(12) EventType.MediaPlayerBackward=EventType(13) EventType.MediaPlayerEndReached=EventType(14) EventType.MediaPlayerEncounteredError=EventType(15) EventType.MediaPlayerTimeChanged=EventType(16) EventType.MediaPlayerPositionChanged=EventType(17) EventType.MediaPlayerSeekableChanged=EventType(18) EventType.MediaPlayerPausableChanged=EventType(19) EventType.MediaListItemAdded=EventType(20) EventType.MediaListWillAddItem=EventType(21) EventType.MediaListItemDeleted=EventType(22) EventType.MediaListWillDeleteItem=EventType(23) EventType.MediaListViewItemAdded=EventType(24) EventType.MediaListViewWillAddItem=EventType(25) EventType.MediaListViewItemDeleted=EventType(26) EventType.MediaListViewWillDeleteItem=EventType(27) EventType.MediaListPlayerPlayed=EventType(28) EventType.MediaListPlayerNextItemSet=EventType(29) EventType.MediaListPlayerStopped=EventType(30) EventType.MediaDiscovererStarted=EventType(31) EventType.MediaDiscovererEnded=EventType(32) EventType.MediaPlayerTitleChanged=EventType(33) EventType.MediaPlayerSnapshotTaken=EventType(34) class Meta(ctypes.c_ulong): """ libvlc_media LibVLC Media Meta """ _names={ 0: 'Title', 1: 'Artist', 2: 'Genre', 3: 'Copyright', 4: 'Album', 5: 'TrackNumber', 6: 'Description', 7: 'Rating', 8: 'Date', 9: 'Setting', 10: 'URL', 11: 'Language', 12: 'NowPlaying', 13: 'Publisher', 14: 'EncodedBy', 15: 'ArtworkURL', 16: 'TrackID', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) Meta.Title=Meta(0) Meta.Artist=Meta(1) Meta.Genre=Meta(2) Meta.Copyright=Meta(3) Meta.Album=Meta(4) Meta.TrackNumber=Meta(5) Meta.Description=Meta(6) Meta.Rating=Meta(7) Meta.Date=Meta(8) Meta.Setting=Meta(9) Meta.URL=Meta(10) Meta.Language=Meta(11) Meta.NowPlaying=Meta(12) Meta.Publisher=Meta(13) Meta.EncodedBy=Meta(14) Meta.ArtworkURL=Meta(15) Meta.TrackID=Meta(16) class State(ctypes.c_ulong): """Note the order of libvlc_state_t enum must match exactly the order of See mediacontrol_PlayerStatus, See input_state_e enums, and VideoLAN.LibVLC.State (at bindings/cil/src/media.cs). Expected states by web plugins are: IDLE/CLOSE=0, OPENING=1, BUFFERING=2, PLAYING=3, PAUSED=4, STOPPING=5, ENDED=6, ERROR=7 """ _names={ 0: 'NothingSpecial', 1: 'Opening', 2: 'Buffering', 3: 'Playing', 4: 'Paused', 5: 'Stopped', 6: 'Ended', 7: 'Error', 8: 'Closed', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) State.NothingSpecial=State(0) State.Opening=State(1) State.Buffering=State(2) State.Playing=State(3) State.Paused=State(4) State.Stopped=State(5) State.Ended=State(6) State.Error=State(7) class AudioOutputDeviceTypes(ctypes.c_ulong): """Audio device types """ _names={ -1: 'Error', 1: 'Mono', 2: 'Stereo', 4: '_2F2R', 5: '_3F2R', 6: '_5_1', 7: '_6_1', 8: '_7_1', 10: 'SPDIF', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) AudioOutputDeviceTypes.Error=AudioOutputDeviceTypes(-1) AudioOutputDeviceTypes.Mono=AudioOutputDeviceTypes(1) AudioOutputDeviceTypes.Stereo=AudioOutputDeviceTypes(2) AudioOutputDeviceTypes._2F2R=AudioOutputDeviceTypes(4) AudioOutputDeviceTypes._3F2R=AudioOutputDeviceTypes(5) AudioOutputDeviceTypes._5_1=AudioOutputDeviceTypes(6) AudioOutputDeviceTypes._6_1=AudioOutputDeviceTypes(7) AudioOutputDeviceTypes._7_1=AudioOutputDeviceTypes(8) AudioOutputDeviceTypes.SPDIF=AudioOutputDeviceTypes(10) class AudioOutputChannel(ctypes.c_ulong): """Audio channels """ _names={ -1: 'Error', 1: 'Stereo', 2: 'RStereo', 3: 'Left', 4: 'Right', 5: 'Dolbys', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) AudioOutputChannel.Error=AudioOutputChannel(-1) AudioOutputChannel.Stereo=AudioOutputChannel(1) AudioOutputChannel.RStereo=AudioOutputChannel(2) AudioOutputChannel.Left=AudioOutputChannel(3) AudioOutputChannel.Right=AudioOutputChannel(4) AudioOutputChannel.Dolbys=AudioOutputChannel(5) class PositionOrigin(ctypes.c_ulong): """A position may have different origins: - absolute counts from the movie start - relative counts from the current position - modulo counts from the current position and wraps at the end of the movie """ _names={ 0: 'AbsolutePosition', 1: 'RelativePosition', 2: 'ModuloPosition', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) PositionOrigin.AbsolutePosition=PositionOrigin(0) PositionOrigin.RelativePosition=PositionOrigin(1) PositionOrigin.ModuloPosition=PositionOrigin(2) class PositionKey(ctypes.c_ulong): """Units available in mediacontrol Positions - ByteCount number of bytes - SampleCount number of frames - MediaTime time in milliseconds """ _names={ 0: 'ByteCount', 1: 'SampleCount', 2: 'MediaTime', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) PositionKey.ByteCount=PositionKey(0) PositionKey.SampleCount=PositionKey(1) PositionKey.MediaTime=PositionKey(2) class PlayerStatus(ctypes.c_ulong): """Possible player status Note the order of these enums must match exactly the order of libvlc_state_t and input_state_e enums. """ _names={ 0: 'UndefinedStatus', 1: 'InitStatus', 2: 'BufferingStatus', 3: 'PlayingStatus', 4: 'PauseStatus', 5: 'StopStatus', 6: 'EndStatus', 7: 'ErrorStatus', } def __repr__(self): return ".".join((self.__class__.__module__, self.__class__.__name__, self._names[self.value])) def __eq__(self, other): return ( (isinstance(other, ctypes.c_ulong) and self.value == other.value) or (isinstance(other, (int, long)) and self.value == other ) ) def __ne__(self, other): return not self.__eq__(other) PlayerStatus.UndefinedStatus=PlayerStatus(0) PlayerStatus.InitStatus=PlayerStatus(1) PlayerStatus.BufferingStatus=PlayerStatus(2) PlayerStatus.PlayingStatus=PlayerStatus(3) PlayerStatus.PauseStatus=PlayerStatus(4) PlayerStatus.StopStatus=PlayerStatus(5) PlayerStatus.EndStatus=PlayerStatus(6) PlayerStatus.ErrorStatus=PlayerStatus(7) # # End of generated enum types. # class ListPOINTER(object): '''Just like a POINTER but accept a list of ctype as an argument. ''' def __init__(self, etype): self.etype = etype def from_param(self, param): if isinstance(param, (list, tuple)): return (self.etype * len(param))(*param) class LibVLCException(Exception): """Python exception raised by libvlc methods. """ pass # From libvlc_structures.h # This is version-dependent, depending on the presence of libvlc_errmsg if hasattr(dll, 'libvlc_errmsg'): # New-style message passing class VLCException(ctypes.Structure): """libvlc exception. """ _fields_= [ ('raised', ctypes.c_int), ] @property def message(self): return dll.libvlc_errmsg() def init(self): libvlc_exception_init(self) def clear(self): libvlc_exception_clear(self) else: # Old-style exceptions class VLCException(ctypes.Structure): """libvlc exception. """ _fields_= [ ('raised', ctypes.c_int), ('code', ctypes.c_int), ('message', ctypes.c_char_p), ] def init(self): libvlc_exception_init(self) def clear(self): libvlc_exception_clear(self) class PlaylistItem(ctypes.Structure): _fields_= [ ('id', ctypes.c_int), ('uri', ctypes.c_char_p), ('name', ctypes.c_char_p), ] def __str__(self): return "PlaylistItem #%d %s (%uri)" % (self.id, self.name, self.uri) class LogMessage(ctypes.Structure): _fields_= [ ('size', ctypes.c_uint), ('severity', ctypes.c_int), ('type', ctypes.c_char_p), ('name', ctypes.c_char_p), ('header', ctypes.c_char_p), ('message', ctypes.c_char_p), ] def __init__(self): super(LogMessage, self).__init__() self.size=ctypes.sizeof(self) def __str__(self): return "vlc.LogMessage(%d:%s): %s" % (self.severity, self.type, self.message) class MediaControlPosition(ctypes.Structure): _fields_= [ ('origin', PositionOrigin), ('key', PositionKey), ('value', ctypes.c_longlong), ] def __init__(self, value=0, origin=None, key=None): # We override the __init__ method so that instanciating the # class with an int as parameter will create the appropriate # default position (absolute position, media time, with the # int as value). super(MediaControlPosition, self).__init__() self.value=value if origin is None: origin=PositionOrigin.AbsolutePosition if key is None: key=PositionKey.MediaTime self.origin=origin self.key=key def __str__(self): return "MediaControlPosition %ld (%s, %s)" % ( self.value, str(self.origin), str(self.key) ) @staticmethod def from_param(arg): if isinstance(arg, (int, long)): return MediaControlPosition(arg) else: return arg class MediaControlException(ctypes.Structure): _fields_= [ ('code', ctypes.c_int), ('message', ctypes.c_char_p), ] def init(self): mediacontrol_exception_init(self) def clear(self): mediacontrol_exception_free(self) class MediaControlStreamInformation(ctypes.Structure): _fields_= [ ('status', PlayerStatus), ('url', ctypes.c_char_p), ('position', ctypes.c_longlong), ('length', ctypes.c_longlong), ] def __str__(self): return "%s (%s) : %ld / %ld" % (self.url or "<No defined URL>", str(self.status), self.position, self.length) class RGBPicture(ctypes.Structure): _fields_= [ ('width', ctypes.c_int), ('height', ctypes.c_int), ('type', ctypes.c_uint32), ('date', ctypes.c_ulonglong), ('size', ctypes.c_int), ('data_pointer', ctypes.c_void_p), ] @property def data(self): return ctypes.string_at(self.data_pointer, self.size) def __str__(self): return "RGBPicture (%d, %d) - %ld ms - %d bytes" % (self.width, self.height, self.date, self.size) def free(self): mediacontrol_RGBPicture__free(self) def check_vlc_exception(result, func, args): """Error checking method for functions using an exception in/out parameter. """ ex=args[-1] if not isinstance(ex, (VLCException, MediaControlException)): logging.warn("python-vlc: error when processing function %s. Please report this as a bug to [email protected]" % str(func)) return result # Take into account both VLCException and MediacontrolException: c=getattr(ex, 'raised', getattr(ex, 'code', 0)) if c: raise LibVLCException(ex.message) return result ### End of header.py ### class AudioOutput(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_audio_output_list_release'): def list_release(self): """Free the list of available audio outputs """ return libvlc_audio_output_list_release(self) class EventManager(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_event_attach'): def event_attach(self, i_event_type, f_callback, user_data): """Register for an event notification. @param i_event_type: the desired event to which we want to listen @param f_callback: the function to call when i_event_type occurs @param user_data: user provided data to carry with the event """ e=VLCException() return libvlc_event_attach(self, i_event_type, f_callback, user_data, e) if hasattr(dll, 'libvlc_event_detach'): def event_detach(self, i_event_type, f_callback, p_user_data): """Unregister an event notification. @param i_event_type: the desired event to which we want to unregister @param f_callback: the function to call when i_event_type occurs @param p_user_data: user provided data to carry with the event """ e=VLCException() return libvlc_event_detach(self, i_event_type, f_callback, p_user_data, e) class Instance(object): """Create a new Instance instance. It may take as parameter either: - a string - a list of strings as first parameters - the parameters given as the constructor parameters (must be strings) - a MediaControl instance """ @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ def __new__(cls, *p): if p and p[0] == 0: return None elif p and isinstance(p[0], (int, long)): # instance creation from ctypes o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(p[0]) return o elif len(p) == 1 and isinstance(p[0], basestring): # Only 1 string parameter: should be a parameter line p=p[0].split(' ') elif len(p) == 1 and isinstance(p[0], (tuple, list)): p=p[0] if p and isinstance(p[0], MediaControl): return p[0].get_instance() else: if not p and detected_plugin_path is not None: # No parameters passed. Under win32 and MacOS, specify # the detected_plugin_path if present. p=[ 'vlc', '--plugin-path='+ detected_plugin_path ] e=VLCException() return libvlc_new(len(p), p, e) def media_player_new(self, uri=None): """Create a new Media Player object. @param uri: an optional URI to play in the player. """ e=VLCException() p=libvlc_media_player_new(self, e) if uri: p.set_media(self.media_new(uri)) p._instance=self return p def media_list_player_new(self): """Create an empty Media Player object """ e=VLCException() p=libvlc_media_list_player_new(self, e) p._instance=self return p if hasattr(dll, 'libvlc_get_vlc_id'): def get_vlc_id(self): """Return a libvlc instance identifier for legacy APIs. Use of this function is discouraged, you should convert your program to use the new API. @return: the instance identifier """ return libvlc_get_vlc_id(self) if hasattr(dll, 'libvlc_release'): def release(self): """Decrement the reference count of a libvlc instance, and destroy it if it reaches zero. """ return libvlc_release(self) if hasattr(dll, 'libvlc_retain'): def retain(self): """Increments the reference count of a libvlc instance. The initial reference count is 1 after libvlc_new() returns. """ return libvlc_retain(self) if hasattr(dll, 'libvlc_add_intf'): def add_intf(self, name): """Try to start a user interface for the libvlc instance. @param name: interface name, or NULL for default """ e=VLCException() return libvlc_add_intf(self, name, e) if hasattr(dll, 'libvlc_wait'): def wait(self): """Waits until an interface causes the instance to exit. You should start at least one interface first, using libvlc_add_intf(). """ return libvlc_wait(self) if hasattr(dll, 'libvlc_get_log_verbosity'): def get_log_verbosity(self): """Return the VLC messaging verbosity level. @return: verbosity level for messages """ e=VLCException() return libvlc_get_log_verbosity(self, e) if hasattr(dll, 'libvlc_set_log_verbosity'): def set_log_verbosity(self, level): """Set the VLC messaging verbosity level. @param level: log level """ e=VLCException() return libvlc_set_log_verbosity(self, level, e) if hasattr(dll, 'libvlc_log_open'): def log_open(self): """Open a VLC message log instance. @return: log message instance """ e=VLCException() return libvlc_log_open(self, e) if hasattr(dll, 'libvlc_media_new'): def media_new(self, psz_mrl): """Create a media with the given MRL. @param psz_mrl: the MRL to read @return: the newly created media """ e=VLCException() return libvlc_media_new(self, psz_mrl, e) if hasattr(dll, 'libvlc_media_new_as_node'): def media_new_as_node(self, psz_name): """Create a media as an empty node with the passed name. @param psz_name: the name of the node @return: the new empty media """ e=VLCException() return libvlc_media_new_as_node(self, psz_name, e) if hasattr(dll, 'libvlc_media_discoverer_new_from_name'): def media_discoverer_new_from_name(self, psz_name): """Discover media service by name. @param psz_name: service name @return: media discover object """ e=VLCException() return libvlc_media_discoverer_new_from_name(self, psz_name, e) if hasattr(dll, 'libvlc_media_library_new'): def media_library_new(self): """\ingroup libvlc LibVLC Media Library """ e=VLCException() return libvlc_media_library_new(self, e) if hasattr(dll, 'libvlc_media_list_new'): def media_list_new(self): """Create an empty media list. @return: empty media list """ e=VLCException() return libvlc_media_list_new(self, e) if hasattr(dll, 'libvlc_audio_output_list_get'): def audio_output_list_get(self): """Get the list of available audio outputs @return: list of available audio outputs, at the end free it with """ e=VLCException() return libvlc_audio_output_list_get(self, e) if hasattr(dll, 'libvlc_audio_output_set'): def audio_output_set(self, psz_name): """Set the audio output. Change will be applied after stop and play. @return: true if function succeded """ return libvlc_audio_output_set(self, psz_name) if hasattr(dll, 'libvlc_audio_output_device_count'): def audio_output_device_count(self, psz_audio_output): """Get count of devices for audio output, these devices are hardware oriented like analor or digital output of sound card @return: number of devices """ return libvlc_audio_output_device_count(self, psz_audio_output) if hasattr(dll, 'libvlc_audio_output_device_longname'): def audio_output_device_longname(self, psz_audio_output, i_device): """Get long name of device, if not available short name given @param psz_audio_output: - name of audio output, \see libvlc_audio_output_t @return: long name of device """ return libvlc_audio_output_device_longname(self, psz_audio_output, i_device) if hasattr(dll, 'libvlc_audio_output_device_id'): def audio_output_device_id(self, psz_audio_output, i_device): """Get id name of device @param psz_audio_output: - name of audio output, \see libvlc_audio_output_t @return: id name of device, use for setting device, need to be free after use """ return libvlc_audio_output_device_id(self, psz_audio_output, i_device) if hasattr(dll, 'libvlc_audio_output_device_set'): def audio_output_device_set(self, psz_audio_output, psz_device_id): """Set device for using @param psz_audio_output: - name of audio output, \see libvlc_audio_output_t """ return libvlc_audio_output_device_set(self, psz_audio_output, psz_device_id) if hasattr(dll, 'libvlc_audio_output_get_device_type'): def audio_output_get_device_type(self): """Get current audio device type. Device type describes something like character of output sound - stereo sound, 2.1, 5.1 etc @return: the audio devices type \see libvlc_audio_output_device_types_t """ e=VLCException() return libvlc_audio_output_get_device_type(self, e) if hasattr(dll, 'libvlc_audio_output_set_device_type'): def audio_output_set_device_type(self, device_type): """Set current audio device type. @param device_type: the audio device type, """ e=VLCException() return libvlc_audio_output_set_device_type(self, device_type, e) if hasattr(dll, 'libvlc_audio_toggle_mute'): def audio_toggle_mute(self): """Toggle mute status. """ e=VLCException() return libvlc_audio_toggle_mute(self, e) if hasattr(dll, 'libvlc_audio_get_mute'): def audio_get_mute(self): """Get current mute status. @return: the mute status (boolean) """ e=VLCException() return libvlc_audio_get_mute(self, e) if hasattr(dll, 'libvlc_audio_set_mute'): def audio_set_mute(self, status): """Set mute status. @param status: If status is true then mute, otherwise unmute """ e=VLCException() return libvlc_audio_set_mute(self, status, e) if hasattr(dll, 'libvlc_audio_get_volume'): def audio_get_volume(self): """Get current audio level. @return: the audio level (int) """ e=VLCException() return libvlc_audio_get_volume(self, e) if hasattr(dll, 'libvlc_audio_set_volume'): def audio_set_volume(self, i_volume): """Set current audio level. @param i_volume: the volume (int) """ e=VLCException() return libvlc_audio_set_volume(self, i_volume, e) if hasattr(dll, 'libvlc_audio_get_channel'): def audio_get_channel(self): """Get current audio channel. @return: the audio channel \see libvlc_audio_output_channel_t """ e=VLCException() return libvlc_audio_get_channel(self, e) if hasattr(dll, 'libvlc_audio_set_channel'): def audio_set_channel(self, channel): """Set current audio channel. @param channel: the audio channel, \see libvlc_audio_output_channel_t """ e=VLCException() return libvlc_audio_set_channel(self, channel, e) if hasattr(dll, 'libvlc_vlm_release'): def vlm_release(self): """Release the vlm instance related to the given libvlc_instance_t """ e=VLCException() return libvlc_vlm_release(self, e) if hasattr(dll, 'libvlc_vlm_add_broadcast'): def vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): """Add a broadcast, with one input. @param psz_name: the name of the new broadcast @param psz_input: the input MRL @param psz_output: the output MRL (the parameter to the "sout" variable) @param i_options: number of additional options @param ppsz_options: additional options @param b_enabled: boolean for enabling the new broadcast @param b_loop: Should this broadcast be played in loop ? """ e=VLCException() return libvlc_vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop, e) if hasattr(dll, 'libvlc_vlm_add_vod'): def vlm_add_vod(self, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux): """Add a vod, with one input. @param psz_name: the name of the new vod media @param psz_input: the input MRL @param i_options: number of additional options @param ppsz_options: additional options @param b_enabled: boolean for enabling the new vod @param psz_mux: the muxer of the vod media """ e=VLCException() return libvlc_vlm_add_vod(self, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux, e) if hasattr(dll, 'libvlc_vlm_del_media'): def vlm_del_media(self, psz_name): """Delete a media (VOD or broadcast). @param psz_name: the media to delete """ e=VLCException() return libvlc_vlm_del_media(self, psz_name, e) if hasattr(dll, 'libvlc_vlm_set_enabled'): def vlm_set_enabled(self, psz_name, b_enabled): """Enable or disable a media (VOD or broadcast). @param psz_name: the media to work on @param b_enabled: the new status """ e=VLCException() return libvlc_vlm_set_enabled(self, psz_name, b_enabled, e) if hasattr(dll, 'libvlc_vlm_set_output'): def vlm_set_output(self, psz_name, psz_output): """Set the output for a media. @param psz_name: the media to work on @param psz_output: the output MRL (the parameter to the "sout" variable) """ e=VLCException() return libvlc_vlm_set_output(self, psz_name, psz_output, e) if hasattr(dll, 'libvlc_vlm_set_input'): def vlm_set_input(self, psz_name, psz_input): """Set a media's input MRL. This will delete all existing inputs and add the specified one. @param psz_name: the media to work on @param psz_input: the input MRL """ e=VLCException() return libvlc_vlm_set_input(self, psz_name, psz_input, e) if hasattr(dll, 'libvlc_vlm_add_input'): def vlm_add_input(self, psz_name, psz_input): """Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on @param psz_input: the input MRL """ e=VLCException() return libvlc_vlm_add_input(self, psz_name, psz_input, e) if hasattr(dll, 'libvlc_vlm_set_loop'): def vlm_set_loop(self, psz_name, b_loop): """Set a media's loop status. @param psz_name: the media to work on @param b_loop: the new status """ e=VLCException() return libvlc_vlm_set_loop(self, psz_name, b_loop, e) if hasattr(dll, 'libvlc_vlm_set_mux'): def vlm_set_mux(self, psz_name, psz_mux): """Set a media's vod muxer. @param psz_name: the media to work on @param psz_mux: the new muxer """ e=VLCException() return libvlc_vlm_set_mux(self, psz_name, psz_mux, e) if hasattr(dll, 'libvlc_vlm_change_media'): def vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): """Edit the parameters of a media. This will delete all existing inputs and add the specified one. @param psz_name: the name of the new broadcast @param psz_input: the input MRL @param psz_output: the output MRL (the parameter to the "sout" variable) @param i_options: number of additional options @param ppsz_options: additional options @param b_enabled: boolean for enabling the new broadcast @param b_loop: Should this broadcast be played in loop ? """ e=VLCException() return libvlc_vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop, e) if hasattr(dll, 'libvlc_vlm_play_media'): def vlm_play_media(self, psz_name): """Play the named broadcast. @param psz_name: the name of the broadcast """ e=VLCException() return libvlc_vlm_play_media(self, psz_name, e) if hasattr(dll, 'libvlc_vlm_stop_media'): def vlm_stop_media(self, psz_name): """Stop the named broadcast. @param psz_name: the name of the broadcast """ e=VLCException() return libvlc_vlm_stop_media(self, psz_name, e) if hasattr(dll, 'libvlc_vlm_pause_media'): def vlm_pause_media(self, psz_name): """Pause the named broadcast. @param psz_name: the name of the broadcast """ e=VLCException() return libvlc_vlm_pause_media(self, psz_name, e) if hasattr(dll, 'libvlc_vlm_seek_media'): def vlm_seek_media(self, psz_name, f_percentage): """Seek in the named broadcast. @param psz_name: the name of the broadcast @param f_percentage: the percentage to seek to """ e=VLCException() return libvlc_vlm_seek_media(self, psz_name, f_percentage, e) if hasattr(dll, 'libvlc_vlm_show_media'): def vlm_show_media(self, psz_name): """Return information about the named broadcast. \bug will always return NULL @param psz_name: the name of the broadcast @return: string with information about named media """ e=VLCException() return libvlc_vlm_show_media(self, psz_name, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_position'): def vlm_get_media_instance_position(self, psz_name, i_instance): """Get vlm_media instance position by name or instance id @param psz_name: name of vlm media instance @param i_instance: instance id @return: position as float """ e=VLCException() return libvlc_vlm_get_media_instance_position(self, psz_name, i_instance, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_time'): def vlm_get_media_instance_time(self, psz_name, i_instance): """Get vlm_media instance time by name or instance id @param psz_name: name of vlm media instance @param i_instance: instance id @return: time as integer """ e=VLCException() return libvlc_vlm_get_media_instance_time(self, psz_name, i_instance, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_length'): def vlm_get_media_instance_length(self, psz_name, i_instance): """Get vlm_media instance length by name or instance id @param psz_name: name of vlm media instance @param i_instance: instance id @return: length of media item """ e=VLCException() return libvlc_vlm_get_media_instance_length(self, psz_name, i_instance, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_rate'): def vlm_get_media_instance_rate(self, psz_name, i_instance): """Get vlm_media instance playback rate by name or instance id @param psz_name: name of vlm media instance @param i_instance: instance id @return: playback rate """ e=VLCException() return libvlc_vlm_get_media_instance_rate(self, psz_name, i_instance, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_title'): def vlm_get_media_instance_title(self, psz_name, i_instance): """Get vlm_media instance title number by name or instance id \bug will always return 0 @param psz_name: name of vlm media instance @param i_instance: instance id @return: title as number """ e=VLCException() return libvlc_vlm_get_media_instance_title(self, psz_name, i_instance, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_chapter'): def vlm_get_media_instance_chapter(self, psz_name, i_instance): """Get vlm_media instance chapter number by name or instance id \bug will always return 0 @param psz_name: name of vlm media instance @param i_instance: instance id @return: chapter as number """ e=VLCException() return libvlc_vlm_get_media_instance_chapter(self, psz_name, i_instance, e) if hasattr(dll, 'libvlc_vlm_get_media_instance_seekable'): def vlm_get_media_instance_seekable(self, psz_name, i_instance): """Is libvlc instance seekable ? \bug will always return 0 @param psz_name: name of vlm media instance @param i_instance: instance id @return: 1 if seekable, 0 if not """ e=VLCException() return libvlc_vlm_get_media_instance_seekable(self, psz_name, i_instance, e) if hasattr(dll, 'mediacontrol_new_from_instance'): def mediacontrol_new_from_instance(self): """Create a MediaControl instance from an existing libvlc instance @return: a mediacontrol_Instance """ e=MediaControlException() return mediacontrol_new_from_instance(self, e) class Log(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ def __iter__(self): return self.get_iterator() def dump(self): return [ str(m) for m in self ] if hasattr(dll, 'libvlc_log_close'): def close(self): """Close a VLC message log instance. """ e=VLCException() return libvlc_log_close(self, e) if hasattr(dll, 'libvlc_log_count'): def count(self): """Returns the number of messages in a log instance. @return: number of log messages """ e=VLCException() return libvlc_log_count(self, e) def __len__(self): e=VLCException() return libvlc_log_count(self, e) if hasattr(dll, 'libvlc_log_clear'): def clear(self): """Clear a log instance. All messages in the log are removed. The log should be cleared on a regular basis to avoid clogging. """ e=VLCException() return libvlc_log_clear(self, e) if hasattr(dll, 'libvlc_log_get_iterator'): def get_iterator(self): """Allocate and returns a new iterator to messages in log. @return: log iterator object """ e=VLCException() return libvlc_log_get_iterator(self, e) class LogIterator(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ def __iter__(self): return self def next(self): if not self.has_next(): raise StopIteration buf=LogMessage() e=VLCException() ret=libvlc_log_iterator_next(self, buf, e) return ret.contents if hasattr(dll, 'libvlc_log_iterator_free'): def free(self): """Release a previoulsy allocated iterator. """ e=VLCException() return libvlc_log_iterator_free(self, e) if hasattr(dll, 'libvlc_log_iterator_has_next'): def has_next(self): """Return whether log iterator has more messages. @return: true if iterator has more message objects, else false """ e=VLCException() return libvlc_log_iterator_has_next(self, e) class Media(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_media_add_option'): def add_option(self, ppsz_options): """Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all" @param ppsz_options: the options (as a string) """ e=VLCException() return libvlc_media_add_option(self, ppsz_options, e) if hasattr(dll, 'libvlc_media_add_option_untrusted'): def add_option_untrusted(self, ppsz_options): """Add an option to the media from an untrusted source. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all" @param ppsz_options: the options (as a string) """ e=VLCException() return libvlc_media_add_option_untrusted(self, ppsz_options, e) if hasattr(dll, 'libvlc_media_retain'): def retain(self): """Retain a reference to a media descriptor object (libvlc_media_t). Use libvlc_media_release() to decrement the reference count of a media descriptor object. """ return libvlc_media_retain(self) if hasattr(dll, 'libvlc_media_release'): def release(self): """Decrement the reference count of a media descriptor object. If the reference count is 0, then libvlc_media_release() will release the media descriptor object. It will send out an libvlc_MediaFreed event to all listeners. If the media descriptor object has been released it should not be used again. """ return libvlc_media_release(self) if hasattr(dll, 'libvlc_media_get_mrl'): def get_mrl(self): """Get the media resource locator (mrl) from a media descriptor object @return: string with mrl of media descriptor object """ e=VLCException() return libvlc_media_get_mrl(self, e) if hasattr(dll, 'libvlc_media_duplicate'): def duplicate(self): """Duplicate a media descriptor object. """ return libvlc_media_duplicate(self) if hasattr(dll, 'libvlc_media_get_meta'): def get_meta(self, e_meta): """Read the meta of the media. @param e_meta_desc: the meta to read @return: the media's meta """ e=VLCException() return libvlc_media_get_meta(self, e_meta, e) if hasattr(dll, 'libvlc_media_get_state'): def get_state(self): """Get current state of media descriptor object. Possible media states are defined in libvlc_structures.c ( libvlc_NothingSpecial=0, libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused, libvlc_Stopped, libvlc_Ended, libvlc_Error). See libvlc_state_t @return: state of media descriptor object """ e=VLCException() return libvlc_media_get_state(self, e) if hasattr(dll, 'libvlc_media_subitems'): def subitems(self): """Get subitems of media descriptor object. This will increment the reference count of supplied media descriptor object. Use libvlc_media_list_release() to decrement the reference counting. @return: list of media descriptor subitems or NULL """ e=VLCException() return libvlc_media_subitems(self, e) if hasattr(dll, 'libvlc_media_event_manager'): def event_manager(self): """Get event manager from media descriptor object. NOTE: this function doesn't increment reference counting. @return: event manager object """ e=VLCException() return libvlc_media_event_manager(self, e) if hasattr(dll, 'libvlc_media_get_duration'): def get_duration(self): """Get duration of media descriptor object item. @return: duration of media item """ e=VLCException() return libvlc_media_get_duration(self, e) if hasattr(dll, 'libvlc_media_is_preparsed'): def is_preparsed(self): """Get preparsed status for media descriptor object. @return: true if media object has been preparsed otherwise it returns false """ e=VLCException() return libvlc_media_is_preparsed(self, e) if hasattr(dll, 'libvlc_media_set_user_data'): def set_user_data(self, p_new_user_data): """Sets media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a libvlc_media_t pointer @param p_new_user_data: pointer to user data """ e=VLCException() return libvlc_media_set_user_data(self, p_new_user_data, e) if hasattr(dll, 'libvlc_media_get_user_data'): def get_user_data(self): """Get media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a libvlc_media_t pointer """ e=VLCException() return libvlc_media_get_user_data(self, e) if hasattr(dll, 'libvlc_media_player_new_from_media'): def player_new_from_media(self): """Create a Media Player object from a Media """ e=VLCException() return libvlc_media_player_new_from_media(self, e) class MediaControl(object): """Create a new MediaControl instance It may take as parameter either: - a string - a list of strings as first parameters - the parameters given as the constructor parameters (must be strings) - a vlc.Instance """ @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ def __new__(cls, *p): if p and p[0] == 0: return None elif p and isinstance(p[0], (int, long)): # instance creation from ctypes o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(p[0]) return o elif len(p) == 1 and isinstance(p[0], basestring): # Only 1 string parameter: should be a parameter line p=p[0].split(' ') elif len(p) == 1 and isinstance(p[0], (tuple, list)): p=p[0] if p and isinstance(p[0], Instance): e=MediaControlException() return mediacontrol_new_from_instance(p[0], e) else: if not p and detected_plugin_path is not None: # No parameters passed. Under win32 and MacOS, specify # the detected_plugin_path if present. p=[ 'vlc', '--plugin-path='+ detected_plugin_path ] e=MediaControlException() return mediacontrol_new(len(p), p, e) def get_media_position(self, origin=PositionOrigin.AbsolutePosition, key=PositionKey.MediaTime): e=MediaControlException() p=mediacontrol_get_media_position(self, origin, key, e) if p: return p.contents else: return None def set_media_position(self, pos): """Set the media position. @param pos: a MediaControlPosition or an integer (in ms) """ if not isinstance(pos, MediaControlPosition): pos=MediaControlPosition(long(pos)) e=MediaControlException() mediacontrol_set_media_position(self, pos, e) def start(self, pos=0): """Start the player at the given position. @param pos: a MediaControlPosition or an integer (in ms) """ if not isinstance(pos, MediaControlPosition): pos=MediaControlPosition(long(pos)) e=MediaControlException() mediacontrol_start(self, pos, e) def snapshot(self, pos=0): """Take a snapshot. Note: the position parameter is not properly implemented. For the moment, the only valid position is the 0-relative position (i.e. the current position). @param pos: a MediaControlPosition or an integer (in ms) """ if not isinstance(pos, MediaControlPosition): pos=MediaControlPosition(long(pos)) e=MediaControlException() p=mediacontrol_snapshot(self, pos, e) if p: snap=p.contents # FIXME: there is a bug in the current mediacontrol_snapshot # implementation, which sets an incorrect date. # Workaround here: snap.date=self.get_media_position().value return snap else: return None def display_text(self, message='', begin=0, end=1000): """Display a caption between begin and end positions. @param message: the caption to display @param begin: the begin position @param end: the end position """ if not isinstance(begin, MediaControlPosition): begin=self.value2position(begin) if not isinstance(end, MediaControlPosition): end=self.value2position(end) e=MediaControlException() mediacontrol_display_text(self, message, begin, end, e) def get_stream_information(self, key=PositionKey.MediaTime): """Return information about the stream. """ e=MediaControlException() return mediacontrol_get_stream_information(self, key, e).contents if hasattr(dll, 'mediacontrol_get_libvlc_instance'): def get_instance(self): """Get the associated libvlc instance @return: a libvlc instance """ return mediacontrol_get_libvlc_instance(self) if hasattr(dll, 'mediacontrol_get_media_player'): def get_media_player(self): """Get the associated libvlc_media_player @return: a libvlc_media_player_t instance """ return mediacontrol_get_media_player(self) if hasattr(dll, 'mediacontrol_pause'): def pause(self): """Pause the movie at a given position """ e=MediaControlException() return mediacontrol_pause(self, e) if hasattr(dll, 'mediacontrol_resume'): def resume(self): """Resume the movie at a given position """ e=MediaControlException() return mediacontrol_resume(self, e) if hasattr(dll, 'mediacontrol_stop'): def stop(self): """Stop the movie at a given position """ e=MediaControlException() return mediacontrol_stop(self, e) if hasattr(dll, 'mediacontrol_exit'): def exit(self): """Exit the player """ return mediacontrol_exit(self) if hasattr(dll, 'mediacontrol_set_mrl'): def set_mrl(self, psz_file): """Set the MRL to be played. @param psz_file: the MRL """ e=MediaControlException() return mediacontrol_set_mrl(self, psz_file, e) if hasattr(dll, 'mediacontrol_get_mrl'): def get_mrl(self): """Get the MRL to be played. """ e=MediaControlException() return mediacontrol_get_mrl(self, e) if hasattr(dll, 'mediacontrol_sound_get_volume'): def sound_get_volume(self): """Get the current audio level, normalized in [0..100] @return: the volume """ e=MediaControlException() return mediacontrol_sound_get_volume(self, e) if hasattr(dll, 'mediacontrol_sound_set_volume'): def sound_set_volume(self, volume): """Set the audio level @param volume: the volume (normalized in [0..100]) """ e=MediaControlException() return mediacontrol_sound_set_volume(self, volume, e) if hasattr(dll, 'mediacontrol_set_visual'): def set_visual(self, visual_id): """Set the video output window @param visual_id: the Xid or HWND, depending on the platform """ e=MediaControlException() return mediacontrol_set_visual(self, visual_id, e) if hasattr(dll, 'mediacontrol_get_rate'): def get_rate(self): """Get the current playing rate, in percent @return: the rate """ e=MediaControlException() return mediacontrol_get_rate(self, e) if hasattr(dll, 'mediacontrol_set_rate'): def set_rate(self, rate): """Set the playing rate, in percent @param rate: the desired rate """ e=MediaControlException() return mediacontrol_set_rate(self, rate, e) if hasattr(dll, 'mediacontrol_get_fullscreen'): def get_fullscreen(self): """Get current fullscreen status @return: the fullscreen status """ e=MediaControlException() return mediacontrol_get_fullscreen(self, e) if hasattr(dll, 'mediacontrol_set_fullscreen'): def set_fullscreen(self, b_fullscreen): """Set fullscreen status @param b_fullscreen: the desired status """ e=MediaControlException() return mediacontrol_set_fullscreen(self, b_fullscreen, e) class MediaDiscoverer(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_media_discoverer_release'): def release(self): """Release media discover object. If the reference count reaches 0, then the object will be released. """ return libvlc_media_discoverer_release(self) if hasattr(dll, 'libvlc_media_discoverer_localized_name'): def localized_name(self): """Get media service discover object its localized name. @return: localized name """ return libvlc_media_discoverer_localized_name(self) if hasattr(dll, 'libvlc_media_discoverer_media_list'): def media_list(self): """Get media service discover media list. @return: list of media items """ return libvlc_media_discoverer_media_list(self) if hasattr(dll, 'libvlc_media_discoverer_event_manager'): def event_manager(self): """Get event manager from media service discover object. @return: event manager object. """ return libvlc_media_discoverer_event_manager(self) if hasattr(dll, 'libvlc_media_discoverer_is_running'): def is_running(self): """Query if media service discover object is running. @return: true if running, false if not """ return libvlc_media_discoverer_is_running(self) class MediaLibrary(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_media_library_release'): def release(self): """Release media library object. This functions decrements the reference count of the media library object. If it reaches 0, then the object will be released. """ return libvlc_media_library_release(self) if hasattr(dll, 'libvlc_media_library_retain'): def retain(self): """Retain a reference to a media library object. This function will increment the reference counting for this object. Use libvlc_media_library_release() to decrement the reference count. """ return libvlc_media_library_retain(self) if hasattr(dll, 'libvlc_media_library_load'): def load(self): """Load media library. """ e=VLCException() return libvlc_media_library_load(self, e) if hasattr(dll, 'libvlc_media_library_save'): def save(self): """Save media library. """ e=VLCException() return libvlc_media_library_save(self, e) if hasattr(dll, 'libvlc_media_library_media_list'): def media_list(self): """Get media library subitems. @return: media list subitems """ e=VLCException() return libvlc_media_library_media_list(self, e) class MediaList(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_media_list_release'): def release(self): """Release media list created with libvlc_media_list_new(). """ return libvlc_media_list_release(self) if hasattr(dll, 'libvlc_media_list_retain'): def retain(self): """Retain reference to a media list """ return libvlc_media_list_retain(self) if hasattr(dll, 'libvlc_media_list_set_media'): def set_media(self, p_mi): """Associate media instance with this media list instance. If another media instance was present it will be released. The libvlc_media_list_lock should NOT be held upon entering this function. @param p_mi: media instance to add """ e=VLCException() return libvlc_media_list_set_media(self, p_mi, e) if hasattr(dll, 'libvlc_media_list_media'): def media(self): """Get media instance from this media list instance. This action will increase the refcount on the media instance. The libvlc_media_list_lock should NOT be held upon entering this function. @return: media instance """ e=VLCException() return libvlc_media_list_media(self, e) if hasattr(dll, 'libvlc_media_list_add_media'): def add_media(self, p_mi): """Add media instance to media list The libvlc_media_list_lock should be held upon entering this function. @param p_mi: a media instance """ e=VLCException() return libvlc_media_list_add_media(self, p_mi, e) if hasattr(dll, 'libvlc_media_list_insert_media'): def insert_media(self, p_mi, i_pos): """Insert media instance in media list on a position The libvlc_media_list_lock should be held upon entering this function. @param p_mi: a media instance @param i_pos: position in array where to insert """ e=VLCException() return libvlc_media_list_insert_media(self, p_mi, i_pos, e) if hasattr(dll, 'libvlc_media_list_remove_index'): def remove_index(self, i_pos): """Remove media instance from media list on a position The libvlc_media_list_lock should be held upon entering this function. @param i_pos: position in array where to insert """ e=VLCException() return libvlc_media_list_remove_index(self, i_pos, e) if hasattr(dll, 'libvlc_media_list_count'): def count(self): """Get count on media list items The libvlc_media_list_lock should be held upon entering this function. @return: number of items in media list """ e=VLCException() return libvlc_media_list_count(self, e) def __len__(self): e=VLCException() return libvlc_media_list_count(self, e) if hasattr(dll, 'libvlc_media_list_item_at_index'): def item_at_index(self, i_pos): """List media instance in media list at a position The libvlc_media_list_lock should be held upon entering this function. @param i_pos: position in array where to insert @return: media instance at position i_pos and libvlc_media_retain() has been called to increase the refcount on this object. """ e=VLCException() return libvlc_media_list_item_at_index(self, i_pos, e) def __getitem__(self, i): e=VLCException() return libvlc_media_list_item_at_index(self, i, e) def __iter__(self): e=VLCException() for i in xrange(len(self)): yield self[i] if hasattr(dll, 'libvlc_media_list_index_of_item'): def index_of_item(self, p_mi): """Find index position of List media instance in media list. Warning: the function will return the first matched position. The libvlc_media_list_lock should be held upon entering this function. @param p_mi: media list instance @return: position of media instance """ e=VLCException() return libvlc_media_list_index_of_item(self, p_mi, e) if hasattr(dll, 'libvlc_media_list_is_readonly'): def is_readonly(self): """This indicates if this media list is read-only from a user point of view @return: 0 on readonly, 1 on readwrite """ return libvlc_media_list_is_readonly(self) if hasattr(dll, 'libvlc_media_list_lock'): def lock(self): """Get lock on media list items """ return libvlc_media_list_lock(self) if hasattr(dll, 'libvlc_media_list_unlock'): def unlock(self): """Release lock on media list items The libvlc_media_list_lock should be held upon entering this function. """ return libvlc_media_list_unlock(self) if hasattr(dll, 'libvlc_media_list_flat_view'): def flat_view(self): """Get a flat media list view of media list items @return: flat media list view instance """ e=VLCException() return libvlc_media_list_flat_view(self, e) if hasattr(dll, 'libvlc_media_list_hierarchical_view'): def hierarchical_view(self): """Get a hierarchical media list view of media list items @return: hierarchical media list view instance """ e=VLCException() return libvlc_media_list_hierarchical_view(self, e) if hasattr(dll, 'libvlc_media_list_hierarchical_node_view'): def hierarchical_node_view(self): """ """ e=VLCException() return libvlc_media_list_hierarchical_node_view(self, e) if hasattr(dll, 'libvlc_media_list_event_manager'): def event_manager(self): """Get libvlc_event_manager from this media list instance. The p_event_manager is immutable, so you don't have to hold the lock @return: libvlc_event_manager """ e=VLCException() return libvlc_media_list_event_manager(self, e) class MediaListPlayer(object): """Create a new MediaPlayer instance. It may take as parameter either: - a vlc.Instance - nothing """ @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ def __new__(cls, *p): if p and p[0] == 0: return None elif p and isinstance(p[0], (int, long)): # instance creation from ctypes o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(p[0]) return o elif len(p) == 1 and isinstance(p[0], (tuple, list)): p=p[0] if p and isinstance(p[0], Instance): return p[0].media_list_player_new() else: i=Instance() o=i.media_list_player_new() return o def get_instance(self): """Return the associated vlc.Instance. """ return self._instance if hasattr(dll, 'libvlc_media_list_player_release'): def release(self): """Release media_list_player. """ return libvlc_media_list_player_release(self) if hasattr(dll, 'libvlc_media_list_player_set_media_player'): def set_media_player(self, p_mi): """Replace media player in media_list_player with this instance. @param p_mi: media player instance """ e=VLCException() return libvlc_media_list_player_set_media_player(self, p_mi, e) if hasattr(dll, 'libvlc_media_list_player_set_media_list'): def set_media_list(self, p_mlist): """ """ e=VLCException() return libvlc_media_list_player_set_media_list(self, p_mlist, e) if hasattr(dll, 'libvlc_media_list_player_play'): def play(self): """Play media list """ e=VLCException() return libvlc_media_list_player_play(self, e) if hasattr(dll, 'libvlc_media_list_player_pause'): def pause(self): """Pause media list """ e=VLCException() return libvlc_media_list_player_pause(self, e) if hasattr(dll, 'libvlc_media_list_player_is_playing'): def is_playing(self): """Is media list playing? @return: true for playing and false for not playing """ e=VLCException() return libvlc_media_list_player_is_playing(self, e) if hasattr(dll, 'libvlc_media_list_player_get_state'): def get_state(self): """Get current libvlc_state of media list player @return: libvlc_state_t for media list player """ e=VLCException() return libvlc_media_list_player_get_state(self, e) if hasattr(dll, 'libvlc_media_list_player_play_item_at_index'): def play_item_at_index(self, i_index): """Play media list item at position index @param i_index: index in media list to play """ e=VLCException() return libvlc_media_list_player_play_item_at_index(self, i_index, e) def __getitem__(self, i): e=VLCException() return libvlc_media_list_player_play_item_at_index(self, i, e) def __iter__(self): e=VLCException() for i in xrange(len(self)): yield self[i] if hasattr(dll, 'libvlc_media_list_player_play_item'): def play_item(self, p_md): """ """ e=VLCException() return libvlc_media_list_player_play_item(self, p_md, e) if hasattr(dll, 'libvlc_media_list_player_stop'): def stop(self): """Stop playing media list """ e=VLCException() return libvlc_media_list_player_stop(self, e) if hasattr(dll, 'libvlc_media_list_player_next'): def next(self): """Play next item from media list """ e=VLCException() return libvlc_media_list_player_next(self, e) class MediaListView(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_media_list_view_retain'): def retain(self): """Retain reference to a media list view """ return libvlc_media_list_view_retain(self) if hasattr(dll, 'libvlc_media_list_view_release'): def release(self): """Release reference to a media list view. If the refcount reaches 0, then the object will be released. """ return libvlc_media_list_view_release(self) if hasattr(dll, 'libvlc_media_list_view_event_manager'): def event_manager(self): """Get libvlc_event_manager from this media list view instance. The p_event_manager is immutable, so you don't have to hold the lock @return: libvlc_event_manager """ return libvlc_media_list_view_event_manager(self) if hasattr(dll, 'libvlc_media_list_view_count'): def count(self): """Get count on media list view items @return: number of items in media list view """ e=VLCException() return libvlc_media_list_view_count(self, e) def __len__(self): e=VLCException() return libvlc_media_list_view_count(self, e) if hasattr(dll, 'libvlc_media_list_view_item_at_index'): def item_at_index(self, i_index): """List media instance in media list view at an index position @param i_index: index position in array where to insert @return: media instance at position i_pos and libvlc_media_retain() has been called to increase the refcount on this object. """ e=VLCException() return libvlc_media_list_view_item_at_index(self, i_index, e) def __getitem__(self, i): e=VLCException() return libvlc_media_list_view_item_at_index(self, i, e) def __iter__(self): e=VLCException() for i in xrange(len(self)): yield self[i] if hasattr(dll, 'libvlc_media_list_view_children_at_index'): def children_at_index(self, index): """ """ e=VLCException() return libvlc_media_list_view_children_at_index(self, index, e) if hasattr(dll, 'libvlc_media_list_view_children_for_item'): def children_for_item(self, p_md): """ """ e=VLCException() return libvlc_media_list_view_children_for_item(self, p_md, e) if hasattr(dll, 'libvlc_media_list_view_parent_media_list'): def parent_media_list(self): """ """ e=VLCException() return libvlc_media_list_view_parent_media_list(self, e) class MediaPlayer(object): """Create a new MediaPlayer instance. It may take as parameter either: - a string (media URI). In this case, a vlc.Instance will be created. - a vlc.Instance """ @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ def __new__(cls, *p): if p and p[0] == 0: return None elif p and isinstance(p[0], (int, long)): # instance creation from ctypes o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(p[0]) return o if p and isinstance(p[0], Instance): return p[0].media_player_new() else: i=Instance() o=i.media_player_new() if p: o.set_media(i.media_new(p[0])) return o def get_instance(self): """Return the associated vlc.Instance. """ return self._instance if hasattr(dll, 'libvlc_media_player_release'): def release(self): """Release a media_player after use Decrement the reference count of a media player object. If the reference count is 0, then libvlc_media_player_release() will release the media player object. If the media player object has been released, then it should not be used again. """ return libvlc_media_player_release(self) if hasattr(dll, 'libvlc_media_player_retain'): def retain(self): """Retain a reference to a media player object. Use libvlc_media_player_release() to decrement reference count. """ return libvlc_media_player_retain(self) if hasattr(dll, 'libvlc_media_player_set_media'): def set_media(self, p_md): """Set the media that will be used by the media_player. If any, previous md will be released. @param p_md: the Media. Afterwards the p_md can be safely """ e=VLCException() return libvlc_media_player_set_media(self, p_md, e) if hasattr(dll, 'libvlc_media_player_get_media'): def get_media(self): """Get the media used by the media_player. @return: the media associated with p_mi, or NULL if no """ e=VLCException() return libvlc_media_player_get_media(self, e) if hasattr(dll, 'libvlc_media_player_event_manager'): def event_manager(self): """Get the Event Manager from which the media player send event. @return: the event manager associated with p_mi """ e=VLCException() return libvlc_media_player_event_manager(self, e) if hasattr(dll, 'libvlc_media_player_is_playing'): def is_playing(self): """is_playing @return: 1 if the media player is playing, 0 otherwise """ e=VLCException() return libvlc_media_player_is_playing(self, e) if hasattr(dll, 'libvlc_media_player_play'): def play(self): """Play """ e=VLCException() return libvlc_media_player_play(self, e) if hasattr(dll, 'libvlc_media_player_pause'): def pause(self): """Pause """ e=VLCException() return libvlc_media_player_pause(self, e) if hasattr(dll, 'libvlc_media_player_stop'): def stop(self): """Stop """ e=VLCException() return libvlc_media_player_stop(self, e) if hasattr(dll, 'libvlc_media_player_set_nsobject'): def set_nsobject(self, drawable): """Set the agl handler where the media player should render its video output. @param drawable: the agl handler """ e=VLCException() return libvlc_media_player_set_nsobject(self, drawable, e) if hasattr(dll, 'libvlc_media_player_get_nsobject'): def get_nsobject(self): """Get the agl handler previously set with libvlc_media_player_set_agl(). @return: the agl handler or 0 if none where set """ return libvlc_media_player_get_nsobject(self) if hasattr(dll, 'libvlc_media_player_set_agl'): def set_agl(self, drawable): """Set the agl handler where the media player should render its video output. @param drawable: the agl handler """ e=VLCException() return libvlc_media_player_set_agl(self, drawable, e) if hasattr(dll, 'libvlc_media_player_get_agl'): def get_agl(self): """Get the agl handler previously set with libvlc_media_player_set_agl(). @return: the agl handler or 0 if none where set """ return libvlc_media_player_get_agl(self) if hasattr(dll, 'libvlc_media_player_set_xwindow'): def set_xwindow(self, drawable): """Set an X Window System drawable where the media player should render its video output. If LibVLC was built without X11 output support, then this has no effects. The specified identifier must correspond to an existing Input/Output class X11 window. Pixmaps are <b>not</b> supported. The caller shall ensure that the X11 server is the same as the one the VLC instance has been configured with. If XVideo is <b>not</b> used, it is assumed that the drawable has the following properties in common with the default X11 screen: depth, scan line pad, black pixel. This is a bug. @param drawable: the ID of the X window """ e=VLCException() return libvlc_media_player_set_xwindow(self, drawable, e) if hasattr(dll, 'libvlc_media_player_get_xwindow'): def get_xwindow(self): """Get the X Window System window identifier previously set with libvlc_media_player_set_xwindow(). Note that this will return the identifier even if VLC is not currently using it (for instance if it is playing an audio-only input). @return: an X window ID, or 0 if none where set. """ return libvlc_media_player_get_xwindow(self) if hasattr(dll, 'libvlc_media_player_set_hwnd'): def set_hwnd(self, drawable): """Set a Win32/Win64 API window handle (HWND) where the media player should render its video output. If LibVLC was built without Win32/Win64 API output support, then this has no effects. @param drawable: windows handle of the drawable """ e=VLCException() return libvlc_media_player_set_hwnd(self, drawable, e) if hasattr(dll, 'libvlc_media_player_get_hwnd'): def get_hwnd(self): """Get the Windows API window handle (HWND) previously set with libvlc_media_player_set_hwnd(). The handle will be returned even if LibVLC is not currently outputting any video to it. @return: a window handle or NULL if there are none. """ return libvlc_media_player_get_hwnd(self) if hasattr(dll, 'libvlc_media_player_get_length'): def get_length(self): """Get the current movie length (in ms). @return: the movie length (in ms). """ e=VLCException() return libvlc_media_player_get_length(self, e) if hasattr(dll, 'libvlc_media_player_get_time'): def get_time(self): """Get the current movie time (in ms). @return: the movie time (in ms). """ e=VLCException() return libvlc_media_player_get_time(self, e) if hasattr(dll, 'libvlc_media_player_set_time'): def set_time(self, the): """Set the movie time (in ms). @param the: movie time (in ms). """ e=VLCException() return libvlc_media_player_set_time(self, the, e) if hasattr(dll, 'libvlc_media_player_get_position'): def get_position(self): """Get movie position. @return: movie position """ e=VLCException() return libvlc_media_player_get_position(self, e) if hasattr(dll, 'libvlc_media_player_set_position'): def set_position(self, p_e): """Set movie position. @return: movie position """ e=VLCException() return libvlc_media_player_set_position(self, p_e, e) if hasattr(dll, 'libvlc_media_player_set_chapter'): def set_chapter(self, i_chapter): """Set movie chapter @param i_chapter: chapter number to play """ e=VLCException() return libvlc_media_player_set_chapter(self, i_chapter, e) if hasattr(dll, 'libvlc_media_player_get_chapter'): def get_chapter(self): """Get movie chapter @return: chapter number currently playing """ e=VLCException() return libvlc_media_player_get_chapter(self, e) if hasattr(dll, 'libvlc_media_player_get_chapter_count'): def get_chapter_count(self): """Get movie chapter count @return: number of chapters in movie """ e=VLCException() return libvlc_media_player_get_chapter_count(self, e) if hasattr(dll, 'libvlc_media_player_will_play'): def will_play(self): """ """ e=VLCException() return libvlc_media_player_will_play(self, e) if hasattr(dll, 'libvlc_media_player_get_chapter_count_for_title'): def get_chapter_count_for_title(self, i_title): """Get title chapter count @param i_title: title @return: number of chapters in title """ e=VLCException() return libvlc_media_player_get_chapter_count_for_title(self, i_title, e) if hasattr(dll, 'libvlc_media_player_set_title'): def set_title(self, i_title): """Set movie title @param i_title: title number to play """ e=VLCException() return libvlc_media_player_set_title(self, i_title, e) if hasattr(dll, 'libvlc_media_player_get_title'): def get_title(self): """Get movie title @return: title number currently playing """ e=VLCException() return libvlc_media_player_get_title(self, e) if hasattr(dll, 'libvlc_media_player_get_title_count'): def get_title_count(self): """Get movie title count @return: title number count """ e=VLCException() return libvlc_media_player_get_title_count(self, e) if hasattr(dll, 'libvlc_media_player_previous_chapter'): def previous_chapter(self): """Set previous chapter """ e=VLCException() return libvlc_media_player_previous_chapter(self, e) if hasattr(dll, 'libvlc_media_player_next_chapter'): def next_chapter(self): """Set next chapter """ e=VLCException() return libvlc_media_player_next_chapter(self, e) if hasattr(dll, 'libvlc_media_player_get_rate'): def get_rate(self): """Get movie play rate @return: movie play rate """ e=VLCException() return libvlc_media_player_get_rate(self, e) if hasattr(dll, 'libvlc_media_player_set_rate'): def set_rate(self, movie): """Set movie play rate @param movie: play rate to set """ e=VLCException() return libvlc_media_player_set_rate(self, movie, e) if hasattr(dll, 'libvlc_media_player_get_state'): def get_state(self): """Get current movie state @return: current movie state as libvlc_state_t """ e=VLCException() return libvlc_media_player_get_state(self, e) if hasattr(dll, 'libvlc_media_player_get_fps'): def get_fps(self): """Get movie fps rate @return: frames per second (fps) for this playing movie """ e=VLCException() return libvlc_media_player_get_fps(self, e) if hasattr(dll, 'libvlc_media_player_has_vout'): def has_vout(self): """Does this media player have a video output? """ e=VLCException() return libvlc_media_player_has_vout(self, e) if hasattr(dll, 'libvlc_media_player_is_seekable'): def is_seekable(self): """Is this media player seekable? """ e=VLCException() return libvlc_media_player_is_seekable(self, e) if hasattr(dll, 'libvlc_media_player_can_pause'): def can_pause(self): """Can this media player be paused? """ e=VLCException() return libvlc_media_player_can_pause(self, e) if hasattr(dll, 'libvlc_toggle_fullscreen'): def toggle_fullscreen(self): """Toggle fullscreen status on video output. """ e=VLCException() return libvlc_toggle_fullscreen(self, e) if hasattr(dll, 'libvlc_set_fullscreen'): def set_fullscreen(self, b_fullscreen): """Enable or disable fullscreen on a video output. @param b_fullscreen: boolean for fullscreen status """ e=VLCException() return libvlc_set_fullscreen(self, b_fullscreen, e) if hasattr(dll, 'libvlc_get_fullscreen'): def get_fullscreen(self): """Get current fullscreen status. @return: the fullscreen status (boolean) """ e=VLCException() return libvlc_get_fullscreen(self, e) if hasattr(dll, 'libvlc_video_get_height'): def video_get_height(self): """Get current video height. @return: the video height """ e=VLCException() return libvlc_video_get_height(self, e) if hasattr(dll, 'libvlc_video_get_width'): def video_get_width(self): """Get current video width. @return: the video width """ e=VLCException() return libvlc_video_get_width(self, e) if hasattr(dll, 'libvlc_video_get_scale'): def video_get_scale(self): """Get the current video scaling factor. See also libvlc_video_set_scale(). @return: the currently configured zoom factor, or 0. if the video is set """ e=VLCException() return libvlc_video_get_scale(self, e) if hasattr(dll, 'libvlc_video_set_scale'): def video_set_scale(self, i_factor): """Set the video scaling factor. That is the ratio of the number of pixels on screen to the number of pixels in the original decoded video in each dimension. Zero is a special value; it will adjust the video to the output window/drawable (in windowed mode) or the entire screen. Note that not all video outputs support scaling. """ e=VLCException() return libvlc_video_set_scale(self, i_factor, e) if hasattr(dll, 'libvlc_video_get_aspect_ratio'): def video_get_aspect_ratio(self): """Get current video aspect ratio. @return: the video aspect ratio """ e=VLCException() return libvlc_video_get_aspect_ratio(self, e) if hasattr(dll, 'libvlc_video_set_aspect_ratio'): def video_set_aspect_ratio(self, psz_aspect): """Set new video aspect ratio. @param psz_aspect: new video aspect-ratio """ e=VLCException() return libvlc_video_set_aspect_ratio(self, psz_aspect, e) if hasattr(dll, 'libvlc_video_get_spu'): def video_get_spu(self): """Get current video subtitle. @return: the video subtitle selected """ e=VLCException() return libvlc_video_get_spu(self, e) if hasattr(dll, 'libvlc_video_get_spu_count'): def video_get_spu_count(self): """Get the number of available video subtitles. @return: the number of available video subtitles """ e=VLCException() return libvlc_video_get_spu_count(self, e) if hasattr(dll, 'libvlc_video_get_spu_description'): def video_get_spu_description(self): """Get the description of available video subtitles. @return: list containing description of available video subtitles """ e=VLCException() return libvlc_video_get_spu_description(self, e) if hasattr(dll, 'libvlc_video_set_spu'): def video_set_spu(self, i_spu): """Set new video subtitle. @param i_spu: new video subtitle to select """ e=VLCException() return libvlc_video_set_spu(self, i_spu, e) if hasattr(dll, 'libvlc_video_set_subtitle_file'): def video_set_subtitle_file(self, psz_subtitle): """Set new video subtitle file. @param psz_subtitle: new video subtitle file @return: the success status (boolean) """ e=VLCException() return libvlc_video_set_subtitle_file(self, psz_subtitle, e) if hasattr(dll, 'libvlc_video_get_title_description'): def video_get_title_description(self): """Get the description of available titles. @return: list containing description of available titles """ e=VLCException() return libvlc_video_get_title_description(self, e) if hasattr(dll, 'libvlc_video_get_chapter_description'): def video_get_chapter_description(self, i_title): """Get the description of available chapters for specific title. @param i_title: selected title @return: list containing description of available chapter for title i_title """ e=VLCException() return libvlc_video_get_chapter_description(self, i_title, e) if hasattr(dll, 'libvlc_video_get_crop_geometry'): def video_get_crop_geometry(self): """Get current crop filter geometry. @return: the crop filter geometry """ e=VLCException() return libvlc_video_get_crop_geometry(self, e) if hasattr(dll, 'libvlc_video_set_crop_geometry'): def video_set_crop_geometry(self, psz_geometry): """Set new crop filter geometry. @param psz_geometry: new crop filter geometry """ e=VLCException() return libvlc_video_set_crop_geometry(self, psz_geometry, e) if hasattr(dll, 'libvlc_toggle_teletext'): def toggle_teletext(self): """Toggle teletext transparent status on video output. """ e=VLCException() return libvlc_toggle_teletext(self, e) if hasattr(dll, 'libvlc_video_get_teletext'): def video_get_teletext(self): """Get current teletext page requested. @return: the current teletext page requested. """ e=VLCException() return libvlc_video_get_teletext(self, e) if hasattr(dll, 'libvlc_video_set_teletext'): def video_set_teletext(self, i_page): """Set new teletext page to retrieve. @param i_page: teletex page number requested """ e=VLCException() return libvlc_video_set_teletext(self, i_page, e) if hasattr(dll, 'libvlc_video_get_track_count'): def video_get_track_count(self): """Get number of available video tracks. @return: the number of available video tracks (int) """ e=VLCException() return libvlc_video_get_track_count(self, e) if hasattr(dll, 'libvlc_video_get_track_description'): def video_get_track_description(self): """Get the description of available video tracks. @return: list with description of available video tracks """ e=VLCException() return libvlc_video_get_track_description(self, e) if hasattr(dll, 'libvlc_video_get_track'): def video_get_track(self): """Get current video track. @return: the video track (int) """ e=VLCException() return libvlc_video_get_track(self, e) if hasattr(dll, 'libvlc_video_set_track'): def video_set_track(self, i_track): """Set video track. @param i_track: the track (int) """ e=VLCException() return libvlc_video_set_track(self, i_track, e) if hasattr(dll, 'libvlc_video_take_snapshot'): def video_take_snapshot(self, psz_filepath, i_width, i_height): """Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param psz_filepath: the path where to save the screenshot to @param i_width: the snapshot's width @param i_height: the snapshot's height """ e=VLCException() return libvlc_video_take_snapshot(self, psz_filepath, i_width, i_height, e) if hasattr(dll, 'libvlc_audio_get_track_count'): def audio_get_track_count(self): """Get number of available audio tracks. @return: the number of available audio tracks (int) """ e=VLCException() return libvlc_audio_get_track_count(self, e) if hasattr(dll, 'libvlc_audio_get_track_description'): def audio_get_track_description(self): """Get the description of available audio tracks. @return: list with description of available audio tracks """ e=VLCException() return libvlc_audio_get_track_description(self, e) if hasattr(dll, 'libvlc_audio_get_track'): def audio_get_track(self): """Get current audio track. @return: the audio track (int) """ e=VLCException() return libvlc_audio_get_track(self, e) if hasattr(dll, 'libvlc_audio_set_track'): def audio_set_track(self, i_track): """Set current audio track. @param i_track: the track (int) """ e=VLCException() return libvlc_audio_set_track(self, i_track, e) class TrackDescription(object): def __new__(cls, pointer=None): '''Internal method used for instanciating wrappers from ctypes. ''' if pointer is None: raise Exception("Internal method. Surely this class cannot be instanciated by itself.") if pointer == 0: return None else: o=object.__new__(cls) o._as_parameter_=ctypes.c_void_p(pointer) return o @staticmethod def from_param(arg): '''(INTERNAL) ctypes parameter conversion method. ''' return arg._as_parameter_ if hasattr(dll, 'libvlc_track_description_release'): def release(self): """Release (free) libvlc_track_description_t """ return libvlc_track_description_release(self) if hasattr(dll, 'libvlc_exception_init'): prototype=ctypes.CFUNCTYPE(None, ctypes.POINTER(VLCException)) paramflags=( (3, ), ) libvlc_exception_init = prototype( ("libvlc_exception_init", dll), paramflags ) libvlc_exception_init.errcheck = check_vlc_exception libvlc_exception_init.__doc__ = """Initialize an exception structure. This can be called several times to reuse an exception structure. @param p_exception the exception to initialize """ if hasattr(dll, 'libvlc_exception_clear'): prototype=ctypes.CFUNCTYPE(None, ctypes.POINTER(VLCException)) paramflags=( (3, ), ) libvlc_exception_clear = prototype( ("libvlc_exception_clear", dll), paramflags ) libvlc_exception_clear.errcheck = check_vlc_exception libvlc_exception_clear.__doc__ = """Clear an exception object so it can be reused. The exception object must have be initialized. @param p_exception the exception to clear """ if hasattr(dll, 'libvlc_new'): prototype=ctypes.CFUNCTYPE(Instance, ctypes.c_int,ListPOINTER(ctypes.c_char_p),ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_new = prototype( ("libvlc_new", dll), paramflags ) libvlc_new.errcheck = check_vlc_exception libvlc_new.__doc__ = """Create and initialize a libvlc instance. @param argc the number of arguments @param argv command-line-type arguments. argv[0] must be the path of the calling program. @param p_e an initialized exception pointer @return the libvlc instance """ if hasattr(dll, 'libvlc_get_vlc_id'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance) paramflags=( (1, ), ) libvlc_get_vlc_id = prototype( ("libvlc_get_vlc_id", dll), paramflags ) libvlc_get_vlc_id.__doc__ = """Return a libvlc instance identifier for legacy APIs. Use of this function is discouraged, you should convert your program to use the new API. @param p_instance the instance @return the instance identifier """ if hasattr(dll, 'libvlc_release'): prototype=ctypes.CFUNCTYPE(None, Instance) paramflags=( (1, ), ) libvlc_release = prototype( ("libvlc_release", dll), paramflags ) libvlc_release.__doc__ = """Decrement the reference count of a libvlc instance, and destroy it if it reaches zero. @param p_instance the instance to destroy """ if hasattr(dll, 'libvlc_retain'): prototype=ctypes.CFUNCTYPE(None, Instance) paramflags=( (1, ), ) libvlc_retain = prototype( ("libvlc_retain", dll), paramflags ) libvlc_retain.__doc__ = """Increments the reference count of a libvlc instance. The initial reference count is 1 after libvlc_new() returns. @param p_instance the instance to reference """ if hasattr(dll, 'libvlc_add_intf'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_add_intf = prototype( ("libvlc_add_intf", dll), paramflags ) libvlc_add_intf.errcheck = check_vlc_exception libvlc_add_intf.__doc__ = """Try to start a user interface for the libvlc instance. @param p_instance the instance @param name interface name, or NULL for default @param p_exception an initialized exception pointer """ if hasattr(dll, 'libvlc_wait'): prototype=ctypes.CFUNCTYPE(None, Instance) paramflags=( (1, ), ) libvlc_wait = prototype( ("libvlc_wait", dll), paramflags ) libvlc_wait.__doc__ = """Waits until an interface causes the instance to exit. You should start at least one interface first, using libvlc_add_intf(). @param p_instance the instance """ if hasattr(dll, 'libvlc_get_version'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p) paramflags= tuple() libvlc_get_version = prototype( ("libvlc_get_version", dll), paramflags ) libvlc_get_version.__doc__ = """Retrieve libvlc version. Example: "0.9.0-git Grishenko" @return a string containing the libvlc version """ if hasattr(dll, 'libvlc_get_compiler'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p) paramflags= tuple() libvlc_get_compiler = prototype( ("libvlc_get_compiler", dll), paramflags ) libvlc_get_compiler.__doc__ = """Retrieve libvlc compiler version. Example: "gcc version 4.2.3 (Ubuntu 4.2.3-2ubuntu6)" @return a string containing the libvlc compiler version """ if hasattr(dll, 'libvlc_get_changeset'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p) paramflags= tuple() libvlc_get_changeset = prototype( ("libvlc_get_changeset", dll), paramflags ) libvlc_get_changeset.__doc__ = """Retrieve libvlc changeset. Example: "aa9bce0bc4" @return a string containing the libvlc changeset """ if hasattr(dll, 'libvlc_free'): prototype=ctypes.CFUNCTYPE(None, ctypes.c_void_p) paramflags=( (1, ), ) libvlc_free = prototype( ("libvlc_free", dll), paramflags ) libvlc_free.__doc__ = """Frees an heap allocation (char *) returned by a LibVLC API. If you know you're using the same underlying C run-time as the LibVLC implementation, then you can call ANSI C free() directly instead. """ if hasattr(dll, 'libvlc_event_attach'): prototype=ctypes.CFUNCTYPE(None, EventManager,EventType,ctypes.c_void_p,ctypes.c_void_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(1,),(3,) libvlc_event_attach = prototype( ("libvlc_event_attach", dll), paramflags ) libvlc_event_attach.errcheck = check_vlc_exception libvlc_event_attach.__doc__ = """Register for an event notification. @param p_event_manager the event manager to which you want to attach to. Generally it is obtained by vlc_my_object_event_manager() where my_object is the object you want to listen to. @param i_event_type the desired event to which we want to listen @param f_callback the function to call when i_event_type occurs @param user_data user provided data to carry with the event @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_event_detach'): prototype=ctypes.CFUNCTYPE(None, EventManager,EventType,ctypes.c_void_p,ctypes.c_void_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(1,),(3,) libvlc_event_detach = prototype( ("libvlc_event_detach", dll), paramflags ) libvlc_event_detach.errcheck = check_vlc_exception libvlc_event_detach.__doc__ = """Unregister an event notification. @param p_event_manager the event manager @param i_event_type the desired event to which we want to unregister @param f_callback the function to call when i_event_type occurs @param p_user_data user provided data to carry with the event @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_event_type_name'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, EventType) paramflags=( (1, ), ) libvlc_event_type_name = prototype( ("libvlc_event_type_name", dll), paramflags ) libvlc_event_type_name.__doc__ = """Get an event's type name. @param i_event_type the desired event """ if hasattr(dll, 'libvlc_get_log_verbosity'): prototype=ctypes.CFUNCTYPE(ctypes.c_uint, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_get_log_verbosity = prototype( ("libvlc_get_log_verbosity", dll), paramflags ) libvlc_get_log_verbosity.errcheck = check_vlc_exception libvlc_get_log_verbosity.__doc__ = """Return the VLC messaging verbosity level. @param p_instance libvlc instance @param p_e an initialized exception pointer @return verbosity level for messages """ if hasattr(dll, 'libvlc_set_log_verbosity'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_uint,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_set_log_verbosity = prototype( ("libvlc_set_log_verbosity", dll), paramflags ) libvlc_set_log_verbosity.errcheck = check_vlc_exception libvlc_set_log_verbosity.__doc__ = """Set the VLC messaging verbosity level. @param p_instance libvlc log instance @param level log level @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_log_open'): prototype=ctypes.CFUNCTYPE(Log, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_open = prototype( ("libvlc_log_open", dll), paramflags ) libvlc_log_open.errcheck = check_vlc_exception libvlc_log_open.__doc__ = """Open a VLC message log instance. @param p_instance libvlc instance @param p_e an initialized exception pointer @return log message instance """ if hasattr(dll, 'libvlc_log_close'): prototype=ctypes.CFUNCTYPE(None, Log,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_close = prototype( ("libvlc_log_close", dll), paramflags ) libvlc_log_close.errcheck = check_vlc_exception libvlc_log_close.__doc__ = """Close a VLC message log instance. @param p_log libvlc log instance @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_log_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_uint, Log,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_count = prototype( ("libvlc_log_count", dll), paramflags ) libvlc_log_count.errcheck = check_vlc_exception libvlc_log_count.__doc__ = """Returns the number of messages in a log instance. @param p_log libvlc log instance @param p_e an initialized exception pointer @return number of log messages """ if hasattr(dll, 'libvlc_log_clear'): prototype=ctypes.CFUNCTYPE(None, Log,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_clear = prototype( ("libvlc_log_clear", dll), paramflags ) libvlc_log_clear.errcheck = check_vlc_exception libvlc_log_clear.__doc__ = """Clear a log instance. All messages in the log are removed. The log should be cleared on a regular basis to avoid clogging. @param p_log libvlc log instance @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_log_get_iterator'): prototype=ctypes.CFUNCTYPE(LogIterator, Log,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_get_iterator = prototype( ("libvlc_log_get_iterator", dll), paramflags ) libvlc_log_get_iterator.errcheck = check_vlc_exception libvlc_log_get_iterator.__doc__ = """Allocate and returns a new iterator to messages in log. @param p_log libvlc log instance @param p_e an initialized exception pointer @return log iterator object """ if hasattr(dll, 'libvlc_log_iterator_free'): prototype=ctypes.CFUNCTYPE(None, LogIterator,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_iterator_free = prototype( ("libvlc_log_iterator_free", dll), paramflags ) libvlc_log_iterator_free.errcheck = check_vlc_exception libvlc_log_iterator_free.__doc__ = """Release a previoulsy allocated iterator. @param p_iter libvlc log iterator @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_log_iterator_has_next'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, LogIterator,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_log_iterator_has_next = prototype( ("libvlc_log_iterator_has_next", dll), paramflags ) libvlc_log_iterator_has_next.errcheck = check_vlc_exception libvlc_log_iterator_has_next.__doc__ = """Return whether log iterator has more messages. @param p_iter libvlc log iterator @param p_e an initialized exception pointer @return true if iterator has more message objects, else false """ if hasattr(dll, 'libvlc_log_iterator_next'): prototype=ctypes.CFUNCTYPE(ctypes.POINTER(LogMessage), LogIterator,ctypes.POINTER(LogMessage),ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_log_iterator_next = prototype( ("libvlc_log_iterator_next", dll), paramflags ) libvlc_log_iterator_next.errcheck = check_vlc_exception libvlc_log_iterator_next.__doc__ = """Return the next log message. The message contents must not be freed @param p_iter libvlc log iterator @param p_buffer log buffer @param p_e an initialized exception pointer @return log message object """ if hasattr(dll, 'libvlc_media_new'): prototype=ctypes.CFUNCTYPE(Media, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_new = prototype( ("libvlc_media_new", dll), paramflags ) libvlc_media_new.errcheck = check_vlc_exception libvlc_media_new.__doc__ = """Create a media with the given MRL. @param p_instance the instance @param psz_mrl the MRL to read @param p_e an initialized exception pointer @return the newly created media """ if hasattr(dll, 'libvlc_media_new_as_node'): prototype=ctypes.CFUNCTYPE(Media, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_new_as_node = prototype( ("libvlc_media_new_as_node", dll), paramflags ) libvlc_media_new_as_node.errcheck = check_vlc_exception libvlc_media_new_as_node.__doc__ = """Create a media as an empty node with the passed name. @param p_instance the instance @param psz_name the name of the node @param p_e an initialized exception pointer @return the new empty media """ if hasattr(dll, 'libvlc_media_add_option'): prototype=ctypes.CFUNCTYPE(None, Media,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_add_option = prototype( ("libvlc_media_add_option", dll), paramflags ) libvlc_media_add_option.errcheck = check_vlc_exception libvlc_media_add_option.__doc__ = """Add an option to the media. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all" @param p_instance the instance @param ppsz_options the options (as a string) @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_add_option_untrusted'): prototype=ctypes.CFUNCTYPE(None, Media,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_add_option_untrusted = prototype( ("libvlc_media_add_option_untrusted", dll), paramflags ) libvlc_media_add_option_untrusted.errcheck = check_vlc_exception libvlc_media_add_option_untrusted.__doc__ = """Add an option to the media from an untrusted source. This option will be used to determine how the media_player will read the media. This allows to use VLC's advanced reading/streaming options on a per-media basis. The options are detailed in vlc --long-help, for instance "--sout-all" @param p_instance the instance @param ppsz_options the options (as a string) @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_retain'): prototype=ctypes.CFUNCTYPE(None, Media) paramflags=( (1, ), ) libvlc_media_retain = prototype( ("libvlc_media_retain", dll), paramflags ) libvlc_media_retain.__doc__ = """Retain a reference to a media descriptor object (libvlc_media_t). Use libvlc_media_release() to decrement the reference count of a media descriptor object. @param p_meta_desc a media descriptor object. """ if hasattr(dll, 'libvlc_media_release'): prototype=ctypes.CFUNCTYPE(None, Media) paramflags=( (1, ), ) libvlc_media_release = prototype( ("libvlc_media_release", dll), paramflags ) libvlc_media_release.__doc__ = """Decrement the reference count of a media descriptor object. If the reference count is 0, then libvlc_media_release() will release the media descriptor object. It will send out an libvlc_MediaFreed event to all listeners. If the media descriptor object has been released it should not be used again. @param p_meta_desc a media descriptor object. """ if hasattr(dll, 'libvlc_media_get_mrl'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_get_mrl = prototype( ("libvlc_media_get_mrl", dll), paramflags ) libvlc_media_get_mrl.errcheck = check_vlc_exception libvlc_media_get_mrl.__doc__ = """Get the media resource locator (mrl) from a media descriptor object @param p_md a media descriptor object @param p_e an initialized exception object @return string with mrl of media descriptor object """ if hasattr(dll, 'libvlc_media_duplicate'): prototype=ctypes.CFUNCTYPE(Media, Media) paramflags=( (1, ), ) libvlc_media_duplicate = prototype( ("libvlc_media_duplicate", dll), paramflags ) libvlc_media_duplicate.__doc__ = """Duplicate a media descriptor object. @param p_meta_desc a media descriptor object. """ if hasattr(dll, 'libvlc_media_get_meta'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, Media,Meta,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_get_meta = prototype( ("libvlc_media_get_meta", dll), paramflags ) libvlc_media_get_meta.errcheck = check_vlc_exception libvlc_media_get_meta.__doc__ = """Read the meta of the media. @param p_meta_desc the media to read @param e_meta_desc the meta to read @param p_e an initialized exception pointer @return the media's meta """ if hasattr(dll, 'libvlc_media_get_state'): prototype=ctypes.CFUNCTYPE(State, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_get_state = prototype( ("libvlc_media_get_state", dll), paramflags ) libvlc_media_get_state.errcheck = check_vlc_exception libvlc_media_get_state.__doc__ = """Get current state of media descriptor object. Possible media states are defined in libvlc_structures.c ( libvlc_NothingSpecial=0, libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused, libvlc_Stopped, libvlc_Ended, libvlc_Error). @see libvlc_state_t @param p_meta_desc a media descriptor object @param p_e an initialized exception object @return state of media descriptor object """ if hasattr(dll, 'libvlc_media_subitems'): prototype=ctypes.CFUNCTYPE(MediaList, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_subitems = prototype( ("libvlc_media_subitems", dll), paramflags ) libvlc_media_subitems.errcheck = check_vlc_exception libvlc_media_subitems.__doc__ = """Get subitems of media descriptor object. This will increment the reference count of supplied media descriptor object. Use libvlc_media_list_release() to decrement the reference counting. @param p_md media descriptor object @param p_e initalized exception object @return list of media descriptor subitems or NULL and this is here for convenience */ """ if hasattr(dll, 'libvlc_media_event_manager'): prototype=ctypes.CFUNCTYPE(EventManager, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_event_manager = prototype( ("libvlc_media_event_manager", dll), paramflags ) libvlc_media_event_manager.errcheck = check_vlc_exception libvlc_media_event_manager.__doc__ = """Get event manager from media descriptor object. NOTE: this function doesn't increment reference counting. @param p_md a media descriptor object @param p_e an initialized exception object @return event manager object """ if hasattr(dll, 'libvlc_media_get_duration'): prototype=ctypes.CFUNCTYPE(ctypes.c_longlong, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_get_duration = prototype( ("libvlc_media_get_duration", dll), paramflags ) libvlc_media_get_duration.errcheck = check_vlc_exception libvlc_media_get_duration.__doc__ = """Get duration of media descriptor object item. @param p_md media descriptor object @param p_e an initialized exception object @return duration of media item """ if hasattr(dll, 'libvlc_media_is_preparsed'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_is_preparsed = prototype( ("libvlc_media_is_preparsed", dll), paramflags ) libvlc_media_is_preparsed.errcheck = check_vlc_exception libvlc_media_is_preparsed.__doc__ = """Get preparsed status for media descriptor object. @param p_md media descriptor object @param p_e an initialized exception object @return true if media object has been preparsed otherwise it returns false """ if hasattr(dll, 'libvlc_media_set_user_data'): prototype=ctypes.CFUNCTYPE(None, Media,ctypes.c_void_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_set_user_data = prototype( ("libvlc_media_set_user_data", dll), paramflags ) libvlc_media_set_user_data.errcheck = check_vlc_exception libvlc_media_set_user_data.__doc__ = """Sets media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a libvlc_media_t pointer @param p_md media descriptor object @param p_new_user_data pointer to user data @param p_e an initialized exception object """ if hasattr(dll, 'libvlc_media_get_user_data'): prototype=ctypes.CFUNCTYPE(ctypes.c_void_p, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_get_user_data = prototype( ("libvlc_media_get_user_data", dll), paramflags ) libvlc_media_get_user_data.errcheck = check_vlc_exception libvlc_media_get_user_data.__doc__ = """Get media descriptor's user_data. user_data is specialized data accessed by the host application, VLC.framework uses it as a pointer to an native object that references a libvlc_media_t pointer @param p_md media descriptor object @param p_e an initialized exception object """ if hasattr(dll, 'libvlc_media_discoverer_new_from_name'): prototype=ctypes.CFUNCTYPE(MediaDiscoverer, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_discoverer_new_from_name = prototype( ("libvlc_media_discoverer_new_from_name", dll), paramflags ) libvlc_media_discoverer_new_from_name.errcheck = check_vlc_exception libvlc_media_discoverer_new_from_name.__doc__ = """Discover media service by name. @param p_inst libvlc instance @param psz_name service name @param p_e an initialized exception object @return media discover object """ if hasattr(dll, 'libvlc_media_discoverer_release'): prototype=ctypes.CFUNCTYPE(None, MediaDiscoverer) paramflags=( (1, ), ) libvlc_media_discoverer_release = prototype( ("libvlc_media_discoverer_release", dll), paramflags ) libvlc_media_discoverer_release.__doc__ = """Release media discover object. If the reference count reaches 0, then the object will be released. @param p_mdis media service discover object """ if hasattr(dll, 'libvlc_media_discoverer_localized_name'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, MediaDiscoverer) paramflags=( (1, ), ) libvlc_media_discoverer_localized_name = prototype( ("libvlc_media_discoverer_localized_name", dll), paramflags ) libvlc_media_discoverer_localized_name.__doc__ = """Get media service discover object its localized name. @param media discover object @return localized name """ if hasattr(dll, 'libvlc_media_discoverer_media_list'): prototype=ctypes.CFUNCTYPE(MediaList, MediaDiscoverer) paramflags=( (1, ), ) libvlc_media_discoverer_media_list = prototype( ("libvlc_media_discoverer_media_list", dll), paramflags ) libvlc_media_discoverer_media_list.__doc__ = """Get media service discover media list. @param p_mdis media service discover object @return list of media items """ if hasattr(dll, 'libvlc_media_discoverer_event_manager'): prototype=ctypes.CFUNCTYPE(EventManager, MediaDiscoverer) paramflags=( (1, ), ) libvlc_media_discoverer_event_manager = prototype( ("libvlc_media_discoverer_event_manager", dll), paramflags ) libvlc_media_discoverer_event_manager.__doc__ = """Get event manager from media service discover object. @param p_mdis media service discover object @return event manager object. """ if hasattr(dll, 'libvlc_media_discoverer_is_running'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaDiscoverer) paramflags=( (1, ), ) libvlc_media_discoverer_is_running = prototype( ("libvlc_media_discoverer_is_running", dll), paramflags ) libvlc_media_discoverer_is_running.__doc__ = """Query if media service discover object is running. @param p_mdis media service discover object @return true if running, false if not """ if hasattr(dll, 'libvlc_media_library_new'): prototype=ctypes.CFUNCTYPE(MediaLibrary, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_library_new = prototype( ("libvlc_media_library_new", dll), paramflags ) libvlc_media_library_new.errcheck = check_vlc_exception libvlc_media_library_new.__doc__ = """\ingroup libvlc LibVLC Media Library @{ """ if hasattr(dll, 'libvlc_media_library_release'): prototype=ctypes.CFUNCTYPE(None, MediaLibrary) paramflags=( (1, ), ) libvlc_media_library_release = prototype( ("libvlc_media_library_release", dll), paramflags ) libvlc_media_library_release.__doc__ = """Release media library object. This functions decrements the reference count of the media library object. If it reaches 0, then the object will be released. @param p_mlib media library object """ if hasattr(dll, 'libvlc_media_library_retain'): prototype=ctypes.CFUNCTYPE(None, MediaLibrary) paramflags=( (1, ), ) libvlc_media_library_retain = prototype( ("libvlc_media_library_retain", dll), paramflags ) libvlc_media_library_retain.__doc__ = """Retain a reference to a media library object. This function will increment the reference counting for this object. Use libvlc_media_library_release() to decrement the reference count. @param p_mlib media library object """ if hasattr(dll, 'libvlc_media_library_load'): prototype=ctypes.CFUNCTYPE(None, MediaLibrary,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_library_load = prototype( ("libvlc_media_library_load", dll), paramflags ) libvlc_media_library_load.errcheck = check_vlc_exception libvlc_media_library_load.__doc__ = """Load media library. @param p_mlib media library object @param p_e an initialized exception object. """ if hasattr(dll, 'libvlc_media_library_save'): prototype=ctypes.CFUNCTYPE(None, MediaLibrary,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_library_save = prototype( ("libvlc_media_library_save", dll), paramflags ) libvlc_media_library_save.errcheck = check_vlc_exception libvlc_media_library_save.__doc__ = """Save media library. @param p_mlib media library object @param p_e an initialized exception object. """ if hasattr(dll, 'libvlc_media_library_media_list'): prototype=ctypes.CFUNCTYPE(MediaList, MediaLibrary,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_library_media_list = prototype( ("libvlc_media_library_media_list", dll), paramflags ) libvlc_media_library_media_list.errcheck = check_vlc_exception libvlc_media_library_media_list.__doc__ = """Get media library subitems. @param p_mlib media library object @param p_e an initialized exception object. @return media list subitems """ if hasattr(dll, 'libvlc_media_list_new'): prototype=ctypes.CFUNCTYPE(MediaList, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_new = prototype( ("libvlc_media_list_new", dll), paramflags ) libvlc_media_list_new.errcheck = check_vlc_exception libvlc_media_list_new.__doc__ = """Create an empty media list. @param p_libvlc libvlc instance @param p_e an initialized exception pointer @return empty media list """ if hasattr(dll, 'libvlc_media_list_release'): prototype=ctypes.CFUNCTYPE(None, MediaList) paramflags=( (1, ), ) libvlc_media_list_release = prototype( ("libvlc_media_list_release", dll), paramflags ) libvlc_media_list_release.__doc__ = """Release media list created with libvlc_media_list_new(). @param p_ml a media list created with libvlc_media_list_new() """ if hasattr(dll, 'libvlc_media_list_retain'): prototype=ctypes.CFUNCTYPE(None, MediaList) paramflags=( (1, ), ) libvlc_media_list_retain = prototype( ("libvlc_media_list_retain", dll), paramflags ) libvlc_media_list_retain.__doc__ = """Retain reference to a media list @param p_ml a media list created with libvlc_media_list_new() """ if hasattr(dll, 'libvlc_media_list_set_media'): prototype=ctypes.CFUNCTYPE(None, MediaList,Media,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_set_media = prototype( ("libvlc_media_list_set_media", dll), paramflags ) libvlc_media_list_set_media.errcheck = check_vlc_exception libvlc_media_list_set_media.__doc__ = """Associate media instance with this media list instance. If another media instance was present it will be released. The libvlc_media_list_lock should NOT be held upon entering this function. @param p_ml a media list instance @param p_mi media instance to add @param p_e initialized exception object """ if hasattr(dll, 'libvlc_media_list_media'): prototype=ctypes.CFUNCTYPE(Media, MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_media = prototype( ("libvlc_media_list_media", dll), paramflags ) libvlc_media_list_media.errcheck = check_vlc_exception libvlc_media_list_media.__doc__ = """Get media instance from this media list instance. This action will increase the refcount on the media instance. The libvlc_media_list_lock should NOT be held upon entering this function. @param p_ml a media list instance @param p_e initialized exception object @return media instance """ if hasattr(dll, 'libvlc_media_list_add_media'): prototype=ctypes.CFUNCTYPE(None, MediaList,Media,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_add_media = prototype( ("libvlc_media_list_add_media", dll), paramflags ) libvlc_media_list_add_media.errcheck = check_vlc_exception libvlc_media_list_add_media.__doc__ = """Add media instance to media list The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance @param p_mi a media instance @param p_e initialized exception object """ if hasattr(dll, 'libvlc_media_list_insert_media'): prototype=ctypes.CFUNCTYPE(None, MediaList,Media,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_media_list_insert_media = prototype( ("libvlc_media_list_insert_media", dll), paramflags ) libvlc_media_list_insert_media.errcheck = check_vlc_exception libvlc_media_list_insert_media.__doc__ = """Insert media instance in media list on a position The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance @param p_mi a media instance @param i_pos position in array where to insert @param p_e initialized exception object """ if hasattr(dll, 'libvlc_media_list_remove_index'): prototype=ctypes.CFUNCTYPE(None, MediaList,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_remove_index = prototype( ("libvlc_media_list_remove_index", dll), paramflags ) libvlc_media_list_remove_index.errcheck = check_vlc_exception libvlc_media_list_remove_index.__doc__ = """Remove media instance from media list on a position The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance @param i_pos position in array where to insert @param p_e initialized exception object """ if hasattr(dll, 'libvlc_media_list_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_count = prototype( ("libvlc_media_list_count", dll), paramflags ) libvlc_media_list_count.errcheck = check_vlc_exception libvlc_media_list_count.__doc__ = """Get count on media list items The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance @param p_e initialized exception object @return number of items in media list """ if hasattr(dll, 'libvlc_media_list_item_at_index'): prototype=ctypes.CFUNCTYPE(Media, MediaList,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_item_at_index = prototype( ("libvlc_media_list_item_at_index", dll), paramflags ) libvlc_media_list_item_at_index.errcheck = check_vlc_exception libvlc_media_list_item_at_index.__doc__ = """List media instance in media list at a position The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance @param i_pos position in array where to insert @param p_e initialized exception object @return media instance at position i_pos and libvlc_media_retain() has been called to increase the refcount on this object. """ if hasattr(dll, 'libvlc_media_list_index_of_item'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaList,Media,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_index_of_item = prototype( ("libvlc_media_list_index_of_item", dll), paramflags ) libvlc_media_list_index_of_item.errcheck = check_vlc_exception libvlc_media_list_index_of_item.__doc__ = """Find index position of List media instance in media list. Warning: the function will return the first matched position. The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance @param p_mi media list instance @param p_e initialized exception object @return position of media instance """ if hasattr(dll, 'libvlc_media_list_is_readonly'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaList) paramflags=( (1, ), ) libvlc_media_list_is_readonly = prototype( ("libvlc_media_list_is_readonly", dll), paramflags ) libvlc_media_list_is_readonly.__doc__ = """This indicates if this media list is read-only from a user point of view @param p_ml media list instance @return 0 on readonly, 1 on readwrite """ if hasattr(dll, 'libvlc_media_list_lock'): prototype=ctypes.CFUNCTYPE(None, MediaList) paramflags=( (1, ), ) libvlc_media_list_lock = prototype( ("libvlc_media_list_lock", dll), paramflags ) libvlc_media_list_lock.__doc__ = """Get lock on media list items @param p_ml a media list instance """ if hasattr(dll, 'libvlc_media_list_unlock'): prototype=ctypes.CFUNCTYPE(None, MediaList) paramflags=( (1, ), ) libvlc_media_list_unlock = prototype( ("libvlc_media_list_unlock", dll), paramflags ) libvlc_media_list_unlock.__doc__ = """Release lock on media list items The libvlc_media_list_lock should be held upon entering this function. @param p_ml a media list instance """ if hasattr(dll, 'libvlc_media_list_flat_view'): prototype=ctypes.CFUNCTYPE(MediaListView, MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_flat_view = prototype( ("libvlc_media_list_flat_view", dll), paramflags ) libvlc_media_list_flat_view.errcheck = check_vlc_exception libvlc_media_list_flat_view.__doc__ = """Get a flat media list view of media list items @param p_ml a media list instance @param p_ex an excpetion instance @return flat media list view instance """ if hasattr(dll, 'libvlc_media_list_hierarchical_view'): prototype=ctypes.CFUNCTYPE(MediaListView, MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_hierarchical_view = prototype( ("libvlc_media_list_hierarchical_view", dll), paramflags ) libvlc_media_list_hierarchical_view.errcheck = check_vlc_exception libvlc_media_list_hierarchical_view.__doc__ = """Get a hierarchical media list view of media list items @param p_ml a media list instance @param p_ex an excpetion instance @return hierarchical media list view instance """ if hasattr(dll, 'libvlc_media_list_hierarchical_node_view'): prototype=ctypes.CFUNCTYPE(MediaListView, MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_hierarchical_node_view = prototype( ("libvlc_media_list_hierarchical_node_view", dll), paramflags ) libvlc_media_list_hierarchical_node_view.errcheck = check_vlc_exception libvlc_media_list_hierarchical_node_view.__doc__ = """""" if hasattr(dll, 'libvlc_media_list_event_manager'): prototype=ctypes.CFUNCTYPE(EventManager, MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_event_manager = prototype( ("libvlc_media_list_event_manager", dll), paramflags ) libvlc_media_list_event_manager.errcheck = check_vlc_exception libvlc_media_list_event_manager.__doc__ = """Get libvlc_event_manager from this media list instance. The p_event_manager is immutable, so you don't have to hold the lock @param p_ml a media list instance @param p_ex an excpetion instance @return libvlc_event_manager """ if hasattr(dll, 'libvlc_media_list_player_new'): prototype=ctypes.CFUNCTYPE(MediaListPlayer, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_new = prototype( ("libvlc_media_list_player_new", dll), paramflags ) libvlc_media_list_player_new.errcheck = check_vlc_exception libvlc_media_list_player_new.__doc__ = """Create new media_list_player. @param p_instance libvlc instance @param p_e initialized exception instance @return media list player instance """ if hasattr(dll, 'libvlc_media_list_player_release'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer) paramflags=( (1, ), ) libvlc_media_list_player_release = prototype( ("libvlc_media_list_player_release", dll), paramflags ) libvlc_media_list_player_release.__doc__ = """Release media_list_player. @param p_mlp media list player instance """ if hasattr(dll, 'libvlc_media_list_player_set_media_player'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_player_set_media_player = prototype( ("libvlc_media_list_player_set_media_player", dll), paramflags ) libvlc_media_list_player_set_media_player.errcheck = check_vlc_exception libvlc_media_list_player_set_media_player.__doc__ = """Replace media player in media_list_player with this instance. @param p_mlp media list player instance @param p_mi media player instance @param p_e initialized exception instance """ if hasattr(dll, 'libvlc_media_list_player_set_media_list'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,MediaList,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_player_set_media_list = prototype( ("libvlc_media_list_player_set_media_list", dll), paramflags ) libvlc_media_list_player_set_media_list.errcheck = check_vlc_exception libvlc_media_list_player_set_media_list.__doc__ = """""" if hasattr(dll, 'libvlc_media_list_player_play'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_play = prototype( ("libvlc_media_list_player_play", dll), paramflags ) libvlc_media_list_player_play.errcheck = check_vlc_exception libvlc_media_list_player_play.__doc__ = """Play media list @param p_mlp media list player instance @param p_e initialized exception instance """ if hasattr(dll, 'libvlc_media_list_player_pause'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_pause = prototype( ("libvlc_media_list_player_pause", dll), paramflags ) libvlc_media_list_player_pause.errcheck = check_vlc_exception libvlc_media_list_player_pause.__doc__ = """Pause media list @param p_mlp media list player instance @param p_e initialized exception instance """ if hasattr(dll, 'libvlc_media_list_player_is_playing'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaListPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_is_playing = prototype( ("libvlc_media_list_player_is_playing", dll), paramflags ) libvlc_media_list_player_is_playing.errcheck = check_vlc_exception libvlc_media_list_player_is_playing.__doc__ = """Is media list playing? @param p_mlp media list player instance @param p_e initialized exception instance @return true for playing and false for not playing """ if hasattr(dll, 'libvlc_media_list_player_get_state'): prototype=ctypes.CFUNCTYPE(State, MediaListPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_get_state = prototype( ("libvlc_media_list_player_get_state", dll), paramflags ) libvlc_media_list_player_get_state.errcheck = check_vlc_exception libvlc_media_list_player_get_state.__doc__ = """Get current libvlc_state of media list player @param p_mlp media list player instance @param p_e initialized exception instance @return libvlc_state_t for media list player """ if hasattr(dll, 'libvlc_media_list_player_play_item_at_index'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_player_play_item_at_index = prototype( ("libvlc_media_list_player_play_item_at_index", dll), paramflags ) libvlc_media_list_player_play_item_at_index.errcheck = check_vlc_exception libvlc_media_list_player_play_item_at_index.__doc__ = """Play media list item at position index @param p_mlp media list player instance @param i_index index in media list to play @param p_e initialized exception instance """ if hasattr(dll, 'libvlc_media_list_player_play_item'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,Media,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_player_play_item = prototype( ("libvlc_media_list_player_play_item", dll), paramflags ) libvlc_media_list_player_play_item.errcheck = check_vlc_exception libvlc_media_list_player_play_item.__doc__ = """""" if hasattr(dll, 'libvlc_media_list_player_stop'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_stop = prototype( ("libvlc_media_list_player_stop", dll), paramflags ) libvlc_media_list_player_stop.errcheck = check_vlc_exception libvlc_media_list_player_stop.__doc__ = """Stop playing media list @param p_mlp media list player instance @param p_e initialized exception instance """ if hasattr(dll, 'libvlc_media_list_player_next'): prototype=ctypes.CFUNCTYPE(None, MediaListPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_player_next = prototype( ("libvlc_media_list_player_next", dll), paramflags ) libvlc_media_list_player_next.errcheck = check_vlc_exception libvlc_media_list_player_next.__doc__ = """Play next item from media list @param p_mlp media list player instance @param p_e initialized exception instance """ if hasattr(dll, 'libvlc_media_list_view_retain'): prototype=ctypes.CFUNCTYPE(None, MediaListView) paramflags=( (1, ), ) libvlc_media_list_view_retain = prototype( ("libvlc_media_list_view_retain", dll), paramflags ) libvlc_media_list_view_retain.__doc__ = """Retain reference to a media list view @param p_mlv a media list view created with libvlc_media_list_view_new() """ if hasattr(dll, 'libvlc_media_list_view_release'): prototype=ctypes.CFUNCTYPE(None, MediaListView) paramflags=( (1, ), ) libvlc_media_list_view_release = prototype( ("libvlc_media_list_view_release", dll), paramflags ) libvlc_media_list_view_release.__doc__ = """Release reference to a media list view. If the refcount reaches 0, then the object will be released. @param p_mlv a media list view created with libvlc_media_list_view_new() """ if hasattr(dll, 'libvlc_media_list_view_event_manager'): prototype=ctypes.CFUNCTYPE(EventManager, MediaListView) paramflags=( (1, ), ) libvlc_media_list_view_event_manager = prototype( ("libvlc_media_list_view_event_manager", dll), paramflags ) libvlc_media_list_view_event_manager.__doc__ = """Get libvlc_event_manager from this media list view instance. The p_event_manager is immutable, so you don't have to hold the lock @param p_mlv a media list view instance @return libvlc_event_manager """ if hasattr(dll, 'libvlc_media_list_view_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaListView,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_view_count = prototype( ("libvlc_media_list_view_count", dll), paramflags ) libvlc_media_list_view_count.errcheck = check_vlc_exception libvlc_media_list_view_count.__doc__ = """Get count on media list view items @param p_mlv a media list view instance @param p_e initialized exception object @return number of items in media list view """ if hasattr(dll, 'libvlc_media_list_view_item_at_index'): prototype=ctypes.CFUNCTYPE(Media, MediaListView,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_view_item_at_index = prototype( ("libvlc_media_list_view_item_at_index", dll), paramflags ) libvlc_media_list_view_item_at_index.errcheck = check_vlc_exception libvlc_media_list_view_item_at_index.__doc__ = """List media instance in media list view at an index position @param p_mlv a media list view instance @param i_index index position in array where to insert @param p_e initialized exception object @return media instance at position i_pos and libvlc_media_retain() has been called to increase the refcount on this object. """ if hasattr(dll, 'libvlc_media_list_view_children_at_index'): prototype=ctypes.CFUNCTYPE(MediaListView, MediaListView,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_view_children_at_index = prototype( ("libvlc_media_list_view_children_at_index", dll), paramflags ) libvlc_media_list_view_children_at_index.errcheck = check_vlc_exception libvlc_media_list_view_children_at_index.__doc__ = """""" if hasattr(dll, 'libvlc_media_list_view_children_for_item'): prototype=ctypes.CFUNCTYPE(MediaListView, MediaListView,Media,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_list_view_children_for_item = prototype( ("libvlc_media_list_view_children_for_item", dll), paramflags ) libvlc_media_list_view_children_for_item.errcheck = check_vlc_exception libvlc_media_list_view_children_for_item.__doc__ = """""" if hasattr(dll, 'libvlc_media_list_view_parent_media_list'): prototype=ctypes.CFUNCTYPE(MediaList, MediaListView,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_list_view_parent_media_list = prototype( ("libvlc_media_list_view_parent_media_list", dll), paramflags ) libvlc_media_list_view_parent_media_list.errcheck = check_vlc_exception libvlc_media_list_view_parent_media_list.__doc__ = """""" if hasattr(dll, 'libvlc_media_player_new'): prototype=ctypes.CFUNCTYPE(MediaPlayer, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_new = prototype( ("libvlc_media_player_new", dll), paramflags ) libvlc_media_player_new.errcheck = check_vlc_exception libvlc_media_player_new.__doc__ = """Create an empty Media Player object @param p_libvlc_instance the libvlc instance in which the Media Player should be created. @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_new_from_media'): prototype=ctypes.CFUNCTYPE(MediaPlayer, Media,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_new_from_media = prototype( ("libvlc_media_player_new_from_media", dll), paramflags ) libvlc_media_player_new_from_media.errcheck = check_vlc_exception libvlc_media_player_new_from_media.__doc__ = """Create a Media Player object from a Media @param p_md the media. Afterwards the p_md can be safely destroyed. @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_release'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer) paramflags=( (1, ), ) libvlc_media_player_release = prototype( ("libvlc_media_player_release", dll), paramflags ) libvlc_media_player_release.__doc__ = """Release a media_player after use Decrement the reference count of a media player object. If the reference count is 0, then libvlc_media_player_release() will release the media player object. If the media player object has been released, then it should not be used again. @param p_mi the Media Player to free """ if hasattr(dll, 'libvlc_media_player_retain'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer) paramflags=( (1, ), ) libvlc_media_player_retain = prototype( ("libvlc_media_player_retain", dll), paramflags ) libvlc_media_player_retain.__doc__ = """Retain a reference to a media player object. Use libvlc_media_player_release() to decrement reference count. @param p_mi media player object """ if hasattr(dll, 'libvlc_media_player_set_media'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,Media,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_media = prototype( ("libvlc_media_player_set_media", dll), paramflags ) libvlc_media_player_set_media.errcheck = check_vlc_exception libvlc_media_player_set_media.__doc__ = """Set the media that will be used by the media_player. If any, previous md will be released. @param p_mi the Media Player @param p_md the Media. Afterwards the p_md can be safely destroyed. @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_media'): prototype=ctypes.CFUNCTYPE(Media, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_media = prototype( ("libvlc_media_player_get_media", dll), paramflags ) libvlc_media_player_get_media.errcheck = check_vlc_exception libvlc_media_player_get_media.__doc__ = """Get the media used by the media_player. @param p_mi the Media Player @param p_e an initialized exception pointer @return the media associated with p_mi, or NULL if no media is associated """ if hasattr(dll, 'libvlc_media_player_event_manager'): prototype=ctypes.CFUNCTYPE(EventManager, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_event_manager = prototype( ("libvlc_media_player_event_manager", dll), paramflags ) libvlc_media_player_event_manager.errcheck = check_vlc_exception libvlc_media_player_event_manager.__doc__ = """Get the Event Manager from which the media player send event. @param p_mi the Media Player @param p_e an initialized exception pointer @return the event manager associated with p_mi """ if hasattr(dll, 'libvlc_media_player_is_playing'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_is_playing = prototype( ("libvlc_media_player_is_playing", dll), paramflags ) libvlc_media_player_is_playing.errcheck = check_vlc_exception libvlc_media_player_is_playing.__doc__ = """is_playing @param p_mi the Media Player @param p_e an initialized exception pointer @return 1 if the media player is playing, 0 otherwise """ if hasattr(dll, 'libvlc_media_player_play'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_play = prototype( ("libvlc_media_player_play", dll), paramflags ) libvlc_media_player_play.errcheck = check_vlc_exception libvlc_media_player_play.__doc__ = """Play @param p_mi the Media Player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_pause'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_pause = prototype( ("libvlc_media_player_pause", dll), paramflags ) libvlc_media_player_pause.errcheck = check_vlc_exception libvlc_media_player_pause.__doc__ = """Pause @param p_mi the Media Player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_stop'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_stop = prototype( ("libvlc_media_player_stop", dll), paramflags ) libvlc_media_player_stop.errcheck = check_vlc_exception libvlc_media_player_stop.__doc__ = """Stop @param p_mi the Media Player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_set_nsobject'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_void_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_nsobject = prototype( ("libvlc_media_player_set_nsobject", dll), paramflags ) libvlc_media_player_set_nsobject.errcheck = check_vlc_exception libvlc_media_player_set_nsobject.__doc__ = """Set the agl handler where the media player should render its video output. @param p_mi the Media Player @param drawable the agl handler @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_nsobject'): prototype=ctypes.CFUNCTYPE(ctypes.c_void_p, MediaPlayer) paramflags=( (1, ), ) libvlc_media_player_get_nsobject = prototype( ("libvlc_media_player_get_nsobject", dll), paramflags ) libvlc_media_player_get_nsobject.__doc__ = """Get the agl handler previously set with libvlc_media_player_set_agl(). @return the agl handler or 0 if none where set """ if hasattr(dll, 'libvlc_media_player_set_agl'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_uint,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_agl = prototype( ("libvlc_media_player_set_agl", dll), paramflags ) libvlc_media_player_set_agl.errcheck = check_vlc_exception libvlc_media_player_set_agl.__doc__ = """Set the agl handler where the media player should render its video output. @param p_mi the Media Player @param drawable the agl handler @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_agl'): prototype=ctypes.CFUNCTYPE(ctypes.c_uint, MediaPlayer) paramflags=( (1, ), ) libvlc_media_player_get_agl = prototype( ("libvlc_media_player_get_agl", dll), paramflags ) libvlc_media_player_get_agl.__doc__ = """Get the agl handler previously set with libvlc_media_player_set_agl(). @return the agl handler or 0 if none where set """ if hasattr(dll, 'libvlc_media_player_set_xwindow'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_uint,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_xwindow = prototype( ("libvlc_media_player_set_xwindow", dll), paramflags ) libvlc_media_player_set_xwindow.errcheck = check_vlc_exception libvlc_media_player_set_xwindow.__doc__ = """Set an X Window System drawable where the media player should render its video output. If LibVLC was built without X11 output support, then this has no effects. The specified identifier must correspond to an existing Input/Output class X11 window. Pixmaps are <b>not</b> supported. The caller shall ensure that the X11 server is the same as the one the VLC instance has been configured with. If XVideo is <b>not</b> used, it is assumed that the drawable has the following properties in common with the default X11 screen: depth, scan line pad, black pixel. This is a bug. @param p_mi the Media Player @param drawable the ID of the X window @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_xwindow'): prototype=ctypes.CFUNCTYPE(ctypes.c_uint, MediaPlayer) paramflags=( (1, ), ) libvlc_media_player_get_xwindow = prototype( ("libvlc_media_player_get_xwindow", dll), paramflags ) libvlc_media_player_get_xwindow.__doc__ = """Get the X Window System window identifier previously set with libvlc_media_player_set_xwindow(). Note that this will return the identifier even if VLC is not currently using it (for instance if it is playing an audio-only input). @return an X window ID, or 0 if none where set. """ if hasattr(dll, 'libvlc_media_player_set_hwnd'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_void_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_hwnd = prototype( ("libvlc_media_player_set_hwnd", dll), paramflags ) libvlc_media_player_set_hwnd.errcheck = check_vlc_exception libvlc_media_player_set_hwnd.__doc__ = """Set a Win32/Win64 API window handle (HWND) where the media player should render its video output. If LibVLC was built without Win32/Win64 API output support, then this has no effects. @param p_mi the Media Player @param drawable windows handle of the drawable @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_hwnd'): prototype=ctypes.CFUNCTYPE(ctypes.c_void_p, MediaPlayer) paramflags=( (1, ), ) libvlc_media_player_get_hwnd = prototype( ("libvlc_media_player_get_hwnd", dll), paramflags ) libvlc_media_player_get_hwnd.__doc__ = """Get the Windows API window handle (HWND) previously set with libvlc_media_player_set_hwnd(). The handle will be returned even if LibVLC is not currently outputting any video to it. @return a window handle or NULL if there are none. """ if hasattr(dll, 'libvlc_media_player_get_length'): prototype=ctypes.CFUNCTYPE(ctypes.c_longlong, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_length = prototype( ("libvlc_media_player_get_length", dll), paramflags ) libvlc_media_player_get_length.errcheck = check_vlc_exception libvlc_media_player_get_length.__doc__ = """Get the current movie length (in ms). @param p_mi the Media Player @param p_e an initialized exception pointer @return the movie length (in ms). """ if hasattr(dll, 'libvlc_media_player_get_time'): prototype=ctypes.CFUNCTYPE(ctypes.c_longlong, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_time = prototype( ("libvlc_media_player_get_time", dll), paramflags ) libvlc_media_player_get_time.errcheck = check_vlc_exception libvlc_media_player_get_time.__doc__ = """Get the current movie time (in ms). @param p_mi the Media Player @param p_e an initialized exception pointer @return the movie time (in ms). """ if hasattr(dll, 'libvlc_media_player_set_time'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_longlong,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_time = prototype( ("libvlc_media_player_set_time", dll), paramflags ) libvlc_media_player_set_time.errcheck = check_vlc_exception libvlc_media_player_set_time.__doc__ = """Set the movie time (in ms). @param p_mi the Media Player @param the movie time (in ms). @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_position'): prototype=ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_position = prototype( ("libvlc_media_player_get_position", dll), paramflags ) libvlc_media_player_get_position.errcheck = check_vlc_exception libvlc_media_player_get_position.__doc__ = """Get movie position. @param p_mi the Media Player @param p_e an initialized exception pointer @return movie position """ if hasattr(dll, 'libvlc_media_player_set_position'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_float,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_position = prototype( ("libvlc_media_player_set_position", dll), paramflags ) libvlc_media_player_set_position.errcheck = check_vlc_exception libvlc_media_player_set_position.__doc__ = """Set movie position. @param p_mi the Media Player @param p_e an initialized exception pointer @return movie position """ if hasattr(dll, 'libvlc_media_player_set_chapter'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_chapter = prototype( ("libvlc_media_player_set_chapter", dll), paramflags ) libvlc_media_player_set_chapter.errcheck = check_vlc_exception libvlc_media_player_set_chapter.__doc__ = """Set movie chapter @param p_mi the Media Player @param i_chapter chapter number to play @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_chapter'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_chapter = prototype( ("libvlc_media_player_get_chapter", dll), paramflags ) libvlc_media_player_get_chapter.errcheck = check_vlc_exception libvlc_media_player_get_chapter.__doc__ = """Get movie chapter @param p_mi the Media Player @param p_e an initialized exception pointer @return chapter number currently playing """ if hasattr(dll, 'libvlc_media_player_get_chapter_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_chapter_count = prototype( ("libvlc_media_player_get_chapter_count", dll), paramflags ) libvlc_media_player_get_chapter_count.errcheck = check_vlc_exception libvlc_media_player_get_chapter_count.__doc__ = """Get movie chapter count @param p_mi the Media Player @param p_e an initialized exception pointer @return number of chapters in movie """ if hasattr(dll, 'libvlc_media_player_will_play'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_will_play = prototype( ("libvlc_media_player_will_play", dll), paramflags ) libvlc_media_player_will_play.errcheck = check_vlc_exception libvlc_media_player_will_play.__doc__ = """""" if hasattr(dll, 'libvlc_media_player_get_chapter_count_for_title'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_get_chapter_count_for_title = prototype( ("libvlc_media_player_get_chapter_count_for_title", dll), paramflags ) libvlc_media_player_get_chapter_count_for_title.errcheck = check_vlc_exception libvlc_media_player_get_chapter_count_for_title.__doc__ = """Get title chapter count @param p_mi the Media Player @param i_title title @param p_e an initialized exception pointer @return number of chapters in title """ if hasattr(dll, 'libvlc_media_player_set_title'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_title = prototype( ("libvlc_media_player_set_title", dll), paramflags ) libvlc_media_player_set_title.errcheck = check_vlc_exception libvlc_media_player_set_title.__doc__ = """Set movie title @param p_mi the Media Player @param i_title title number to play @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_title'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_title = prototype( ("libvlc_media_player_get_title", dll), paramflags ) libvlc_media_player_get_title.errcheck = check_vlc_exception libvlc_media_player_get_title.__doc__ = """Get movie title @param p_mi the Media Player @param p_e an initialized exception pointer @return title number currently playing """ if hasattr(dll, 'libvlc_media_player_get_title_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_title_count = prototype( ("libvlc_media_player_get_title_count", dll), paramflags ) libvlc_media_player_get_title_count.errcheck = check_vlc_exception libvlc_media_player_get_title_count.__doc__ = """Get movie title count @param p_mi the Media Player @param p_e an initialized exception pointer @return title number count """ if hasattr(dll, 'libvlc_media_player_previous_chapter'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_previous_chapter = prototype( ("libvlc_media_player_previous_chapter", dll), paramflags ) libvlc_media_player_previous_chapter.errcheck = check_vlc_exception libvlc_media_player_previous_chapter.__doc__ = """Set previous chapter @param p_mi the Media Player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_next_chapter'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_next_chapter = prototype( ("libvlc_media_player_next_chapter", dll), paramflags ) libvlc_media_player_next_chapter.errcheck = check_vlc_exception libvlc_media_player_next_chapter.__doc__ = """Set next chapter @param p_mi the Media Player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_rate'): prototype=ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_rate = prototype( ("libvlc_media_player_get_rate", dll), paramflags ) libvlc_media_player_get_rate.errcheck = check_vlc_exception libvlc_media_player_get_rate.__doc__ = """Get movie play rate @param p_mi the Media Player @param p_e an initialized exception pointer @return movie play rate """ if hasattr(dll, 'libvlc_media_player_set_rate'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_float,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_media_player_set_rate = prototype( ("libvlc_media_player_set_rate", dll), paramflags ) libvlc_media_player_set_rate.errcheck = check_vlc_exception libvlc_media_player_set_rate.__doc__ = """Set movie play rate @param p_mi the Media Player @param movie play rate to set @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_get_state'): prototype=ctypes.CFUNCTYPE(State, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_state = prototype( ("libvlc_media_player_get_state", dll), paramflags ) libvlc_media_player_get_state.errcheck = check_vlc_exception libvlc_media_player_get_state.__doc__ = """Get current movie state @param p_mi the Media Player @param p_e an initialized exception pointer @return current movie state as libvlc_state_t """ if hasattr(dll, 'libvlc_media_player_get_fps'): prototype=ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_get_fps = prototype( ("libvlc_media_player_get_fps", dll), paramflags ) libvlc_media_player_get_fps.errcheck = check_vlc_exception libvlc_media_player_get_fps.__doc__ = """Get movie fps rate @param p_mi the Media Player @param p_e an initialized exception pointer @return frames per second (fps) for this playing movie """ if hasattr(dll, 'libvlc_media_player_has_vout'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_has_vout = prototype( ("libvlc_media_player_has_vout", dll), paramflags ) libvlc_media_player_has_vout.errcheck = check_vlc_exception libvlc_media_player_has_vout.__doc__ = """Does this media player have a video output? @param p_md the media player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_is_seekable'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_is_seekable = prototype( ("libvlc_media_player_is_seekable", dll), paramflags ) libvlc_media_player_is_seekable.errcheck = check_vlc_exception libvlc_media_player_is_seekable.__doc__ = """Is this media player seekable? @param p_input the input @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_media_player_can_pause'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_media_player_can_pause = prototype( ("libvlc_media_player_can_pause", dll), paramflags ) libvlc_media_player_can_pause.errcheck = check_vlc_exception libvlc_media_player_can_pause.__doc__ = """Can this media player be paused? @param p_input the input @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_track_description_release'): prototype=ctypes.CFUNCTYPE(None, TrackDescription) paramflags=( (1, ), ) libvlc_track_description_release = prototype( ("libvlc_track_description_release", dll), paramflags ) libvlc_track_description_release.__doc__ = """Release (free) libvlc_track_description_t @param p_track_description the structure to release """ if hasattr(dll, 'libvlc_toggle_fullscreen'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_toggle_fullscreen = prototype( ("libvlc_toggle_fullscreen", dll), paramflags ) libvlc_toggle_fullscreen.errcheck = check_vlc_exception libvlc_toggle_fullscreen.__doc__ = """Toggle fullscreen status on video output. @param p_mediaplayer the media player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_set_fullscreen'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_set_fullscreen = prototype( ("libvlc_set_fullscreen", dll), paramflags ) libvlc_set_fullscreen.errcheck = check_vlc_exception libvlc_set_fullscreen.__doc__ = """Enable or disable fullscreen on a video output. @param p_mediaplayer the media player @param b_fullscreen boolean for fullscreen status @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_get_fullscreen'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_get_fullscreen = prototype( ("libvlc_get_fullscreen", dll), paramflags ) libvlc_get_fullscreen.errcheck = check_vlc_exception libvlc_get_fullscreen.__doc__ = """Get current fullscreen status. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the fullscreen status (boolean) """ if hasattr(dll, 'libvlc_video_get_height'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_height = prototype( ("libvlc_video_get_height", dll), paramflags ) libvlc_video_get_height.errcheck = check_vlc_exception libvlc_video_get_height.__doc__ = """Get current video height. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the video height """ if hasattr(dll, 'libvlc_video_get_width'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_width = prototype( ("libvlc_video_get_width", dll), paramflags ) libvlc_video_get_width.errcheck = check_vlc_exception libvlc_video_get_width.__doc__ = """Get current video width. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the video width """ if hasattr(dll, 'libvlc_video_get_scale'): prototype=ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_scale = prototype( ("libvlc_video_get_scale", dll), paramflags ) libvlc_video_get_scale.errcheck = check_vlc_exception libvlc_video_get_scale.__doc__ = """Get the current video scaling factor. See also libvlc_video_set_scale(). @param p_mediaplayer the media player @return the currently configured zoom factor, or 0. if the video is set to fit to the output window/drawable automatically. """ if hasattr(dll, 'libvlc_video_set_scale'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_float,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_scale = prototype( ("libvlc_video_set_scale", dll), paramflags ) libvlc_video_set_scale.errcheck = check_vlc_exception libvlc_video_set_scale.__doc__ = """Set the video scaling factor. That is the ratio of the number of pixels on screen to the number of pixels in the original decoded video in each dimension. Zero is a special value; it will adjust the video to the output window/drawable (in windowed mode) or the entire screen. Note that not all video outputs support scaling. @param p_mediaplayer the media player @param i_factor the scaling factor, or zero """ if hasattr(dll, 'libvlc_video_get_aspect_ratio'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_aspect_ratio = prototype( ("libvlc_video_get_aspect_ratio", dll), paramflags ) libvlc_video_get_aspect_ratio.errcheck = check_vlc_exception libvlc_video_get_aspect_ratio.__doc__ = """Get current video aspect ratio. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the video aspect ratio """ if hasattr(dll, 'libvlc_video_set_aspect_ratio'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_aspect_ratio = prototype( ("libvlc_video_set_aspect_ratio", dll), paramflags ) libvlc_video_set_aspect_ratio.errcheck = check_vlc_exception libvlc_video_set_aspect_ratio.__doc__ = """Set new video aspect ratio. @param p_mediaplayer the media player @param psz_aspect new video aspect-ratio @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_video_get_spu'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_spu = prototype( ("libvlc_video_get_spu", dll), paramflags ) libvlc_video_get_spu.errcheck = check_vlc_exception libvlc_video_get_spu.__doc__ = """Get current video subtitle. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the video subtitle selected """ if hasattr(dll, 'libvlc_video_get_spu_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_spu_count = prototype( ("libvlc_video_get_spu_count", dll), paramflags ) libvlc_video_get_spu_count.errcheck = check_vlc_exception libvlc_video_get_spu_count.__doc__ = """Get the number of available video subtitles. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the number of available video subtitles """ if hasattr(dll, 'libvlc_video_get_spu_description'): prototype=ctypes.CFUNCTYPE(TrackDescription, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_spu_description = prototype( ("libvlc_video_get_spu_description", dll), paramflags ) libvlc_video_get_spu_description.errcheck = check_vlc_exception libvlc_video_get_spu_description.__doc__ = """Get the description of available video subtitles. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return list containing description of available video subtitles """ if hasattr(dll, 'libvlc_video_set_spu'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_spu = prototype( ("libvlc_video_set_spu", dll), paramflags ) libvlc_video_set_spu.errcheck = check_vlc_exception libvlc_video_set_spu.__doc__ = """Set new video subtitle. @param p_mediaplayer the media player @param i_spu new video subtitle to select @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_video_set_subtitle_file'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_subtitle_file = prototype( ("libvlc_video_set_subtitle_file", dll), paramflags ) libvlc_video_set_subtitle_file.errcheck = check_vlc_exception libvlc_video_set_subtitle_file.__doc__ = """Set new video subtitle file. @param p_mediaplayer the media player @param psz_subtitle new video subtitle file @param p_e an initialized exception pointer @return the success status (boolean) """ if hasattr(dll, 'libvlc_video_get_title_description'): prototype=ctypes.CFUNCTYPE(TrackDescription, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_title_description = prototype( ("libvlc_video_get_title_description", dll), paramflags ) libvlc_video_get_title_description.errcheck = check_vlc_exception libvlc_video_get_title_description.__doc__ = """Get the description of available titles. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return list containing description of available titles """ if hasattr(dll, 'libvlc_video_get_chapter_description'): prototype=ctypes.CFUNCTYPE(TrackDescription, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_get_chapter_description = prototype( ("libvlc_video_get_chapter_description", dll), paramflags ) libvlc_video_get_chapter_description.errcheck = check_vlc_exception libvlc_video_get_chapter_description.__doc__ = """Get the description of available chapters for specific title. @param p_mediaplayer the media player @param i_title selected title @param p_e an initialized exception pointer @return list containing description of available chapter for title i_title """ if hasattr(dll, 'libvlc_video_get_crop_geometry'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_crop_geometry = prototype( ("libvlc_video_get_crop_geometry", dll), paramflags ) libvlc_video_get_crop_geometry.errcheck = check_vlc_exception libvlc_video_get_crop_geometry.__doc__ = """Get current crop filter geometry. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the crop filter geometry """ if hasattr(dll, 'libvlc_video_set_crop_geometry'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_crop_geometry = prototype( ("libvlc_video_set_crop_geometry", dll), paramflags ) libvlc_video_set_crop_geometry.errcheck = check_vlc_exception libvlc_video_set_crop_geometry.__doc__ = """Set new crop filter geometry. @param p_mediaplayer the media player @param psz_geometry new crop filter geometry @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_toggle_teletext'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_toggle_teletext = prototype( ("libvlc_toggle_teletext", dll), paramflags ) libvlc_toggle_teletext.errcheck = check_vlc_exception libvlc_toggle_teletext.__doc__ = """Toggle teletext transparent status on video output. @param p_mediaplayer the media player @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_video_get_teletext'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_teletext = prototype( ("libvlc_video_get_teletext", dll), paramflags ) libvlc_video_get_teletext.errcheck = check_vlc_exception libvlc_video_get_teletext.__doc__ = """Get current teletext page requested. @param p_mediaplayer the media player @param p_e an initialized exception pointer @return the current teletext page requested. """ if hasattr(dll, 'libvlc_video_set_teletext'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_teletext = prototype( ("libvlc_video_set_teletext", dll), paramflags ) libvlc_video_set_teletext.errcheck = check_vlc_exception libvlc_video_set_teletext.__doc__ = """Set new teletext page to retrieve. @param p_mediaplayer the media player @param i_page teletex page number requested @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_video_get_track_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_track_count = prototype( ("libvlc_video_get_track_count", dll), paramflags ) libvlc_video_get_track_count.errcheck = check_vlc_exception libvlc_video_get_track_count.__doc__ = """Get number of available video tracks. @param p_mi media player @param p_e an initialized exception @return the number of available video tracks (int) """ if hasattr(dll, 'libvlc_video_get_track_description'): prototype=ctypes.CFUNCTYPE(TrackDescription, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_track_description = prototype( ("libvlc_video_get_track_description", dll), paramflags ) libvlc_video_get_track_description.errcheck = check_vlc_exception libvlc_video_get_track_description.__doc__ = """Get the description of available video tracks. @param p_mi media player @param p_e an initialized exception @return list with description of available video tracks """ if hasattr(dll, 'libvlc_video_get_track'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_video_get_track = prototype( ("libvlc_video_get_track", dll), paramflags ) libvlc_video_get_track.errcheck = check_vlc_exception libvlc_video_get_track.__doc__ = """Get current video track. @param p_mi media player @param p_e an initialized exception pointer @return the video track (int) """ if hasattr(dll, 'libvlc_video_set_track'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_video_set_track = prototype( ("libvlc_video_set_track", dll), paramflags ) libvlc_video_set_track.errcheck = check_vlc_exception libvlc_video_set_track.__doc__ = """Set video track. @param p_mi media player @param i_track the track (int) @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_video_take_snapshot'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_char_p,ctypes.c_uint,ctypes.c_uint,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(1,),(3,) libvlc_video_take_snapshot = prototype( ("libvlc_video_take_snapshot", dll), paramflags ) libvlc_video_take_snapshot.errcheck = check_vlc_exception libvlc_video_take_snapshot.__doc__ = """Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param p_mi media player instance @param psz_filepath the path where to save the screenshot to @param i_width the snapshot's width @param i_height the snapshot's height @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_audio_output_list_get'): prototype=ctypes.CFUNCTYPE(AudioOutput, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_output_list_get = prototype( ("libvlc_audio_output_list_get", dll), paramflags ) libvlc_audio_output_list_get.errcheck = check_vlc_exception libvlc_audio_output_list_get.__doc__ = """Get the list of available audio outputs @param p_instance libvlc instance @param p_e an initialized exception pointer @return list of available audio outputs, at the end free it with """ if hasattr(dll, 'libvlc_audio_output_list_release'): prototype=ctypes.CFUNCTYPE(None, AudioOutput) paramflags=( (1, ), ) libvlc_audio_output_list_release = prototype( ("libvlc_audio_output_list_release", dll), paramflags ) libvlc_audio_output_list_release.__doc__ = """Free the list of available audio outputs @param p_list list with audio outputs for release """ if hasattr(dll, 'libvlc_audio_output_set'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p) paramflags=(1,),(1,) libvlc_audio_output_set = prototype( ("libvlc_audio_output_set", dll), paramflags ) libvlc_audio_output_set.__doc__ = """Set the audio output. Change will be applied after stop and play. @param p_instance libvlc instance @param psz_name name of audio output, use psz_name of \see libvlc_audio_output_t @return true if function succeded """ if hasattr(dll, 'libvlc_audio_output_device_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p) paramflags=(1,),(1,) libvlc_audio_output_device_count = prototype( ("libvlc_audio_output_device_count", dll), paramflags ) libvlc_audio_output_device_count.__doc__ = """Get count of devices for audio output, these devices are hardware oriented like analor or digital output of sound card @param p_instance libvlc instance @param psz_audio_output - name of audio output, \see libvlc_audio_output_t @return number of devices """ if hasattr(dll, 'libvlc_audio_output_device_longname'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, Instance,ctypes.c_char_p,ctypes.c_int) paramflags=(1,),(1,),(1,) libvlc_audio_output_device_longname = prototype( ("libvlc_audio_output_device_longname", dll), paramflags ) libvlc_audio_output_device_longname.__doc__ = """Get long name of device, if not available short name given @param p_instance libvlc instance @param psz_audio_output - name of audio output, \see libvlc_audio_output_t @param i_device device index @return long name of device """ if hasattr(dll, 'libvlc_audio_output_device_id'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, Instance,ctypes.c_char_p,ctypes.c_int) paramflags=(1,),(1,),(1,) libvlc_audio_output_device_id = prototype( ("libvlc_audio_output_device_id", dll), paramflags ) libvlc_audio_output_device_id.__doc__ = """Get id name of device @param p_instance libvlc instance @param psz_audio_output - name of audio output, \see libvlc_audio_output_t @param i_device device index @return id name of device, use for setting device, need to be free after use """ if hasattr(dll, 'libvlc_audio_output_device_set'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p) paramflags=(1,),(1,),(1,) libvlc_audio_output_device_set = prototype( ("libvlc_audio_output_device_set", dll), paramflags ) libvlc_audio_output_device_set.__doc__ = """Set device for using @param p_instance libvlc instance @param psz_audio_output - name of audio output, \see libvlc_audio_output_t @param psz_device_id device """ if hasattr(dll, 'libvlc_audio_output_get_device_type'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_output_get_device_type = prototype( ("libvlc_audio_output_get_device_type", dll), paramflags ) libvlc_audio_output_get_device_type.errcheck = check_vlc_exception libvlc_audio_output_get_device_type.__doc__ = """Get current audio device type. Device type describes something like character of output sound - stereo sound, 2.1, 5.1 etc @param p_instance vlc instance @param p_e an initialized exception pointer @return the audio devices type \see libvlc_audio_output_device_types_t """ if hasattr(dll, 'libvlc_audio_output_set_device_type'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_audio_output_set_device_type = prototype( ("libvlc_audio_output_set_device_type", dll), paramflags ) libvlc_audio_output_set_device_type.errcheck = check_vlc_exception libvlc_audio_output_set_device_type.__doc__ = """Set current audio device type. @param p_instance vlc instance @param device_type the audio device type, @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_audio_toggle_mute'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_toggle_mute = prototype( ("libvlc_audio_toggle_mute", dll), paramflags ) libvlc_audio_toggle_mute.errcheck = check_vlc_exception libvlc_audio_toggle_mute.__doc__ = """Toggle mute status. @param p_instance libvlc instance @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_audio_get_mute'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_get_mute = prototype( ("libvlc_audio_get_mute", dll), paramflags ) libvlc_audio_get_mute.errcheck = check_vlc_exception libvlc_audio_get_mute.__doc__ = """Get current mute status. @param p_instance libvlc instance @param p_e an initialized exception pointer @return the mute status (boolean) """ if hasattr(dll, 'libvlc_audio_set_mute'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_audio_set_mute = prototype( ("libvlc_audio_set_mute", dll), paramflags ) libvlc_audio_set_mute.errcheck = check_vlc_exception libvlc_audio_set_mute.__doc__ = """Set mute status. @param p_instance libvlc instance @param status If status is true then mute, otherwise unmute @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_audio_get_volume'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_get_volume = prototype( ("libvlc_audio_get_volume", dll), paramflags ) libvlc_audio_get_volume.errcheck = check_vlc_exception libvlc_audio_get_volume.__doc__ = """Get current audio level. @param p_instance libvlc instance @param p_e an initialized exception pointer @return the audio level (int) """ if hasattr(dll, 'libvlc_audio_set_volume'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_audio_set_volume = prototype( ("libvlc_audio_set_volume", dll), paramflags ) libvlc_audio_set_volume.errcheck = check_vlc_exception libvlc_audio_set_volume.__doc__ = """Set current audio level. @param p_instance libvlc instance @param i_volume the volume (int) @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_audio_get_track_count'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_get_track_count = prototype( ("libvlc_audio_get_track_count", dll), paramflags ) libvlc_audio_get_track_count.errcheck = check_vlc_exception libvlc_audio_get_track_count.__doc__ = """Get number of available audio tracks. @param p_mi media player @param p_e an initialized exception @return the number of available audio tracks (int) """ if hasattr(dll, 'libvlc_audio_get_track_description'): prototype=ctypes.CFUNCTYPE(TrackDescription, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_get_track_description = prototype( ("libvlc_audio_get_track_description", dll), paramflags ) libvlc_audio_get_track_description.errcheck = check_vlc_exception libvlc_audio_get_track_description.__doc__ = """Get the description of available audio tracks. @param p_mi media player @param p_e an initialized exception @return list with description of available audio tracks """ if hasattr(dll, 'libvlc_audio_get_track'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_get_track = prototype( ("libvlc_audio_get_track", dll), paramflags ) libvlc_audio_get_track.errcheck = check_vlc_exception libvlc_audio_get_track.__doc__ = """Get current audio track. @param p_mi media player @param p_e an initialized exception pointer @return the audio track (int) """ if hasattr(dll, 'libvlc_audio_set_track'): prototype=ctypes.CFUNCTYPE(None, MediaPlayer,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_audio_set_track = prototype( ("libvlc_audio_set_track", dll), paramflags ) libvlc_audio_set_track.errcheck = check_vlc_exception libvlc_audio_set_track.__doc__ = """Set current audio track. @param p_mi media player @param i_track the track (int) @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_audio_get_channel'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_audio_get_channel = prototype( ("libvlc_audio_get_channel", dll), paramflags ) libvlc_audio_get_channel.errcheck = check_vlc_exception libvlc_audio_get_channel.__doc__ = """Get current audio channel. @param p_instance vlc instance @param p_e an initialized exception pointer @return the audio channel \see libvlc_audio_output_channel_t """ if hasattr(dll, 'libvlc_audio_set_channel'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_audio_set_channel = prototype( ("libvlc_audio_set_channel", dll), paramflags ) libvlc_audio_set_channel.errcheck = check_vlc_exception libvlc_audio_set_channel.__doc__ = """Set current audio channel. @param p_instance vlc instance @param channel the audio channel, \see libvlc_audio_output_channel_t @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_release'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.POINTER(VLCException)) paramflags=(1,),(3,) libvlc_vlm_release = prototype( ("libvlc_vlm_release", dll), paramflags ) libvlc_vlm_release.errcheck = check_vlc_exception libvlc_vlm_release.__doc__ = """Release the vlm instance related to the given libvlc_instance_t @param p_instance the instance @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_add_broadcast'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,ListPOINTER(ctypes.c_char_p),ctypes.c_int,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(3,) libvlc_vlm_add_broadcast = prototype( ("libvlc_vlm_add_broadcast", dll), paramflags ) libvlc_vlm_add_broadcast.errcheck = check_vlc_exception libvlc_vlm_add_broadcast.__doc__ = """Add a broadcast, with one input. @param p_instance the instance @param psz_name the name of the new broadcast @param psz_input the input MRL @param psz_output the output MRL (the parameter to the "sout" variable) @param i_options number of additional options @param ppsz_options additional options @param b_enabled boolean for enabling the new broadcast @param b_loop Should this broadcast be played in loop ? @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_add_vod'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,ListPOINTER(ctypes.c_char_p),ctypes.c_int,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(1,),(1,),(1,),(1,),(3,) libvlc_vlm_add_vod = prototype( ("libvlc_vlm_add_vod", dll), paramflags ) libvlc_vlm_add_vod.errcheck = check_vlc_exception libvlc_vlm_add_vod.__doc__ = """Add a vod, with one input. @param p_instance the instance @param psz_name the name of the new vod media @param psz_input the input MRL @param i_options number of additional options @param ppsz_options additional options @param b_enabled boolean for enabling the new vod @param psz_mux the muxer of the vod media @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_del_media'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_vlm_del_media = prototype( ("libvlc_vlm_del_media", dll), paramflags ) libvlc_vlm_del_media.errcheck = check_vlc_exception libvlc_vlm_del_media.__doc__ = """Delete a media (VOD or broadcast). @param p_instance the instance @param psz_name the media to delete @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_set_enabled'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_set_enabled = prototype( ("libvlc_vlm_set_enabled", dll), paramflags ) libvlc_vlm_set_enabled.errcheck = check_vlc_exception libvlc_vlm_set_enabled.__doc__ = """Enable or disable a media (VOD or broadcast). @param p_instance the instance @param psz_name the media to work on @param b_enabled the new status @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_set_output'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_set_output = prototype( ("libvlc_vlm_set_output", dll), paramflags ) libvlc_vlm_set_output.errcheck = check_vlc_exception libvlc_vlm_set_output.__doc__ = """Set the output for a media. @param p_instance the instance @param psz_name the media to work on @param psz_output the output MRL (the parameter to the "sout" variable) @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_set_input'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_set_input = prototype( ("libvlc_vlm_set_input", dll), paramflags ) libvlc_vlm_set_input.errcheck = check_vlc_exception libvlc_vlm_set_input.__doc__ = """Set a media's input MRL. This will delete all existing inputs and add the specified one. @param p_instance the instance @param psz_name the media to work on @param psz_input the input MRL @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_add_input'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_add_input = prototype( ("libvlc_vlm_add_input", dll), paramflags ) libvlc_vlm_add_input.errcheck = check_vlc_exception libvlc_vlm_add_input.__doc__ = """Add a media's input MRL. This will add the specified one. @param p_instance the instance @param psz_name the media to work on @param psz_input the input MRL @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_set_loop'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_set_loop = prototype( ("libvlc_vlm_set_loop", dll), paramflags ) libvlc_vlm_set_loop.errcheck = check_vlc_exception libvlc_vlm_set_loop.__doc__ = """Set a media's loop status. @param p_instance the instance @param psz_name the media to work on @param b_loop the new status @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_set_mux'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_set_mux = prototype( ("libvlc_vlm_set_mux", dll), paramflags ) libvlc_vlm_set_mux.errcheck = check_vlc_exception libvlc_vlm_set_mux.__doc__ = """Set a media's vod muxer. @param p_instance the instance @param psz_name the media to work on @param psz_mux the new muxer @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_change_media'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,ListPOINTER(ctypes.c_char_p),ctypes.c_int,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(3,) libvlc_vlm_change_media = prototype( ("libvlc_vlm_change_media", dll), paramflags ) libvlc_vlm_change_media.errcheck = check_vlc_exception libvlc_vlm_change_media.__doc__ = """Edit the parameters of a media. This will delete all existing inputs and add the specified one. @param p_instance the instance @param psz_name the name of the new broadcast @param psz_input the input MRL @param psz_output the output MRL (the parameter to the "sout" variable) @param i_options number of additional options @param ppsz_options additional options @param b_enabled boolean for enabling the new broadcast @param b_loop Should this broadcast be played in loop ? @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_play_media'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_vlm_play_media = prototype( ("libvlc_vlm_play_media", dll), paramflags ) libvlc_vlm_play_media.errcheck = check_vlc_exception libvlc_vlm_play_media.__doc__ = """Play the named broadcast. @param p_instance the instance @param psz_name the name of the broadcast @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_stop_media'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_vlm_stop_media = prototype( ("libvlc_vlm_stop_media", dll), paramflags ) libvlc_vlm_stop_media.errcheck = check_vlc_exception libvlc_vlm_stop_media.__doc__ = """Stop the named broadcast. @param p_instance the instance @param psz_name the name of the broadcast @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_pause_media'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_vlm_pause_media = prototype( ("libvlc_vlm_pause_media", dll), paramflags ) libvlc_vlm_pause_media.errcheck = check_vlc_exception libvlc_vlm_pause_media.__doc__ = """Pause the named broadcast. @param p_instance the instance @param psz_name the name of the broadcast @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_seek_media'): prototype=ctypes.CFUNCTYPE(None, Instance,ctypes.c_char_p,ctypes.c_float,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_seek_media = prototype( ("libvlc_vlm_seek_media", dll), paramflags ) libvlc_vlm_seek_media.errcheck = check_vlc_exception libvlc_vlm_seek_media.__doc__ = """Seek in the named broadcast. @param p_instance the instance @param psz_name the name of the broadcast @param f_percentage the percentage to seek to @param p_e an initialized exception pointer """ if hasattr(dll, 'libvlc_vlm_show_media'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, Instance,ctypes.c_char_p,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(3,) libvlc_vlm_show_media = prototype( ("libvlc_vlm_show_media", dll), paramflags ) libvlc_vlm_show_media.errcheck = check_vlc_exception libvlc_vlm_show_media.__doc__ = """Return information about the named broadcast. \bug will always return NULL @param p_instance the instance @param psz_name the name of the broadcast @param p_e an initialized exception pointer @return string with information about named media """ if hasattr(dll, 'libvlc_vlm_get_media_instance_position'): prototype=ctypes.CFUNCTYPE(ctypes.c_float, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_position = prototype( ("libvlc_vlm_get_media_instance_position", dll), paramflags ) libvlc_vlm_get_media_instance_position.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_position.__doc__ = """Get vlm_media instance position by name or instance id @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return position as float """ if hasattr(dll, 'libvlc_vlm_get_media_instance_time'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_time = prototype( ("libvlc_vlm_get_media_instance_time", dll), paramflags ) libvlc_vlm_get_media_instance_time.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_time.__doc__ = """Get vlm_media instance time by name or instance id @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return time as integer """ if hasattr(dll, 'libvlc_vlm_get_media_instance_length'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_length = prototype( ("libvlc_vlm_get_media_instance_length", dll), paramflags ) libvlc_vlm_get_media_instance_length.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_length.__doc__ = """Get vlm_media instance length by name or instance id @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return length of media item """ if hasattr(dll, 'libvlc_vlm_get_media_instance_rate'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_rate = prototype( ("libvlc_vlm_get_media_instance_rate", dll), paramflags ) libvlc_vlm_get_media_instance_rate.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_rate.__doc__ = """Get vlm_media instance playback rate by name or instance id @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return playback rate """ if hasattr(dll, 'libvlc_vlm_get_media_instance_title'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_title = prototype( ("libvlc_vlm_get_media_instance_title", dll), paramflags ) libvlc_vlm_get_media_instance_title.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_title.__doc__ = """Get vlm_media instance title number by name or instance id \bug will always return 0 @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return title as number """ if hasattr(dll, 'libvlc_vlm_get_media_instance_chapter'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_chapter = prototype( ("libvlc_vlm_get_media_instance_chapter", dll), paramflags ) libvlc_vlm_get_media_instance_chapter.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_chapter.__doc__ = """Get vlm_media instance chapter number by name or instance id \bug will always return 0 @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return chapter as number """ if hasattr(dll, 'libvlc_vlm_get_media_instance_seekable'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, Instance,ctypes.c_char_p,ctypes.c_int,ctypes.POINTER(VLCException)) paramflags=(1,),(1,),(1,),(3,) libvlc_vlm_get_media_instance_seekable = prototype( ("libvlc_vlm_get_media_instance_seekable", dll), paramflags ) libvlc_vlm_get_media_instance_seekable.errcheck = check_vlc_exception libvlc_vlm_get_media_instance_seekable.__doc__ = """Is libvlc instance seekable ? \bug will always return 0 @param p_instance a libvlc instance @param psz_name name of vlm media instance @param i_instance instance id @param p_e an initialized exception pointer @return 1 if seekable, 0 if not """ if hasattr(dll, 'mediacontrol_RGBPicture__free'): prototype=ctypes.CFUNCTYPE(None, ctypes.POINTER(RGBPicture)) paramflags=( (1, ), ) mediacontrol_RGBPicture__free = prototype( ("mediacontrol_RGBPicture__free", dll), paramflags ) mediacontrol_RGBPicture__free.__doc__ = """Free a RGBPicture structure. @param pic: the RGBPicture structure """ if hasattr(dll, 'mediacontrol_StreamInformation__free'): prototype=ctypes.CFUNCTYPE(None, ctypes.POINTER(MediaControlStreamInformation)) paramflags=( (1, ), ) mediacontrol_StreamInformation__free = prototype( ("mediacontrol_StreamInformation__free", dll), paramflags ) mediacontrol_StreamInformation__free.__doc__ = """Free a StreamInformation structure. @param pic: the StreamInformation structure """ if hasattr(dll, 'mediacontrol_exception_create'): prototype=ctypes.CFUNCTYPE(MediaControlException) paramflags= tuple() mediacontrol_exception_create = prototype( ("mediacontrol_exception_create", dll), paramflags ) mediacontrol_exception_create.__doc__ = """Instanciate and initialize an exception structure. @return the exception """ if hasattr(dll, 'mediacontrol_exception_init'): prototype=ctypes.CFUNCTYPE(None, MediaControlException) paramflags=( (1, ), ) mediacontrol_exception_init = prototype( ("mediacontrol_exception_init", dll), paramflags ) mediacontrol_exception_init.__doc__ = """Initialize an existing exception structure. @param p_exception the exception to initialize. """ if hasattr(dll, 'mediacontrol_exception_cleanup'): prototype=ctypes.CFUNCTYPE(None, MediaControlException) paramflags=( (1, ), ) mediacontrol_exception_cleanup = prototype( ("mediacontrol_exception_cleanup", dll), paramflags ) mediacontrol_exception_cleanup.__doc__ = """Clean up an existing exception structure after use. @param p_exception the exception to clean up. """ if hasattr(dll, 'mediacontrol_exception_free'): prototype=ctypes.CFUNCTYPE(None, MediaControlException) paramflags=( (1, ), ) mediacontrol_exception_free = prototype( ("mediacontrol_exception_free", dll), paramflags ) mediacontrol_exception_free.__doc__ = """Free an exception structure created with mediacontrol_exception_create(). @return the exception """ if hasattr(dll, 'mediacontrol_new'): prototype=ctypes.CFUNCTYPE(MediaControl, ctypes.c_int,ListPOINTER(ctypes.c_char_p),MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_new = prototype( ("mediacontrol_new", dll), paramflags ) mediacontrol_new.__doc__ = """Create a MediaControl instance with parameters @param argc the number of arguments @param argv parameters @param exception an initialized exception pointer @return a mediacontrol_Instance """ if hasattr(dll, 'mediacontrol_new_from_instance'): prototype=ctypes.CFUNCTYPE(MediaControl, Instance,MediaControlException) paramflags=(1,),(1,) mediacontrol_new_from_instance = prototype( ("mediacontrol_new_from_instance", dll), paramflags ) mediacontrol_new_from_instance.__doc__ = """Create a MediaControl instance from an existing libvlc instance @param p_instance the libvlc instance @param exception an initialized exception pointer @return a mediacontrol_Instance """ if hasattr(dll, 'mediacontrol_get_libvlc_instance'): prototype=ctypes.CFUNCTYPE(Instance, MediaControl) paramflags=( (1, ), ) mediacontrol_get_libvlc_instance = prototype( ("mediacontrol_get_libvlc_instance", dll), paramflags ) mediacontrol_get_libvlc_instance.__doc__ = """Get the associated libvlc instance @param self: the mediacontrol instance @return a libvlc instance """ if hasattr(dll, 'mediacontrol_get_media_player'): prototype=ctypes.CFUNCTYPE(MediaPlayer, MediaControl) paramflags=( (1, ), ) mediacontrol_get_media_player = prototype( ("mediacontrol_get_media_player", dll), paramflags ) mediacontrol_get_media_player.__doc__ = """Get the associated libvlc_media_player @param self: the mediacontrol instance @return a libvlc_media_player_t instance """ if hasattr(dll, 'mediacontrol_get_media_position'): prototype=ctypes.CFUNCTYPE(ctypes.POINTER(MediaControlPosition), MediaControl,PositionOrigin,PositionKey,MediaControlException) paramflags=(1,),(1,),(1,),(1,) mediacontrol_get_media_position = prototype( ("mediacontrol_get_media_position", dll), paramflags ) mediacontrol_get_media_position.__doc__ = """Get the current position @param self the mediacontrol instance @param an_origin the position origin @param a_key the position unit @param exception an initialized exception pointer @return a mediacontrol_Position """ if hasattr(dll, 'mediacontrol_set_media_position'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.POINTER(MediaControlPosition),MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_set_media_position = prototype( ("mediacontrol_set_media_position", dll), paramflags ) mediacontrol_set_media_position.__doc__ = """Set the position @param self the mediacontrol instance @param a_position a mediacontrol_Position @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_start'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.POINTER(MediaControlPosition),MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_start = prototype( ("mediacontrol_start", dll), paramflags ) mediacontrol_start.__doc__ = """Play the movie at a given position @param self the mediacontrol instance @param a_position a mediacontrol_Position @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_pause'): prototype=ctypes.CFUNCTYPE(None, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_pause = prototype( ("mediacontrol_pause", dll), paramflags ) mediacontrol_pause.__doc__ = """Pause the movie at a given position @param self the mediacontrol instance @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_resume'): prototype=ctypes.CFUNCTYPE(None, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_resume = prototype( ("mediacontrol_resume", dll), paramflags ) mediacontrol_resume.__doc__ = """Resume the movie at a given position @param self the mediacontrol instance @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_stop'): prototype=ctypes.CFUNCTYPE(None, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_stop = prototype( ("mediacontrol_stop", dll), paramflags ) mediacontrol_stop.__doc__ = """Stop the movie at a given position @param self the mediacontrol instance @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_exit'): prototype=ctypes.CFUNCTYPE(None, MediaControl) paramflags=( (1, ), ) mediacontrol_exit = prototype( ("mediacontrol_exit", dll), paramflags ) mediacontrol_exit.__doc__ = """Exit the player @param self the mediacontrol instance """ if hasattr(dll, 'mediacontrol_set_mrl'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.c_char_p,MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_set_mrl = prototype( ("mediacontrol_set_mrl", dll), paramflags ) mediacontrol_set_mrl.__doc__ = """Set the MRL to be played. @param self the mediacontrol instance @param psz_file the MRL @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_get_mrl'): prototype=ctypes.CFUNCTYPE(ctypes.c_char_p, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_get_mrl = prototype( ("mediacontrol_get_mrl", dll), paramflags ) mediacontrol_get_mrl.__doc__ = """Get the MRL to be played. @param self the mediacontrol instance @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_snapshot'): prototype=ctypes.CFUNCTYPE(ctypes.POINTER(RGBPicture), MediaControl,ctypes.POINTER(MediaControlPosition),MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_snapshot = prototype( ("mediacontrol_snapshot", dll), paramflags ) mediacontrol_snapshot.__doc__ = """Get a snapshot @param self the mediacontrol instance @param a_position the desired position (ignored for now) @param exception an initialized exception pointer @return a RGBpicture """ if hasattr(dll, 'mediacontrol_display_text'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.c_char_p,ctypes.POINTER(MediaControlPosition),ctypes.POINTER(MediaControlPosition),MediaControlException) paramflags=(1,),(1,),(1,),(1,),(1,) mediacontrol_display_text = prototype( ("mediacontrol_display_text", dll), paramflags ) mediacontrol_display_text.__doc__ = """ Displays the message string, between "begin" and "end" positions. @param self the mediacontrol instance @param message the message to display @param begin the begin position @param end the end position @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_get_stream_information'): prototype=ctypes.CFUNCTYPE(ctypes.POINTER(MediaControlStreamInformation), MediaControl,PositionKey,MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_get_stream_information = prototype( ("mediacontrol_get_stream_information", dll), paramflags ) mediacontrol_get_stream_information.__doc__ = """ Get information about a stream @param self the mediacontrol instance @param a_key the time unit @param exception an initialized exception pointer @return a mediacontrol_StreamInformation """ if hasattr(dll, 'mediacontrol_sound_get_volume'): prototype=ctypes.CFUNCTYPE(ctypes.c_short, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_sound_get_volume = prototype( ("mediacontrol_sound_get_volume", dll), paramflags ) mediacontrol_sound_get_volume.__doc__ = """Get the current audio level, normalized in [0..100] @param self the mediacontrol instance @param exception an initialized exception pointer @return the volume """ if hasattr(dll, 'mediacontrol_sound_set_volume'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.c_short,MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_sound_set_volume = prototype( ("mediacontrol_sound_set_volume", dll), paramflags ) mediacontrol_sound_set_volume.__doc__ = """Set the audio level @param self the mediacontrol instance @param volume the volume (normalized in [0..100]) @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_set_visual'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaControl,ctypes.c_ulong,MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_set_visual = prototype( ("mediacontrol_set_visual", dll), paramflags ) mediacontrol_set_visual.__doc__ = """Set the video output window @param self the mediacontrol instance @param visual_id the Xid or HWND, depending on the platform @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_get_rate'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_get_rate = prototype( ("mediacontrol_get_rate", dll), paramflags ) mediacontrol_get_rate.__doc__ = """Get the current playing rate, in percent @param self the mediacontrol instance @param exception an initialized exception pointer @return the rate """ if hasattr(dll, 'mediacontrol_set_rate'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.c_int,MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_set_rate = prototype( ("mediacontrol_set_rate", dll), paramflags ) mediacontrol_set_rate.__doc__ = """Set the playing rate, in percent @param self the mediacontrol instance @param rate the desired rate @param exception an initialized exception pointer """ if hasattr(dll, 'mediacontrol_get_fullscreen'): prototype=ctypes.CFUNCTYPE(ctypes.c_int, MediaControl,MediaControlException) paramflags=(1,),(1,) mediacontrol_get_fullscreen = prototype( ("mediacontrol_get_fullscreen", dll), paramflags ) mediacontrol_get_fullscreen.__doc__ = """Get current fullscreen status @param self the mediacontrol instance @param exception an initialized exception pointer @return the fullscreen status """ if hasattr(dll, 'mediacontrol_set_fullscreen'): prototype=ctypes.CFUNCTYPE(None, MediaControl,ctypes.c_int,MediaControlException) paramflags=(1,),(1,),(1,) mediacontrol_set_fullscreen = prototype( ("mediacontrol_set_fullscreen", dll), paramflags ) mediacontrol_set_fullscreen.__doc__ = """Set fullscreen status @param self the mediacontrol instance @param b_fullscreen the desired status @param exception an initialized exception pointer """ ### Start of footer.py ### class MediaEvent(ctypes.Structure): _fields_ = [ ('media_name', ctypes.c_char_p), ('instance_name', ctypes.c_char_p), ] class EventUnion(ctypes.Union): _fields_ = [ ('meta_type', ctypes.c_uint), ('new_child', ctypes.c_uint), ('new_duration', ctypes.c_longlong), ('new_status', ctypes.c_int), ('media', ctypes.c_void_p), ('new_state', ctypes.c_uint), # Media instance ('new_position', ctypes.c_float), ('new_time', ctypes.c_longlong), ('new_title', ctypes.c_int), ('new_seekable', ctypes.c_longlong), ('new_pausable', ctypes.c_longlong), # FIXME: Skipped MediaList and MediaListView... ('filename', ctypes.c_char_p), ('new_length', ctypes.c_longlong), ('media_event', MediaEvent), ] class Event(ctypes.Structure): _fields_ = [ ('type', EventType), ('object', ctypes.c_void_p), ('u', EventUnion), ] # Decorator for callback methods callbackmethod=ctypes.CFUNCTYPE(None, Event, ctypes.c_void_p) # Example callback method @callbackmethod def debug_callback(event, data): print "Debug callback method" print "Event:", event.type print "Data", data if __name__ == '__main__': try: from msvcrt import getch except ImportError: def getch(): import tty import termios fd=sys.stdin.fileno() old_settings=termios.tcgetattr(fd) try: tty.setraw(fd) ch=sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch @callbackmethod def end_callback(event, data): print "End of stream" sys.exit(0) if sys.argv[1:]: instance=Instance() media=instance.media_new(sys.argv[1]) player=instance.media_player_new() player.set_media(media) player.play() event_manager=player.event_manager() event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback, None) def print_info(): """Print information about the media.""" media=player.get_media() print "State:", player.get_state() print "Media:", media.get_mrl() try: print "Current time:", player.get_time(), "/", media.get_duration() print "Position:", player.get_position() print "FPS:", player.get_fps() print "Rate:", player.get_rate() print "Video size: (%d, %d)" % (player.video_get_width(), player.video_get_height()) except Exception: pass def forward(): """Go forward 1s""" player.set_time(player.get_time() + 1000) def one_frame_forward(): """Go forward one frame""" player.set_time(player.get_time() + long(1000 / (player.get_fps() or 25))) def one_frame_backward(): """Go backward one frame""" player.set_time(player.get_time() - long(1000 / (player.get_fps() or 25))) def backward(): """Go backward 1s""" player.set_time(player.get_time() - 1000) def print_help(): """Print help """ print "Commands:" for k, m in keybindings.iteritems(): print " %s: %s" % (k, (m.__doc__ or m.__name__).splitlines()[0]) print " 1-9: go to the given fraction of the movie" def quit_app(): """Exit.""" sys.exit(0) keybindings={ 'f': player.toggle_fullscreen, ' ': player.pause, '+': forward, '-': backward, '.': one_frame_forward, ',': one_frame_backward, '?': print_help, 'i': print_info, 'q': quit_app, } print "Press q to quit, ? to get help." while True: k=getch() o=ord(k) method=keybindings.get(k, None) if method is not None: method() elif o >= 49 and o <= 57: # Numeric value. Jump to a fraction of the movie. v=0.1*(o-48) player.set_position(v) # Not wrapped methods: # libvlc_get_version # libvlc_exception_get_message # libvlc_media_list_view_remove_at_index # libvlc_media_list_view_insert_at_index # libvlc_get_compiler # mediacontrol_RGBPicture__free # libvlc_free # libvlc_event_type_name # libvlc_get_vlc_instance # libvlc_media_list_view_add_item # libvlc_get_changeset # libvlc_exception_init # mediacontrol_exception_init # mediacontrol_exception_create # libvlc_new # mediacontrol_exception_cleanup # libvlc_exception_raise # mediacontrol_new # libvlc_media_list_view_index_of_item # libvlc_exception_raised # mediacontrol_StreamInformation__free # mediacontrol_PlaylistSeq__free # libvlc_exception_clear # mediacontrol_exception_free
zicbee-vlc
/zicbee-vlc-0.9.2.tar.gz/zicbee-vlc-0.9.2/zicbee_vlc/vlc.py
vlc.py
User documentation ================== For a shorter introduction, see `Quickstart`_ page. Install ------- Instructions (skip this if you already installed zicbee) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Preferably, download and unzip a `packaged release`_ or clone the workshop repository if you plan to hack the code: :: ~/programs/> hg clone http://zicbee.gnux.info/hg/zicbee-workshop/ bee ~/programs/> cd bee Now you should be able to run **manage** program so every source will be retrieved and a compact distribution will be built. :: ~/programs/bee/> ./manage ... You can also install it in the standard setuptools way: :: easy_install -U zicbee or pip install -U zicbee "-U" means update in pip and easy_install. `setuptools`_ or distribute is required for that. After that, you should have working "zicdb", "wasp" and "zicserve" binaries. Feel free to run execute with "help" as the only argument! Note that zicserve is just a convenient way to run "zicdb serve". Dependencies: ............. - 3.0 > Python >= 2.6 - or Python 2.5 with: - cjson [json] - or simplejson [json] - or demjson [json] Knowledges about shell usage and readline is a good point. - any shell, preferably with readline enabled [ui_core] - webpy >= 0.3 [ui_www] - buzhug [database]optional dependencies: - mplayer (the open one, mostly known by free software users) [player] - vlc [player] - python-gst (gstreamer) [player] For playback, according to the backend, you will need either: - mplayer(.exe) in your PATH - libvlc available on your system - gstreamer + pygst bindings Once you installed zicbee (unpacking a pack or installing individual packages) on computers with music, run those shell commands on each : :: % zicdb scan <base directory containing music files> wait a little, depending on your library size ... :: % zicserve now the server is looping, you can access the music of this computer remotely (or not ;)) If you installed zicbee-mplayer (or vlc or gst), then you can use this device to play music too. If you want to use your own player with zicbee, just search the database and request some playlist (m3u) output ! Open your web browser, point `http://localhost:9090/`_ and you should see some graphics. To know all the commands, try **zicdb help** command. Note that there is a shortcut for **zicdb serve**, you can just type **zicserve**. Don't forget to run **wasp help** for all clients commands (most, in fact). Help yourself ------------- :: % wasp help % zicdb help Pattern/match command --------------------- Pattern is everywhere, used in www interface, in many shell commands (search, play, etc...). Syntax summary: :: field: value [ [or|and] field2: value2 ]... for length, value may be preceded by **<** or **>** if field name starts with a capital, the search is case-sensitive Possible fields: - id (compact style) - genre - artist - album - title - track - score - tags - length - auto <special: auto-expand artists according to last.fm statistics) - pls <special: save/update a playlist> Commented Examples ++++++++++++++++++ :: % wasp search artist: =shakira length: > 3*60 > songs from "shakira" and of more than 3 min :: % wasp search artist: the rolling length: > 3*60 or artist: black > songs with "the rolling" or "black" in artist name and of more than 3 min :: % wasp search artist: shak length: > 3*60 and title: mo > songs with "shak" in artist name and of more than 3 min and with "moon" on the title :: % wasp search tags: jazz title: moon > songs tagged "jazz" and with titles containing "moon" :: % wasp search score: >2 > songs with a score higher than 2 :: % wasp search score: >2 score: <= 3 tags: rock length: <= 120 > a quite dumb search ;) (the selected songs will have a score of 3, less than 2 min and tagged as "rock") Basic commands details ====================== Most commands will read ::db_host and ::player_host variables (see **set** command). Common to zicbee and wasp ------------------------- help ++++ List all available commands (with associated help if available) set +++ Without argument, lists the variables If two arguments are passed, just set the value List of "set" variables ....................... fork ( yes,no ) :::::::::::::::: tells if the server should fork or not enable_history ( yes, no ) :::::::::::::::::::::::::: enable commands history in wasp web_skin ( default ) ::::::::::::::::::::: skin name (only one now) players* ( off,gst,mplayer,vlc ) :::::::::::::::::::::::::::::::: player backend preference* download_dir ( /tmp ) ::::::::::::::::::::: download directory for **get** command mainly socket_timeout ( 30 ) ::::::::::::::::::::: sets the default socket timeout (increase the value if you have timeout problems) default_search ( off, "any valid search pattern" ) :::::::::::::::::::::::::::::::::::::::::::::::::: sets the default pattern used in "play" command when no parameter is specified allow_remote_admin ( yes,no ) ::::::::::::::::::::::::::::: allow usage of **kill** and **stfu** from any host streaming_file ( /tmp/zsong ) ::::::::::::::::::::::::::::: temporary file used in player history_size ( 50 ) ::::::::::::::::::: size of commandline history | custom_extensions* ( mpg, mp2 ) ::::::::::::::::::::::::::::::: adds support for officially unsupported extensions to **scan** command* player_host* ( localhost:9090 ) ::::::::::::::::::::::::::::::: the host you want to play music on* db_host ( localhost:9090 ) :::::::::::::::::::::::::: the host you want to take music from notify ( yes,no ) ::::::::::::::::: add desktop notification support to advert song changes default_port ( 9090 ) ::::::::::::::::::::: port used by default if not specififed debug ( off,on ) :::::::::::::::: enables debuging mode autoshuffle ( yes,no ) :::::::::::::::::::::: automatically runs "shuffle" command when a playlist is fully loaded loop ( yes,no ) ::::::::::::::: runs player in loop, infinitely, if **autoshuffle** is enabled, then re- shuffle the playlist before each loop {*} Multi values can be passed, using a coma (","), but **NO SPACES**. Note: "on" and "yes" are equivalent value, same for "off" and "no". zicdb specific -------------- Note that "command::argument1[=foo][:argument2...]" syntax is only supported by zicdb. serve[::pure] +++++++++++++ Runs a user-accessible www server on port 9090 pure: don't allow player functionality access You can alternatively use the "zicserve" alias. scan [directory|archive]... +++++++++++++++++++++++++++ Scan directories/archive for files and add them to the database search[::format] "match command" ++++++++++++++++++++++++++++++++ Search for songs, display results (output on stdout). format: specifies the output format (for now: m3u or null or default) list ++++ List available Databases. reset +++++ Erases the Database (every previous scan is lost!) bundle "filename" +++++++++++++++++ Create a bundle (compressed archive) of the database use +++ Not a command by itself, used to specify active database (default: songs) Exemple: :: % zicdb use lisa serve > starts serving lisa's database :: % zicdb use usb_drive reset > destroy usb_drive database :: % zicdb use ipod bundle ipod_database_backup.zdb > backups the "ipod" database into "ipod_database_backup.zdb" file in current directory **WARNING:** using more than one database will most probably lead to song conflicts and won't be usable consider this feature very experimental, use only if you know what you are doing. **NOTE:** you can alternatively use the "ZDB" environment variable instead wasp specific ------------- get "match command" +++++++++++++++++++ Downloads the previous **search** result in ``download_dir`` Examples: ......... :: % wasp get artist: black % zicdb search::out=m3u artist: black show [number of items|slice] ++++++++++++++++++++++++++++ Shows the playlist - show 4 will show the 4 elements from the current one - show 1:15 will show elements from 1 to 15 - show :10 is equivalent to show 0:10 - show 20: will show elements from 20 to end - show -5: syntax is not really supported but still "works" (shows the last 5 elements, but indexes are incorrect) playlist ++++++++ Display the whole playlist play "match command" ++++++++++++++++++++ Set playlist to specified request and start playing if previously stopped match command: same as 'search' command with 2 more fields: pls: output playlist name playlist: input playlist name - "#" is the special name for the current playlist - names can be prefixed with > to append to playlist - or + to insert just after the current song - no prefix means replace Not using any playlist field is equivalent to "pls: #" Note a special sugar is provided when copy/paste'ing a zicbee uri. :: % play http://myfriend.mydomain.com:9090/db/get/song.mp3?id=34g Will be interpreted as ``play id: 34g pls: +#`` on myfriend.mydomain.com host. More examples: .............. :: % wasp play artist: doors > play the doors :: % wasp play artist: bouchers pls: boucherie > store in playlist "boucherie" songs with "bouchers" in artist :: % wasp play artist: pigalle pls: +boucherie > append to playlist "boucherie" songs with "pigalle" in artist :: % wasp play playlist: boucherie > play songs stored in playlist "boucherie" :: % wasp play pls: sogood playlist: # > save the current playlist to playlist "sogood" search "match command" ++++++++++++++++++++++ Search for a patter, display results Results are also stored for commands like "get" random "what" +++++++++++++ Chooses a random thing (artist by default, can be "album" as well) then plays it m3u +++ Prints the current playlist in m3u format grep "arbitrary string" +++++++++++++++++++++++ Only shows playlist elements containing the specified string Result is stored for commands like "move" or "delete" move "what" "where" +++++++++++++++++++ Moves song at position "what" to "where" If "where" is not given, defaults to the song next current one. "what" can be special keyword "grep", will move previously grep'ped songs infos +++++ Display informations about player status shuffle +++++++ Shuffles the current playlist next ++++ Zap current song prev ++++ Move backward in playlist guess +++++ Tells if the given name matches with the current song Problems ======== If you find any problem with installation, don't hesitate to post an Issue or contact me directly fdev31 AT gmail DOT com or fill the `Bugtracker`_. .. _Quickstart: Quickstart .. _packaged release: http://zicbee.gnux.info/files/ .. _setuptools: http://peak.telecommunity.com/dist/ez_setup.py .. _http://localhost:9090/: http://localhost:9090/ .. _Bugtracker: http://zicbee.gnux.info/bugtraq
zicbee
/zicbee-0.9-rc9.tar.gz/zicbee-0.9-rc9/README
README
ZicBee ++++++ To know more, visit `the website <http://zicbee.gnux.info/>`_. Install ======= If you just want to test the program, the simplest way is to get a `Zicbee Pack <http://zicbee.gnux.info/files/zicbee-0.9-rc7.zip>`_, it's a compressed archive ready to run. If you know Python language, you may want to download a fresh copy of `the workshop <http://zicbee.gnux.info/hg/zicbee-workshop/archive/default.zip>`_ ,or `clone it <http://zicbee.gnux.info/Developers>`_. It's a collection of scripts to ease sources handling (fetching, building, distributing) plus examples programs. For a better experience, consider installing `Mercurial <http://mercurial.selenic.com/wiki/>`_. Setuptools way is supported too, using something like easy_install, here is an example:: easy_install zicbee If you want to enable playback, install some player glue (pick one):: easy_install zicbee-mplayer easy_install zicbee-vlc easy_install zicbee-gst Features ======== * Still **fast** even on big playlists and libraries (OK with 30k entries on a netbook) * **Nice syntax** for queries, accessible to any user, *search* and *play* takes the same parameters so you just replace the command name when you are happy with the output * Daemon/Network oriented (not unlike mpd) * Access songs on remote computers * Close the client, songs will continue playing * Open as many clients as you want at any moment * You can mix songs from several computers on the same playlist * Pure **Python** (it should run on any computer, mac, etc...) * **HTTP everywhere** (you can use the web browser on your phone to control the playback or do a query on your library, try "http://host:9090/basic" HTTP address for minimal embedded devices support) * Always growing set of features: * nice playlist handling * real shuffle (not random) * last fm support (auto-generation of playlist based on small request) * song downloading * blind test mode (very minimalistic btw, see *guess* command) * duplicates detection (alpha quality) And much more... try *help* parameter to get an idea ! :) Including projects ================== * `zicbee <http://pypi.python.org/pypi/zicbee>`_ (server (zicserve) / admin utilities (zicdb) / lightweight client (wasp)) * `zicbee-lib <http://pypi.python.org/pypi/zicbee-lib>`_ (base library for zicbee) * `zicbee-mplayer <http://pypi.python.org/pypi/zicbee-mplayer>`_ (mplayer bindings, allow zicbee to play music) * `zicbee-vlc <http://pypi.python.org/pypi/zicbee-vlc>`_ (vlc bindings, allow zicbee to play music) * `zicbee-gst <http://pypi.python.org/pypi/zicbee-gst>`_ (GStreamer bindings, allow zicbee to play music) * `zicbee-quodlibet <http://pypi.python.org/pypi/zicbee-quodlibet>`_ (plugin that turns quodlibet into a zicbee client) Quickstart ========== Start the server (you may want to do this uppon your session startup):: zicserve Scan your songs (you can reproduce this step several times):: zicdb scan <a directory with many songs> Connect to the www interface:: firefox http://localhost:9090/ Read help:: zicdb help Fire up the client:: wasp Example session =============== search artist containing "black" in their name:: wasp search artist: black show all configuration variables:: wasp set changes the host to take songs from:: wasp set db_host 192.168.0.40 tells zicbee to play song on THIS computer:: wasp set player_host localhost search again (on the new db_host):: wasp search artist: black play black sabbath's music :: wasp play artist: black sab skip current song:: wasp next Shows the next entries in the playlist:: wasp show Play "IAM" music, case sensitive and exact match:: wasp play artist: =IAM Play an auto-generated playlist based on some artists:: wasp play auto: artist: =IAM or artist: =Archive Find some song "grepping" some pattern, then move it just after the currently playing song (only works on interactive shell):: wasp> grep lune wasp> move grep I think you *must* read it at least once:: wasp help You can also just run "wasp", and you will get into an interactive shell with completion. Dependencies ============ The software and all the dependencies are available in pure python without native code requirement, it should run on any OS. Wherever many packages answers that requirement, then evaluate speed and simplicity. * Some JSON implementation (python-cjson, simplejson, demjson or builtin if using python >= 2.6) * mutagen (song metadatas handling) * buzhug (database) * web.py (minimalistic www providing library) Additional dependencies may be required if you want playback (libvlc in case of zicbee-vlc and mplayer executable for zicbee-mplayer). `Notice it's not required to play music easily, since you can generate m3u output that will open in your favorite music player.` Changelog ========= 0.9 ... * shiny new client (wasp), comes with many new features (grep, append, inject, get...) * **grep** can be used as parameter for ``move`` and ``delete`` commands. (use after using grep command) * ``move`` and ``delete`` also support slices passing (ex.: ``move 1:3``, ``delete 2:10``) * ``set`` can now unset a variable :P * improve shell completion * abbreviations everywhere * better completion * Support for live streaming, try "play <your favorite mp3 stream>" * Change process title if ``setproctitle`` is available * autoshuffle mode (can be disabled of course) * new "random" command, plays some artist or album randomly * stfu won't have unexpected results, it *kills* the player_host * visual notification for player (can be disabled, unset "notify" variable) * satisfying duplicates detection [WIP] * more flexible commands (handles short commands) * allow easy player backends integration (packages splitting via entry-points) * there is two available backends so far (mplayer and vlc) * see Developers section * minimal www interface (for low power machines, don't expect too much) * use /basic on any server with a player, it's quite rought now * Integrate automatic playlists with ``auto`` special tag * minimalistic last.fm support (no account needed, only works with "artist" keyword) * modulable tolerence giving a digit (ex: ``auto: 15``) * "``artist: wax tailor or artist: birdy nam nam auto:``" automatically generates a playlist of similar artists (no value=10) * Split project for clarity * stored playlists (including position) * related wasp commands: load, save, append, inject * inc. playlist resume * you can alternatively use "pls:" option in play: * use "``#``" to act on current playlist * use "``pls: <playlist name>``" to WRITE a playlist * prefix playlist name with "``>``" to append results to playlist * prefix playlist name with "``+``" to insert results into playlist just after the current song * cleaner javascript/cookies/sessions (prepare theme support) * Tons of bugfixes! (among others, the parser is rewritten, with minor syntax changes) * Automatic hostname guessing for smart URLs * known bugs: volume command is not very functional yet 0.8 ... * add support for FLAC * interactive shell support with completion and history * see "zicdb shell" or "zicbee" commands * integrate/complete tagging & scoring support * add support for multiple DBs at once * (ie. have separate databases for your mp3 player & your local drive) * see "use" command for usage * complete admin commands (see "set" command) 0.7 ... * add play, pause, next, prev, list * add cleaner configuration:: more unified (prepare themes handling) * ensure default host is well given 0.7-rc1 (first public release) .............................. * site launch * fixes egg/root installation (temporary file created)
zicbee
/zicbee-0.9-rc9.tar.gz/zicbee-0.9-rc9/zicbee.rst
zicbee.rst
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):b(a.RSVP=a.RSVP||{})}(this,function(a){"use strict";function b(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function c(a){var b=a._promiseCallbacks;return b||(b=a._promiseCallbacks={}),b}function d(a,b){if(2!==arguments.length)return wa[a];wa[a]=b}function e(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function f(a){return"function"==typeof a}function g(a){return null!==a&&"object"==typeof a}function h(a){return null!==a&&"object"==typeof a}function i(){setTimeout(function(){for(var a=0;a<Aa.length;a++){var b=Aa[a],c=b.payload;c.guid=c.key+c.id,c.childGuid=c.key+c.childId,c.error&&(c.stack=c.error.stack),wa.trigger(b.name,b.payload)}Aa.length=0},50)}function j(a,b,c){1===Aa.push({name:a,payload:{key:b._guidKey,id:b._id,eventName:a,detail:b._result,childId:c&&c._id,label:b._label,timeStamp:za(),error:wa["instrument-with-stack"]?new Error(b._label):null}})&&i()}function k(a,b){var c=this;if(a&&"object"==typeof a&&a.constructor===c)return a;var d=new c(m,b);return s(d,a),d}function l(){return new TypeError("A promises callback cannot return that same promise.")}function m(){}function n(a){try{return a.then}catch(a){return Ea.error=a,Ea}}function o(a,b,c,d){try{a.call(b,c,d)}catch(a){return a}}function p(a,b,c){wa.async(function(a){var d=!1,e=o(c,b,function(c){d||(d=!0,b!==c?s(a,c,void 0):u(a,c))},function(b){d||(d=!0,v(a,b))},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,v(a,e))},a)}function q(a,b){b._state===Ca?u(a,b._result):b._state===Da?(b._onError=null,v(a,b._result)):w(b,void 0,function(c){b!==c?s(a,c,void 0):u(a,c)},function(b){return v(a,b)})}function r(a,b,c){b.constructor===a.constructor&&c===C&&a.constructor.resolve===k?q(a,b):c===Ea?(v(a,Ea.error),Ea.error=null):f(c)?p(a,b,c):u(a,b)}function s(a,b){a===b?u(a,b):e(b)?r(a,b,n(b)):u(a,b)}function t(a){a._onError&&a._onError(a._result),x(a)}function u(a,b){a._state===Ba&&(a._result=b,a._state=Ca,0===a._subscribers.length?wa.instrument&&j("fulfilled",a):wa.async(x,a))}function v(a,b){a._state===Ba&&(a._state=Da,a._result=b,wa.async(t,a))}function w(a,b,c,d){var e=a._subscribers,f=e.length;a._onError=null,e[f]=b,e[f+Ca]=c,e[f+Da]=d,0===f&&a._state&&wa.async(x,a)}function x(a){var b=a._subscribers,c=a._state;if(wa.instrument&&j(c===Ca?"fulfilled":"rejected",a),0!==b.length){for(var d=void 0,e=void 0,f=a._result,g=0;g<b.length;g+=3)d=b[g],e=b[g+c],d?A(c,d,e,f):e(f);a._subscribers.length=0}}function y(){this.error=null}function z(a,b){try{return a(b)}catch(a){return Fa.error=a,Fa}}function A(a,b,c,d){var e=f(c),g=void 0,h=void 0;if(e){if((g=z(c,d))===Fa)h=g.error,g.error=null;else if(g===b)return void v(b,l())}else g=d;b._state!==Ba||(e&&void 0===h?s(b,g):void 0!==h?v(b,h):a===Ca?u(b,g):a===Da&&v(b,g))}function B(a,b){var c=!1;try{b(function(b){c||(c=!0,s(a,b))},function(b){c||(c=!0,v(a,b))})}catch(b){v(a,b)}}function C(a,b,c){var d=this,e=d._state;if(e===Ca&&!a||e===Da&&!b)return wa.instrument&&j("chained",d,d),d;d._onError=null;var f=new d.constructor(m,c),g=d._result;if(wa.instrument&&j("chained",d,f),e===Ba)w(d,f,a,b);else{var h=e===Ca?a:b;wa.async(function(){return A(e,f,h,g)})}return f}function D(a,b,c){return a===Ca?{state:"fulfilled",value:c}:{state:"rejected",reason:c}}function E(a,b){return ya(a)?new Ga(this,a,!0,b).promise:this.reject(new TypeError("Promise.all must be called with an array"),b)}function F(a,b){var c=this,d=new c(m,b);if(!ya(a))return v(d,new TypeError("Promise.race must be called with an array")),d;for(var e=0;d._state===Ba&&e<a.length;e++)w(c.resolve(a[e]),void 0,function(a){return s(d,a)},function(a){return v(d,a)});return d}function G(a,b){var c=this,d=new c(m,b);return v(d,a),d}function H(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function I(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function J(){this.value=void 0}function K(a){try{return a.then}catch(a){return Ka.value=a,Ka}}function L(a,b,c){try{a.apply(b,c)}catch(a){return Ka.value=a,Ka}}function M(a,b){for(var c={},d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=a[f];for(var g=0;g<b.length;g++){c[b[g]]=e[g+1]}return c}function N(a){for(var b=a.length,c=new Array(b-1),d=1;d<b;d++)c[d-1]=a[d];return c}function O(a,b){return{then:function(c,d){return a.call(b,c,d)}}}function P(a,b){var c=function(){for(var c=this,d=arguments.length,e=new Array(d+1),f=!1,g=0;g<d;++g){var h=arguments[g];if(!f){if((f=S(h))===La){var i=new Ja(m);return v(i,La.value),i}f&&!0!==f&&(h=O(f,h))}e[g]=h}var j=new Ja(m);return e[d]=function(a,c){a?v(j,a):void 0===b?s(j,c):!0===b?s(j,N(arguments)):ya(b)?s(j,M(arguments,b)):s(j,c)},f?R(j,e,a,c):Q(j,e,a,c)};return c.__proto__=a,c}function Q(a,b,c,d){var e=L(c,d,b);return e===Ka&&v(a,e.value),a}function R(a,b,c,d){return Ja.all(b).then(function(b){var e=L(c,d,b);return e===Ka&&v(a,e.value),a})}function S(a){return!(!a||"object"!=typeof a)&&(a.constructor===Ja||K(a))}function T(a,b){return Ja.all(a,b)}function U(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function V(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function W(a,b){return ya(a)?new Ma(Ja,a,b).promise:Ja.reject(new TypeError("Promise.allSettled must be called with an array"),b)}function X(a,b){return Ja.race(a,b)}function Y(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function Z(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function $(a,b){return g(a)?new Oa(Ja,a,b).promise:Ja.reject(new TypeError("Promise.hash must be called with an object"),b)}function _(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function aa(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function ba(a,b){return g(a)?new Pa(Ja,a,!1,b).promise:Ja.reject(new TypeError("RSVP.hashSettled must be called with an object"),b)}function ca(a){throw setTimeout(function(){throw a}),a}function da(a){var b={resolve:void 0,reject:void 0};return b.promise=new Ja(function(a,c){b.resolve=a,b.reject=c},a),b}function ea(a,b,c){return ya(a)?f(b)?Ja.all(a,c).then(function(a){for(var d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=b(a[f]);return Ja.all(e,c)}):Ja.reject(new TypeError("RSVP.map expects a function as a second argument"),c):Ja.reject(new TypeError("RSVP.map must be called with an array"),c)}function fa(a,b){return Ja.resolve(a,b)}function ga(a,b){return Ja.reject(a,b)}function ha(a,b){return Ja.all(a,b)}function ia(a,b){return Ja.resolve(a,b).then(function(a){return ha(a,b)})}function ja(a,b,c){return ya(a)||g(a)&&void 0!==a.then?f(b)?(ya(a)?ha(a,c):ia(a,c)).then(function(a){for(var d=a.length,e=new Array(d),f=0;f<d;f++)e[f]=b(a[f]);return ha(e,c).then(function(b){for(var c=new Array(d),e=0,f=0;f<d;f++)b[f]&&(c[e]=a[f],e++);return c.length=e,c})}):Ja.reject(new TypeError("RSVP.filter expects function as a second argument"),c):Ja.reject(new TypeError("RSVP.filter must be called with an array or promise"),c)}function ka(a,b){Xa[Qa]=a,Xa[Qa+1]=b,2===(Qa+=2)&&Ya()}function la(){var a=process.nextTick,b=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);return Array.isArray(b)&&"0"===b[1]&&"10"===b[2]&&(a=setImmediate),function(){return a(qa)}}function ma(){return void 0!==Ra?function(){Ra(qa)}:pa()}function na(){var a=0,b=new Ua(qa),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){return c.data=a=++a%2}}function oa(){var a=new MessageChannel;return a.port1.onmessage=qa,function(){return a.port2.postMessage(0)}}function pa(){return function(){return setTimeout(qa,1)}}function qa(){for(var a=0;a<Qa;a+=2){(0,Xa[a])(Xa[a+1]),Xa[a]=void 0,Xa[a+1]=void 0}Qa=0}function ra(){try{var a=require,b=a("vertx");return Ra=b.runOnLoop||b.runOnContext,ma()}catch(a){return pa()}}function sa(a,b,c){return b in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function ta(){wa.on.apply(wa,arguments)}function ua(){wa.off.apply(wa,arguments)}var va={mixin:function(a){return a.on=this.on,a.off=this.off,a.trigger=this.trigger,a._promiseCallbacks=void 0,a},on:function(a,d){if("function"!=typeof d)throw new TypeError("Callback must be a function");var e=c(this),f=void 0;f=e[a],f||(f=e[a]=[]),-1===b(f,d)&&f.push(d)},off:function(a,d){var e=c(this),f=void 0,g=void 0;if(!d)return void(e[a]=[]);f=e[a],-1!==(g=b(f,d))&&f.splice(g,1)},trigger:function(a,b,d){var e=c(this),f=void 0;if(f=e[a])for(var g=0;g<f.length;g++)(0,f[g])(b,d)}},wa={instrument:!1};va.mixin(wa);var xa=void 0;xa=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)};var ya=xa,za=Date.now||function(){return(new Date).getTime()},Aa=[],Ba=void 0,Ca=1,Da=2,Ea=new y,Fa=new y,Ga=function(){function a(a,b,c,d){this._instanceConstructor=a,this.promise=new a(m,d),this._abortOnReject=c,this._init.apply(this,arguments)}return a.prototype._init=function(a,b){var c=b.length||0;this.length=c,this._remaining=c,this._result=new Array(c),this._enumerate(b),0===this._remaining&&u(this.promise,this._result)},a.prototype._enumerate=function(a){for(var b=this.length,c=this.promise,d=0;c._state===Ba&&d<b;d++)this._eachEntry(a[d],d)},a.prototype._settleMaybeThenable=function(a,b){var c=this._instanceConstructor,d=c.resolve;if(d===k){var e=n(a);if(e===C&&a._state!==Ba)a._onError=null,this._settledAt(a._state,b,a._result);else if("function"!=typeof e)this._remaining--,this._result[b]=this._makeResult(Ca,b,a);else if(c===Ja){var f=new c(m);r(f,a,e),this._willSettleAt(f,b)}else this._willSettleAt(new c(function(b){return b(a)}),b)}else this._willSettleAt(d(a),b)},a.prototype._eachEntry=function(a,b){h(a)?this._settleMaybeThenable(a,b):(this._remaining--,this._result[b]=this._makeResult(Ca,b,a))},a.prototype._settledAt=function(a,b,c){var d=this.promise;d._state===Ba&&(this._abortOnReject&&a===Da?v(d,c):(this._remaining--,this._result[b]=this._makeResult(a,b,c),0===this._remaining&&u(d,this._result)))},a.prototype._makeResult=function(a,b,c){return c},a.prototype._willSettleAt=function(a,b){var c=this;w(a,void 0,function(a){return c._settledAt(Ca,b,a)},function(a){return c._settledAt(Da,b,a)})},a}(),Ha="rsvp_"+za()+"-",Ia=0,Ja=function(){function a(b,c){this._id=Ia++,this._label=c,this._state=void 0,this._result=void 0,this._subscribers=[],wa.instrument&&j("created",this),m!==b&&("function"!=typeof b&&H(),this instanceof a?B(this,b):I())}return a.prototype._onError=function(a){var b=this;wa.after(function(){b._onError&&wa.trigger("error",a,b._label)})},a.prototype.catch=function(a,b){return this.then(void 0,a,b)},a.prototype.finally=function(a,b){var c=this,d=c.constructor;return c.then(function(b){return d.resolve(a()).then(function(){return b})},function(b){return d.resolve(a()).then(function(){throw b})},b)},a}();Ja.cast=k,Ja.all=E,Ja.race=F,Ja.resolve=k,Ja.reject=G,Ja.prototype._guidKey=Ha,Ja.prototype.then=C;var Ka=new J,La=new J,Ma=function(a){function b(b,c,d){return U(this,a.call(this,b,c,!1,d))}return V(b,a),b}(Ga);Ma.prototype._makeResult=D;var Na=Object.prototype.hasOwnProperty,Oa=function(a){function b(b,c){var d=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],e=arguments[3];return Y(this,a.call(this,b,c,d,e))}return Z(b,a),b.prototype._init=function(a,b){this._result={},this._enumerate(b),0===this._remaining&&u(this.promise,this._result)},b.prototype._enumerate=function(a){var b=this.promise,c=[];for(var d in a)Na.call(a,d)&&c.push({position:d,entry:a[d]});var e=c.length;this._remaining=e;for(var f=void 0,g=0;b._state===Ba&&g<e;g++)f=c[g],this._eachEntry(f.entry,f.position)},b}(Ga),Pa=function(a){function b(b,c,d){return _(this,a.call(this,b,c,!1,d))}return aa(b,a),b}(Oa);Pa.prototype._makeResult=D;var Qa=0,Ra=void 0,Sa="undefined"!=typeof window?window:void 0,Ta=Sa||{},Ua=Ta.MutationObserver||Ta.WebKitMutationObserver,Va="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Wa="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,Xa=new Array(1e3),Ya=void 0;Ya=Va?la():Ua?na():Wa?oa():void 0===Sa&&"function"==typeof require?ra():pa();if("object"==typeof self)self;else{if("object"!=typeof global)throw new Error("no global: `self` or `global` found");global}var Za;wa.async=ka,wa.after=function(a){return setTimeout(a,0)};var $a=fa,_a=function(a,b){return wa.async(a,b)};if("undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var ab=window.__PROMISE_INSTRUMENTATION__;d("instrument",!0);for(var bb in ab)ab.hasOwnProperty(bb)&&ta(bb,ab[bb])}var cb=(Za={asap:ka,cast:$a,Promise:Ja,EventTarget:va,all:T,allSettled:W,race:X,hash:$,hashSettled:ba,rethrow:ca,defer:da,denodeify:P,configure:d,on:ta,off:ua,resolve:fa,reject:ga,map:ea},sa(Za,"async",_a),sa(Za,"filter",ja),Za);a.default=cb,a.asap=ka,a.cast=$a,a.Promise=Ja,a.EventTarget=va,a.all=T,a.allSettled=W,a.race=X,a.hash=$,a.hashSettled=ba,a.rethrow=ca,a.defer=da,a.denodeify=P,a.configure=d,a.on=ta,a.off=ua,a.resolve=fa,a.reject=ga,a.map=ea,a.async=_a,a.filter=ja,Object.defineProperty(a,"__esModule",{value:!0})});var EPUBJS=EPUBJS||{};EPUBJS.core={};var ELEMENT_NODE=1,TEXT_NODE=3,COMMENT_NODE=8,DOCUMENT_NODE=9;EPUBJS.core.getEl=function(a){return document.getElementById(a)},EPUBJS.core.getEls=function(a){return document.getElementsByClassName(a)},EPUBJS.core.request=function(a,b,c){var d,e=window.URL,f=e?"blob":"arraybuffer",g=new RSVP.defer,h=new XMLHttpRequest,i=XMLHttpRequest.prototype,j=function(){var a;this.readyState==this.DONE&&(200!==this.status&&0!==this.status||!this.response?g.reject({message:this.response,stack:(new Error).stack}):(a="xml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xml"):"xhtml"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"application/xhtml+xml"):"html"==b?this.responseXML?this.responseXML:(new DOMParser).parseFromString(this.response,"text/html"):"json"==b?JSON.parse(this.response):"blob"==b?e?this.response:new Blob([this.response]):this.response,g.resolve(a)))};return"overrideMimeType"in i||Object.defineProperty(i,"overrideMimeType",{value:function(a){}}),h.onreadystatechange=j,h.open("GET",a,!0),c&&(h.withCredentials=!0),b||(d=EPUBJS.core.uri(a),b=d.extension,b={htm:"html"}[b]||b),"blob"==b&&(h.responseType=f),"json"==b&&h.setRequestHeader("Accept","application/json"),"xml"==b&&(h.responseType="document",h.overrideMimeType("text/xml")),"xhtml"==b&&(h.responseType="document"),"html"==b&&(h.responseType="document"),"binary"==b&&(h.responseType="arraybuffer"),h.send(),g.promise},EPUBJS.core.toArray=function(a){var b=[];for(var c in a){var d;a.hasOwnProperty(c)&&(d=a[c],d.ident=c,b.push(d))}return b},EPUBJS.core.uri=function(a){var b,c,d,e={protocol:"",host:"",path:"",origin:"",directory:"",base:"",filename:"",extension:"",fragment:"",href:a},f=a.indexOf("blob:"),g=a.indexOf("://"),h=a.indexOf("?"),i=a.indexOf("#");return 0===f?(e.protocol="blob",e.base=a.indexOf(0,i),e):(-1!=i&&(e.fragment=a.slice(i+1),a=a.slice(0,i)),-1!=h&&(e.search=a.slice(h+1),a=a.slice(0,h),href=e.href),-1!=g?(e.protocol=a.slice(0,g),b=a.slice(g+3),d=b.indexOf("/"),-1===d?(e.host=e.path,e.path=""):(e.host=b.slice(0,d),e.path=b.slice(d)),e.origin=e.protocol+"://"+e.host,e.directory=EPUBJS.core.folder(e.path),e.base=e.origin+e.directory):(e.path=a,e.directory=EPUBJS.core.folder(a),e.base=e.directory),e.filename=a.replace(e.base,""),c=e.filename.lastIndexOf("."),-1!=c&&(e.extension=e.filename.slice(c+1)),e)},EPUBJS.core.folder=function(a){var b=a.lastIndexOf("/");if(-1==b);return a.slice(0,b+1)},EPUBJS.core.dataURLToBlob=function(a){var b,c,d,e,f,g=";base64,";if(-1==a.indexOf(g))return b=a.split(","),c=b[0].split(":")[1],d=b[1],new Blob([d],{type:c});b=a.split(g),c=b[0].split(":")[1],d=window.atob(b[1]),e=d.length,f=new Uint8Array(e);for(var h=0;h<e;++h)f[h]=d.charCodeAt(h);return new Blob([f],{type:c})},EPUBJS.core.addScript=function(a,b,c){var d,e;e=!1,d=document.createElement("script"),d.type="text/javascript",d.async=!1,d.src=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.addScripts=function(a,b,c){var d=a.length,e=0,f=function(){e++,d==e?b&&b():EPUBJS.core.addScript(a[e],f,c)};EPUBJS.core.addScript(a[e],f,c)},EPUBJS.core.addCss=function(a,b,c){var d,e;e=!1,d=document.createElement("link"),d.type="text/css",d.rel="stylesheet",d.href=a,d.onload=d.onreadystatechange=function(){e||this.readyState&&"complete"!=this.readyState||(e=!0,b&&b())},c=c||document.body,c.appendChild(d)},EPUBJS.core.prefixed=function(a){var b=["Webkit","Moz","O","ms"],c=a[0].toUpperCase()+a.slice(1),d=b.length;if(void 0!==document.documentElement.style[a])return a;for(var e=0;e<d;e++)if(void 0!==document.documentElement.style[b[e]+c])return b[e]+c;return a},EPUBJS.core.resolveUrl=function(a,b){var c,d,e=[],f=EPUBJS.core.uri(b),g=a.split("/");return f.host?b:(g.pop(),d=b.split("/"),d.forEach(function(a){".."===a?g.pop():e.push(a)}),c=g.concat(e),c.join("/"))},EPUBJS.core.uuid=function(){var a=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(b){var c=(a+16*Math.random())%16|0;return a=Math.floor(a/16),("x"==b?c:7&c|8).toString(16)})},EPUBJS.core.insert=function(a,b,c){var d=EPUBJS.core.locationOf(a,b,c);return b.splice(d,0,a),d},EPUBJS.core.locationOf=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:a<b?-1:(a=b)?0:void 0}),h-g<=0?i:(f=c(b[i],a),h-g==1?f>0?i:i+1:0===f?i:-1===f?EPUBJS.core.locationOf(a,b,c,i,h):EPUBJS.core.locationOf(a,b,c,g,i))},EPUBJS.core.indexOfSorted=function(a,b,c,d,e){var f,g=d||0,h=e||b.length,i=parseInt(g+(h-g)/2);return c||(c=function(a,b){return a>b?1:a<b?-1:(a=b)?0:void 0}),h-g<=0?-1:(f=c(b[i],a),h-g==1?0===f?i:-1:0===f?i:-1===f?EPUBJS.core.indexOfSorted(a,b,c,i,h):EPUBJS.core.indexOfSorted(a,b,c,g,i))},EPUBJS.core.queue=function(a){var b=[],c=a,d=function(a,c,d){return b.push({funcName:a,args:c,context:d}),b},e=function(){var a;b.length&&(a=b.shift(),c[a.funcName].apply(a.context||c,a.args))};return{enqueue:d,dequeue:e,flush:function(){for(;b.length;)e()},clear:function(){b=[]},length:function(){return b.length}}},EPUBJS.core.getElementXPath=function(a){return a&&a.id?'//*[@id="'+a.id+'"]':EPUBJS.core.getElementTreeXPath(a)},EPUBJS.core.getElementTreeXPath=function(a){var b,c,d,e,f=[],g="http://www.w3.org/1999/xhtml"===a.ownerDocument.documentElement.getAttribute("xmlns");for(a.nodeType===Node.TEXT_NODE&&(b=EPUBJS.core.indexOfTextNode(a)+1,f.push("text()["+b+"]"),a=a.parentNode);a&&1==a.nodeType;a=a.parentNode){b=0;for(var h=a.previousSibling;h;h=h.previousSibling)h.nodeType!=Node.DOCUMENT_TYPE_NODE&&h.nodeName==a.nodeName&&++b;c=a.nodeName.toLowerCase(),d=g?"xhtml:"+c:c,e=b?"["+(b+1)+"]":"",f.splice(0,0,d+e)}return f.length?"./"+f.join("/"):null},EPUBJS.core.nsResolver=function(a){return{xhtml:"http://www.w3.org/1999/xhtml",epub:"http://www.idpf.org/2007/ops"}[a]||null},EPUBJS.core.cleanStringForXpath=function(a){var b=a.match(/[^'"]+|['"]/g);return b=b.map(function(a){return"'"===a?'"\'"':'"'===a?"'\"'":"'"+a+"'"}),"concat('',"+b.join(",")+")"},EPUBJS.core.indexOfTextNode=function(a){for(var b,c=a.parentNode,d=c.childNodes,e=-1,f=0;f<d.length&&(b=d[f],b.nodeType===Node.TEXT_NODE&&e++,b!=a);f++);return e},EPUBJS.core.defaults=function(a){for(var b=1,c=arguments.length;b<c;b++){var d=arguments[b];for(var e in d)void 0===a[e]&&(a[e]=d[e])}return a},EPUBJS.core.extend=function(a){return[].slice.call(arguments,1).forEach(function(b){b&&Object.getOwnPropertyNames(b).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))})}),a},EPUBJS.core.clone=function(a){return EPUBJS.core.isArray(a)?a.slice():EPUBJS.core.extend({},a)},EPUBJS.core.isElement=function(a){return!(!a||1!=a.nodeType)},EPUBJS.core.isNumber=function(a){return!isNaN(parseFloat(a))&&isFinite(a)},EPUBJS.core.isString=function(a){return"string"==typeof a||a instanceof String},EPUBJS.core.isArray=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},EPUBJS.core.values=function(a){var b,c,d,e=-1;if(!a)return[];for(b=Object.keys(a),c=b.length,d=Array(c);++e<c;)d[e]=a[b[e]];return d},EPUBJS.core.indexOfNode=function(a,b){for(var c,d=a.parentNode,e=d.childNodes,f=-1,g=0;g<e.length&&(c=e[g],c.nodeType===b&&f++,c!=a);g++);return f},EPUBJS.core.indexOfTextNode=function(a){return EPUBJS.core.indexOfNode(a,TEXT_NODE)},EPUBJS.core.indexOfElementNode=function(a){return EPUBJS.core.indexOfNode(a,ELEMENT_NODE)};var EPUBJS=EPUBJS||{};EPUBJS.reader={},EPUBJS.reader.plugins={},function(a,b){var c=(a.ePubReader,a.ePubReader=function(a,b){return new EPUBJS.Reader(a,b)});"function"==typeof define&&define.amd?define(function(){return Reader}):"undefined"!=typeof module&&module.exports&&(module.exports=c)}(window,jQuery),EPUBJS.Reader=function(a,b){var c,d,e,f=this,g=$("#viewer"),h=window.location.search;this.settings=EPUBJS.core.defaults(b||{},{bookPath:a,restore:!1,reload:!1,bookmarks:void 0,annotations:void 0,contained:void 0,bookKey:void 0,styles:void 0,sidebarReflow:!1,generatePagination:!1,history:!0}),h&&(e=h.slice(1).split("&"),e.forEach(function(a){var b=a.split("="),c=b[0],d=b[1]||"";f.settings[c]=decodeURIComponent(d)})),this.setBookKey(this.settings.bookPath),this.settings.restore&&this.isSaved()&&this.applySavedSettings(),this.settings.styles=this.settings.styles||{fontSize:"100%"},this.book=c=new ePub(this.settings.bookPath,this.settings),this.offline=!1,this.sidebarOpen=!1,this.settings.bookmarks||(this.settings.bookmarks=[]),this.settings.annotations||(this.settings.annotations=[]),this.settings.generatePagination&&c.generatePagination(g.width(),g.height()),this.rendition=c.renderTo("viewer",{ignoreClass:"annotator-hl",width:"100%",height:"100%"}),this.settings.previousLocationCfi?this.displayed=this.rendition.display(this.settings.previousLocationCfi):this.displayed=this.rendition.display(),c.ready.then(function(){f.ReaderController=EPUBJS.reader.ReaderController.call(f,c),f.SettingsController=EPUBJS.reader.SettingsController.call(f,c),f.ControlsController=EPUBJS.reader.ControlsController.call(f,c),f.SidebarController=EPUBJS.reader.SidebarController.call(f,c),f.BookmarksController=EPUBJS.reader.BookmarksController.call(f,c),f.NotesController=EPUBJS.reader.NotesController.call(f,c),window.addEventListener("hashchange",this.hashChanged.bind(this),!1),document.addEventListener("keydown",this.adjustFontSize.bind(this),!1),this.rendition.on("keydown",this.adjustFontSize.bind(this)),this.rendition.on("keydown",f.ReaderController.arrowKeys.bind(this)),this.rendition.on("selected",this.selectedRange.bind(this))}.bind(this)).then(function(){f.ReaderController.hideLoader()}.bind(this));for(d in EPUBJS.reader.plugins)EPUBJS.reader.plugins.hasOwnProperty(d)&&(f[d]=EPUBJS.reader.plugins[d].call(f,c));return c.loaded.metadata.then(function(a){f.MetaController=EPUBJS.reader.MetaController.call(f,a)}),c.loaded.navigation.then(function(a){f.TocController=EPUBJS.reader.TocController.call(f,a)}),window.addEventListener("beforeunload",this.unload.bind(this),!1),this},EPUBJS.Reader.prototype.adjustFontSize=function(a){var b,c=2,d=a.ctrlKey||a.metaKey;this.settings.styles&&(this.settings.styles.fontSize||(this.settings.styles.fontSize="100%"),b=parseInt(this.settings.styles.fontSize.slice(0,-1)),d&&187==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize",b+c+"%")),d&&189==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize",b-c+"%")),d&&48==a.keyCode&&(a.preventDefault(),this.book.setStyle("fontSize","100%")))},EPUBJS.Reader.prototype.addBookmark=function(a){this.isBookmarked(a)>-1||(this.settings.bookmarks.push(a),this.trigger("reader:bookmarked",a))},EPUBJS.Reader.prototype.removeBookmark=function(a){var b=this.isBookmarked(a);-1!==b&&(this.settings.bookmarks.splice(b,1),this.trigger("reader:unbookmarked",b))},EPUBJS.Reader.prototype.isBookmarked=function(a){return this.settings.bookmarks.indexOf(a)},EPUBJS.Reader.prototype.clearBookmarks=function(){this.settings.bookmarks=[]},EPUBJS.Reader.prototype.addNote=function(a){this.settings.annotations.push(a)},EPUBJS.Reader.prototype.removeNote=function(a){var b=this.settings.annotations.indexOf(a);-1!==b&&delete this.settings.annotations[b]},EPUBJS.Reader.prototype.clearNotes=function(){this.settings.annotations=[]},EPUBJS.Reader.prototype.setBookKey=function(a){return this.settings.bookKey||(this.settings.bookKey="epubjsreader:"+EPUBJS.VERSION+":"+window.location.host+":"+a),this.settings.bookKey},EPUBJS.Reader.prototype.isSaved=function(a){return!!localStorage&&null!==localStorage.getItem(this.settings.bookKey)},EPUBJS.Reader.prototype.removeSavedSettings=function(){if(!localStorage)return!1;localStorage.removeItem(this.settings.bookKey)},EPUBJS.Reader.prototype.applySavedSettings=function(){var a;if(!localStorage)return!1;try{a=JSON.parse(localStorage.getItem(this.settings.bookKey))}catch(a){return!1}return!!a&&(a.styles&&(this.settings.styles=EPUBJS.core.defaults(this.settings.styles||{},a.styles)),this.settings=EPUBJS.core.defaults(this.settings,a),!0)},EPUBJS.Reader.prototype.saveSettings=function(){if(this.book&&(this.settings.previousLocationCfi=this.rendition.currentLocation().start.cfi),!localStorage)return!1;localStorage.setItem(this.settings.bookKey,JSON.stringify(this.settings))},EPUBJS.Reader.prototype.unload=function(){this.settings.restore&&localStorage&&this.saveSettings()},EPUBJS.Reader.prototype.hashChanged=function(){var a=window.location.hash.slice(1);this.rendition.display(a)},EPUBJS.Reader.prototype.selectedRange=function(a){var b="#"+a;this.settings.history&&window.location.hash!=b&&(history.pushState({},"",b),this.currentLocationCfi=a)},RSVP.EventTarget.mixin(EPUBJS.Reader.prototype),EPUBJS.reader.BookmarksController=function(){var a=this.book,b=this.rendition,c=$("#bookmarksView"),d=c.find("#bookmarks"),e=document.createDocumentFragment(),f=function(){c.show()},g=function(){c.hide()},h=0,i=function(c){var d=document.createElement("li"),e=document.createElement("a");d.id="bookmark-"+h,d.classList.add("list_item");var f,g=a.spine.get(c);return g.index in a.navigation.toc?(f=a.navigation.toc[g.index],e.textContent=f.label):e.textContent=c,e.href=c,e.classList.add("bookmark_link"),e.addEventListener("click",function(a){var c=this.getAttribute("href");b.display(c),a.preventDefault()},!1),d.appendChild(e),h++,d};return this.settings.bookmarks.forEach(function(a){var b=i(a);e.appendChild(b)}),d.append(e),this.on("reader:bookmarked",function(a){var b=i(a);d.append(b)}),this.on("reader:unbookmarked",function(a){$("#bookmark-"+a).remove()}),{show:f,hide:g}},EPUBJS.reader.ControlsController=function(a){var b=this,c=this.rendition,d=($("#store"),$("#fullscreen")),e=($("#fullscreenicon"),$("#cancelfullscreenicon"),$("#slider")),f=($("#main"),$("#sidebar"),$("#setting")),g=$("#bookmark");return e.on("click",function(){b.sidebarOpen?(b.SidebarController.hide(),e.addClass("icon-menu"),e.removeClass("icon-right")):(b.SidebarController.show(),e.addClass("icon-right"),e.removeClass("icon-menu"))}),"undefined"!=typeof screenfull&&(d.on("click",function(){screenfull.toggle($("#container")[0])}),screenfull.raw&&document.addEventListener(screenfull.raw.fullscreenchange,function(){fullscreen=screenfull.isFullscreen,fullscreen?d.addClass("icon-resize-small").removeClass("icon-resize-full"):d.addClass("icon-resize-full").removeClass("icon-resize-small")})),f.on("click",function(){b.SettingsController.show()}),g.on("click",function(){var a=b.rendition.currentLocation().start.cfi;-1===b.isBookmarked(a)?(b.addBookmark(a),g.addClass("icon-bookmark").removeClass("icon-bookmark-empty")):(b.removeBookmark(a),g.removeClass("icon-bookmark").addClass("icon-bookmark-empty"))}),c.on("relocated",function(a){var c=a.start.cfi,d="#"+c;-1===b.isBookmarked(c)?g.removeClass("icon-bookmark").addClass("icon-bookmark-empty"):g.addClass("icon-bookmark").removeClass("icon-bookmark-empty"),b.currentLocationCfi=c,b.settings.history&&window.location.hash!=d&&history.pushState({},"",d)}),{}},EPUBJS.reader.MetaController=function(a){var b=a.title,c=a.creator,d=$("#book-title"),e=$("#chapter-title"),f=$("#title-seperator");document.title=b+" – "+c,d.html(b),e.html(c),f.show()},EPUBJS.reader.NotesController=function(){var a=this.book,b=this.rendition,c=this,d=$("#notesView"),e=$("#notes"),f=$("#note-text"),g=$("#note-anchor"),h=c.settings.annotations,i=a.renderer,j=[],k=new ePub.CFI,l=function(){d.show()},m=function(){d.hide()},n=function(d){var e,h,i,j,l,m=a.renderer.doc;if(m.caretPositionFromPoint?(e=m.caretPositionFromPoint(d.clientX,d.clientY),h=e.offsetNode,i=e.offset):m.caretRangeFromPoint&&(e=m.caretRangeFromPoint(d.clientX,d.clientY),h=e.startContainer,i=e.startOffset),3!==h.nodeType)for(var q=0;q<h.childNodes.length;q++)if(3==h.childNodes[q].nodeType){h=h.childNodes[q];break}i=h.textContent.indexOf(".",i),-1===i?i=h.length:i+=1,j=k.generateCfiFromTextNode(h,i,a.renderer.currentChapter.cfiBase),l={annotatedAt:new Date,anchor:j,body:f.val()},c.addNote(l),o(l),p(l),f.val(""),g.text("Attach"),f.prop("disabled",!1),b.off("click",n)},o=function(a){var c=document.createElement("li"),d=document.createElement("a");c.innerHTML=a.body,d.innerHTML=" context &#187;",d.href="#"+a.anchor,d.onclick=function(){return b.display(a.anchor),!1},c.appendChild(d),e.append(c)},p=function(b){var c=a.renderer.doc,d=document.createElement("span"),e=document.createElement("a");d.classList.add("footnotesuperscript","reader_generated"),d.style.verticalAlign="super",d.style.fontSize=".75em",d.style.lineHeight="1em",e.style.padding="2px",e.style.backgroundColor="#fffa96",e.style.borderRadius="5px",e.style.cursor="pointer",d.id="note-"+EPUBJS.core.uuid(),e.innerHTML=h.indexOf(b)+1+"[Reader]",d.appendChild(e),k.addMarker(b.anchor,c,d),q(d,b.body)},q=function(a,d){var e=a.id,f=function(){var c,f,l,m,n=i.height,o=i.width,p=225;j[e]||(j[e]=document.createElement("div"),j[e].setAttribute("class","popup"),pop_content=document.createElement("div"),j[e].appendChild(pop_content),pop_content.innerHTML=d,pop_content.setAttribute("class","pop_content"),i.render.document.body.appendChild(j[e]),j[e].addEventListener("mouseover",g,!1),j[e].addEventListener("mouseout",h,!1),b.on("locationChanged",k,this),b.on("locationChanged",h,this)),c=j[e],f=a.getBoundingClientRect(),l=f.left,m=f.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=l-popRect.width/2+"px",c.style.top=m+"px",p>n/2.5&&(p=n/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+m>=n-25?(c.style.top=m-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),l-popRect.width<=0?(c.style.left=l+"px",c.classList.add("left")):c.classList.remove("left"),l+popRect.width/2>=o?(c.style.left=l-300+"px",popRect=c.getBoundingClientRect(),c.style.left=l-popRect.width+"px",popRect.height+m>=n-25?(c.style.top=m-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")},g=function(){j[e].classList.add("on")},h=function(){j[e].classList.remove("on")},k=function(){setTimeout(function(){j[e].classList.remove("show")},100)},m=function(){c.ReaderController.slideOut(),l()};a.addEventListener("mouseover",f,!1),a.addEventListener("mouseout",k,!1),a.addEventListener("click",m,!1)};return g.on("click",function(a){g.text("Cancel"),f.prop("disabled","true"),b.on("click",n)}),h.forEach(function(a){o(a)}),{show:l,hide:m}},EPUBJS.reader.ReaderController=function(a){var b=$("#main"),c=$("#divider"),d=$("#loader"),e=$("#next"),f=$("#prev"),g=this,a=this.book,h=this.rendition,i=function(){h.currentLocation().start.cfi;g.settings.sidebarReflow?(b.removeClass("single"),b.one("transitionend",function(){h.resize()})):b.removeClass("closed")},j=function(){var a=h.currentLocation();if(a){a.start.cfi;g.settings.sidebarReflow?(b.addClass("single"),b.one("transitionend",function(){h.resize()})):b.addClass("closed")}},k=function(){d.show(),n()},l=function(){d.hide()},m=function(){c.addClass("show")},n=function(){c.removeClass("show")},o=!1,p=function(b){37==b.keyCode&&("rtl"===a.package.metadata.direction?h.next():h.prev(),f.addClass("active"),o=!0,setTimeout(function(){o=!1,f.removeClass("active")},100),b.preventDefault()),39==b.keyCode&&("rtl"===a.package.metadata.direction?h.prev():h.next(),e.addClass("active"),o=!0,setTimeout(function(){o=!1,e.removeClass("active")},100),b.preventDefault())};return document.addEventListener("keydown",p,!1),e.on("click",function(b){"rtl"===a.package.metadata.direction?h.prev():h.next(),b.preventDefault()}),f.on("click",function(b){"rtl"===a.package.metadata.direction?h.next():h.prev(),b.preventDefault()}),h.on("layout",function(a){!0===a.spread?m():n()}),h.on("relocated",function(a){a.atStart&&f.addClass("disabled"),a.atEnd&&e.addClass("disabled")}),{slideOut:j,slideIn:i,showLoader:k,hideLoader:l,showDivider:m,hideDivider:n,arrowKeys:p}},EPUBJS.reader.SettingsController=function(){var a=(this.book,this),b=$("#settings-modal"),c=$(".overlay"),d=function(){b.addClass("md-show")},e=function(){b.removeClass("md-show")};return $("#sidebarReflow").on("click",function(){a.settings.sidebarReflow=!a.settings.sidebarReflow}),b.find(".closer").on("click",function(){e()}),c.on("click",function(){e()}),{show:d,hide:e}},EPUBJS.reader.SidebarController=function(a){var b=this,c=$("#sidebar"),d=$("#panels"),e="Toc",f=function(a){var c=a+"Controller";e!=a&&void 0!==b[c]&&(b[e+"Controller"].hide(),b[c].show(),e=a,d.find(".active").removeClass("active"),d.find("#show-"+a).addClass("active"))},g=function(){return e},h=function(){b.sidebarOpen=!0,b.ReaderController.slideOut(),c.addClass("open")},i=function(){b.sidebarOpen=!1,b.ReaderController.slideIn(),c.removeClass("open")};return d.find(".show_view").on("click",function(a){var b=$(this).data("view");f(b),a.preventDefault()}),{show:h,hide:i,getActivePanel:g,changePanelTo:f}},EPUBJS.reader.TocController=function(a){var b=(this.book,this.rendition),c=$("#tocView"),d=document.createDocumentFragment(),e=!1,f=function(a,b){var c=document.createElement("ul");return b||(b=1),a.forEach(function(a){var d=document.createElement("li"),e=document.createElement("a");toggle=document.createElement("a");var g;d.id="toc-"+a.id,d.classList.add("list_item"),e.textContent=a.label,e.href=a.href,e.classList.add("toc_link"),d.appendChild(e),a.subitems&&a.subitems.length>0&&(b++,g=f(a.subitems,b),toggle.classList.add("toc_toggle"),d.insertBefore(toggle,e),d.appendChild(g)),c.appendChild(d)}),c},g=function(){c.show()},h=function(){c.hide()},i=function(a){var b=a.id,d=c.find("#toc-"+b),f=c.find(".currentChapter");c.find(".openChapter");d.length&&(d!=f&&d.has(e).length>0&&f.removeClass("currentChapter"),d.addClass("currentChapter"),d.parents("li").addClass("openChapter"))};b.on("renderered",i);var j=f(a);return d.appendChild(j),c.append(d),c.find(".toc_link").on("click",function(a){var d=this.getAttribute("href");a.preventDefault(),b.display(d),c.find(".currentChapter").addClass("openChapter").removeClass("currentChapter"),$(this).parent("li").addClass("currentChapter")}),c.find(".toc_toggle").on("click",function(a){var b=$(this).parent("li"),c=b.hasClass("openChapter");a.preventDefault(),c?b.removeClass("openChapter"):b.addClass("openChapter")}),{show:g,hide:h}};
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/reader.min.js
reader.min.js
EPUBJS.Hooks.register("beforeChapterDisplay").endnotes=function(a,b){var c=b.contents.querySelectorAll("a[href]"),d=Array.prototype.slice.call(c),e=EPUBJS.core.folder(location.pathname),f=(EPUBJS.cssPath,{});EPUBJS.core.addCss(EPUBJS.cssPath+"popup.css",!1,b.render.document.head),d.forEach(function(a){function c(){var c,h,n=b.height,o=b.width,p=225;m||(c=j.cloneNode(!0),m=c.querySelector("p")),f[i]||(f[i]=document.createElement("div"),f[i].setAttribute("class","popup"),pop_content=document.createElement("div"),f[i].appendChild(pop_content),pop_content.appendChild(m),pop_content.setAttribute("class","pop_content"),b.render.document.body.appendChild(f[i]),f[i].addEventListener("mouseover",d,!1),f[i].addEventListener("mouseout",e,!1),b.on("renderer:pageChanged",g,this),b.on("renderer:pageChanged",e,this)),c=f[i],h=a.getBoundingClientRect(),k=h.left,l=h.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=k-popRect.width/2+"px",c.style.top=l+"px",p>n/2.5&&(p=n/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+l>=n-25?(c.style.top=l-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),k-popRect.width<=0?(c.style.left=k+"px",c.classList.add("left")):c.classList.remove("left"),k+popRect.width/2>=o?(c.style.left=k-300+"px",popRect=c.getBoundingClientRect(),c.style.left=k-popRect.width+"px",popRect.height+l>=n-25?(c.style.top=l-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")}function d(){f[i].classList.add("on")}function e(){f[i].classList.remove("on")}function g(){setTimeout(function(){f[i].classList.remove("show")},100)}var h,i,j,k,l,m;"noteref"==a.getAttribute("epub:type")&&(h=a.getAttribute("href"),i=h.replace("#",""),j=b.render.document.getElementById(i),a.addEventListener("mouseover",c,!1),a.addEventListener("mouseout",g,!1))}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").mathml=function(a,b){if(b.currentChapter.manifestProperties.indexOf("mathml")!==-1){b.render.iframe.contentWindow.mathmlCallback=a;var c=document.createElement("script");c.type="text/x-mathjax-config",c.innerHTML=' MathJax.Hub.Register.StartupHook("End",function () { window.mathmlCallback(); }); MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); ',b.doc.body.appendChild(c),EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",null,b.doc.head)}else a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").smartimages=function(a,b){var c=b.contents.querySelectorAll("img"),d=Array.prototype.slice.call(c),e=b.height;if("reflowable"!=b.layoutSettings.layout)return void a();d.forEach(function(a){var c=function(){var c,d=a.getBoundingClientRect(),f=d.height,g=d.top,h=a.getAttribute("data-height"),i=h||f,j=Number(getComputedStyle(a,"").fontSize.match(/(\d*(\.\d*)?)px/)[1]),k=j?j/2:0;e=b.contents.clientHeight,g<0&&(g=0),a.style.maxWidth="100%",i+g>=e?(g<e/2?(c=e-g-k,a.style.maxHeight=c+"px",a.style.width="auto"):(i>e&&(a.style.maxHeight=e+"px",a.style.width="auto",d=a.getBoundingClientRect(),i=d.height),a.style.display="block",a.style.WebkitColumnBreakBefore="always",a.style.breakBefore="column"),a.setAttribute("data-height",c)):(a.style.removeProperty("max-height"),a.style.removeProperty("margin-top"))},d=function(){b.off("renderer:resized",c),b.off("renderer:chapterUnload",this)};a.addEventListener("load",c,!1),b.on("renderer:resized",c),b.on("renderer:chapterUnload",d),c()}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").transculsions=function(a,b){var c=b.contents.querySelectorAll("[transclusion]");Array.prototype.slice.call(c).forEach(function(a){function c(){j=g,k=h,j>chapter.colWidth&&(d=chapter.colWidth/j,j=chapter.colWidth,k*=d),f.width=j,f.height=k}var d,e=a.getAttribute("ref"),f=document.createElement("iframe"),g=a.getAttribute("width"),h=a.getAttribute("height"),i=a.parentNode,j=g,k=h;c(),b.listenUntil("renderer:resized","renderer:chapterUnloaded",c),f.src=e,i.replaceChild(f,a)}),a&&a()};
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/hooks.min.js
hooks.min.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.RSVP = global.RSVP || {}))); }(this, (function (exports) { 'use strict'; function indexOf(callbacks, callback) { for (var i = 0, l = callbacks.length; i < l; i++) { if (callbacks[i] === callback) { return i; } } return -1; } function callbacksFor(object) { var callbacks = object._promiseCallbacks; if (!callbacks) { callbacks = object._promiseCallbacks = {}; } return callbacks; } /** @class RSVP.EventTarget */ var EventTarget = { /** `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For Example: ```javascript let object = {}; RSVP.EventTarget.mixin(object); object.on('finished', function(event) { // handle event }); object.trigger('finished', { detail: value }); ``` `EventTarget.mixin` also works with prototypes: ```javascript let Person = function() {}; RSVP.EventTarget.mixin(Person.prototype); let yehuda = new Person(); let tom = new Person(); yehuda.on('poke', function(event) { console.log('Yehuda says OW'); }); tom.on('poke', function(event) { console.log('Tom says OW'); }); yehuda.trigger('poke'); tom.trigger('poke'); ``` @method mixin @for RSVP.EventTarget @private @param {Object} object object to extend with EventTarget methods */ mixin: function (object) { object['on'] = this['on']; object['off'] = this['off']; object['trigger'] = this['trigger']; object._promiseCallbacks = undefined; return object; }, /** Registers a callback to be executed when `eventName` is triggered ```javascript object.on('event', function(eventInfo){ // handle the event }); object.trigger('event'); ``` @method on @for RSVP.EventTarget @private @param {String} eventName name of the event to listen for @param {Function} callback function to be called when the event is triggered. */ on: function (eventName, callback) { if (typeof callback !== 'function') { throw new TypeError('Callback must be a function'); } var allCallbacks = callbacksFor(this), callbacks = void 0; callbacks = allCallbacks[eventName]; if (!callbacks) { callbacks = allCallbacks[eventName] = []; } if (indexOf(callbacks, callback) === -1) { callbacks.push(callback); } }, /** You can use `off` to stop firing a particular callback for an event: ```javascript function doStuff() { // do stuff! } object.on('stuff', doStuff); object.trigger('stuff'); // doStuff will be called // Unregister ONLY the doStuff callback object.off('stuff', doStuff); object.trigger('stuff'); // doStuff will NOT be called ``` If you don't pass a `callback` argument to `off`, ALL callbacks for the event will not be executed when the event fires. For example: ```javascript let callback1 = function(){}; let callback2 = function(){}; object.on('stuff', callback1); object.on('stuff', callback2); object.trigger('stuff'); // callback1 and callback2 will be executed. object.off('stuff'); object.trigger('stuff'); // callback1 and callback2 will not be executed! ``` @method off @for RSVP.EventTarget @private @param {String} eventName event to stop listening to @param {Function} callback optional argument. If given, only the function given will be removed from the event's callback queue. If no `callback` argument is given, all callbacks will be removed from the event's callback queue. */ off: function (eventName, callback) { var allCallbacks = callbacksFor(this), callbacks = void 0, index = void 0; if (!callback) { allCallbacks[eventName] = []; return; } callbacks = allCallbacks[eventName]; index = indexOf(callbacks, callback); if (index !== -1) { callbacks.splice(index, 1); } }, /** Use `trigger` to fire custom events. For example: ```javascript object.on('foo', function(){ console.log('foo event happened!'); }); object.trigger('foo'); // 'foo event happened!' logged to the console ``` You can also pass a value as a second argument to `trigger` that will be passed as an argument to all event listeners for the event: ```javascript object.on('foo', function(value){ console.log(value.name); }); object.trigger('foo', { name: 'bar' }); // 'bar' logged to the console ``` @method trigger @for RSVP.EventTarget @private @param {String} eventName name of the event to be triggered @param {*} options optional value to be passed to any event handlers for the given `eventName` */ trigger: function (eventName, options, label) { var allCallbacks = callbacksFor(this), callbacks = void 0, callback = void 0; if (callbacks = allCallbacks[eventName]) { // Don't cache the callbacks.length since it may grow for (var i = 0; i < callbacks.length; i++) { callback = callbacks[i]; callback(options, label); } } } }; var config = { instrument: false }; EventTarget['mixin'](config); function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } function isObject(x) { return x !== null && typeof x === 'object'; } function isMaybeThenable(x) { return x !== null && typeof x === 'object'; } var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function () { return new Date().getTime(); }; var queue = []; function scheduleFlush() { setTimeout(function () { for (var i = 0; i < queue.length; i++) { var entry = queue[i]; var payload = entry.payload; payload.guid = payload.key + payload.id; payload.childGuid = payload.key + payload.childId; if (payload.error) { payload.stack = payload.error.stack; } config['trigger'](entry.name, entry.payload); } queue.length = 0; }, 50); } function instrument(eventName, promise, child) { if (1 === queue.push({ name: eventName, payload: { key: promise._guidKey, id: promise._id, eventName: eventName, detail: promise._result, childId: child && child._id, label: promise._label, timeStamp: now(), error: config["instrument-with-stack"] ? new Error(promise._label) : null } })) { scheduleFlush(); } } /** `RSVP.Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new RSVP.Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = RSVP.Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {*} object value that the returned promise will be resolved with @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$1(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop, label); resolve(promise, object); return promise; } function withOwnPromise() { return new TypeError('A promises callback cannot return that same promise.'); } function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { config.async(function (promise) { var sealed = false; var error = tryThen(then$$1, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { resolve(promise, value, undefined); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { thenable._onError = null; reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { if (thenable !== value) { resolve(promise, value, undefined); } else { fulfill(promise, value); } }, function (reason) { return reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$1) { var isOwnThenable = maybeThenable.constructor === promise.constructor && then$$1 === then && promise.constructor.resolve === resolve$1; if (isOwnThenable) { handleOwnThenable(promise, maybeThenable); } else if (then$$1 === GET_THEN_ERROR) { reject(promise, GET_THEN_ERROR.error); GET_THEN_ERROR.error = null; } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } else { fulfill(promise, maybeThenable); } } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onError) { promise._onError(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length === 0) { if (config.instrument) { instrument('fulfilled', promise); } } else { config.async(publish, promise); } } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; config.async(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onError = null; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { config.async(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (config.instrument) { instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); } if (subscribers.length === 0) { return; } var child = void 0, callback = void 0, result = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, result); } else { callback(result); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, result) { try { return callback(result); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(state, promise, callback, result) { var hasCallback = isFunction(callback); var value = void 0, error = void 0; if (hasCallback) { value = tryCatch(callback, result); if (value === TRY_CATCH_ERROR) { error = value.error; value.error = null; // release } else if (value === promise) { reject(promise, withOwnPromise()); return; } } else { value = result; } if (promise._state !== PENDING) { // noop } else if (hasCallback && error === undefined) { resolve(promise, value); } else if (error !== undefined) { reject(promise, error); } else if (state === FULFILLED) { fulfill(promise, value); } else if (state === REJECTED) { reject(promise, value); } } function initializePromise(promise, resolver) { var resolved = false; try { resolver(function (value) { if (resolved) { return; } resolved = true; resolve(promise, value); }, function (reason) { if (resolved) { return; } resolved = true; reject(promise, reason); }); } catch (e) { reject(promise, e); } } function then(onFulfillment, onRejection, label) { var parent = this; var state = parent._state; if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { config.instrument && instrument('chained', parent, parent); return parent; } parent._onError = null; var child = new parent.constructor(noop, label); var result = parent._result; config.instrument && instrument('chained', parent, child); if (state === PENDING) { subscribe(parent, child, onFulfillment, onRejection); } else { var callback = state === FULFILLED ? onFulfillment : onRejection; config.async(function () { return invokeCallback(state, child, callback, result); }); } return child; } var Enumerator = function () { function Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop, label); this._abortOnReject = abortOnReject; this._init.apply(this, arguments); } Enumerator.prototype._init = function _init(Constructor, input) { var len = input.length || 0; this.length = len; this._remaining = len; this._result = new Array(len); this._enumerate(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } }; Enumerator.prototype._enumerate = function _enumerate(input) { var length = this.length; var promise = this.promise; for (var i = 0; promise._state === PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._settleMaybeThenable = function _settleMaybeThenable(entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { var then$$1 = getThen(entry); if (then$$1 === then && entry._state !== PENDING) { entry._onError = null; this._settledAt(entry._state, i, entry._result); } else if (typeof then$$1 !== 'function') { this._remaining--; this._result[i] = this._makeResult(FULFILLED, i, entry); } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, then$$1); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { if (isMaybeThenable(entry)) { this._settleMaybeThenable(entry, i); } else { this._remaining--; this._result[i] = this._makeResult(FULFILLED, i, entry); } }; Enumerator.prototype._settledAt = function _settledAt(state, i, value) { var promise = this.promise; if (promise._state === PENDING) { if (this._abortOnReject && state === REJECTED) { reject(promise, value); } else { this._remaining--; this._result[i] = this._makeResult(state, i, value); if (this._remaining === 0) { fulfill(promise, this._result); } } } }; Enumerator.prototype._makeResult = function _makeResult(state, i, value) { return value; }; Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); function makeSettledResult(state, position, value) { if (state === FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } /** `RSVP.Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = RSVP.resolve(1); let promise2 = RSVP.resolve(2); let promise3 = RSVP.resolve(3); let promises = [ promise1, promise2, promise3 ]; RSVP.Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = RSVP.resolve(1); let promise2 = RSVP.reject(new Error("2")); let promise3 = RSVP.reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; RSVP.Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries, label) { if (!isArray(entries)) { return this.reject(new TypeError("Promise.all must be called with an array"), label); } return new Enumerator(this, entries, true /* abort on reject */, label).promise; } /** `RSVP.Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); RSVP.Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `RSVP.Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); RSVP.Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript RSVP.Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} entries array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop, label); if (!isArray(entries)) { reject(promise, new TypeError('Promise.race must be called with an array')); return promise; } for (var i = 0; promise._state === PENDING && i < entries.length; i++) { subscribe(Constructor.resolve(entries[i]), undefined, function (value) { return resolve(promise, value); }, function (reason) { return reject(promise, reason); }); } return promise; } /** `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = RSVP.Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {*} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$1(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop, label); reject(promise, reason); return promise; } var guidKey = 'rsvp_' + now() + '-'; var counter = 0; function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class RSVP.Promise @param {function} resolver @param {String} label optional string for labeling the promise. Useful for tooling. @constructor */ var Promise = function () { function Promise(resolver, label) { this._id = counter++; this._label = label; this._state = undefined; this._result = undefined; this._subscribers = []; config.instrument && instrument('created', this); if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.prototype._onError = function _onError(reason) { var _this = this; config.after(function () { if (_this._onError) { config.trigger('error', reason, _this._label); } }); }; /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn\'t find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ Promise.prototype.catch = function _catch(onRejection, label) { return this.then(undefined, onRejection, label); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuthor(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuthor(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ Promise.prototype.finally = function _finally(callback, label) { var promise = this; var constructor = promise.constructor; return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }, label); }; return Promise; }(); Promise.cast = resolve$1; // deprecated Promise.all = all; Promise.race = race; Promise.resolve = resolve$1; Promise.reject = reject$1; Promise.prototype._guidKey = guidKey; /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we\'re unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we\'re unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfillment @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ Promise.prototype.then = then; function Result() { this.value = undefined; } var ERROR = new Result(); var GET_THEN_ERROR$1 = new Result(); function getThen$1(obj) { try { return obj.then; } catch (error) { ERROR.value = error; return ERROR; } } function tryApply(f, s, a) { try { f.apply(s, a); } catch (error) { ERROR.value = error; return ERROR; } } function makeObject(_, argumentNames) { var obj = {}; var length = _.length; var args = new Array(length); for (var x = 0; x < length; x++) { args[x] = _[x]; } for (var i = 0; i < argumentNames.length; i++) { var name = argumentNames[i]; obj[name] = args[i + 1]; } return obj; } function arrayResult(_) { var length = _.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = _[i]; } return args; } function wrapThenable(then, promise) { return { then: function (onFulFillment, onRejection) { return then.call(promise, onFulFillment, onRejection); } }; } /** `RSVP.denodeify` takes a 'node-style' function and returns a function that will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the browser when you'd prefer to use promises over using callbacks. For example, `denodeify` transforms the following: ```javascript let fs = require('fs'); fs.readFile('myfile.txt', function(err, data){ if (err) return handleError(err); handleData(data); }); ``` into: ```javascript let fs = require('fs'); let readFile = RSVP.denodeify(fs.readFile); readFile('myfile.txt').then(handleData, handleError); ``` If the node function has multiple success parameters, then `denodeify` just returns the first one: ```javascript let request = RSVP.denodeify(require('request')); request('http://example.com').then(function(res) { // ... }); ``` However, if you need all success parameters, setting `denodeify`'s second parameter to `true` causes it to return all success parameters as an array: ```javascript let request = RSVP.denodeify(require('request'), true); request('http://example.com').then(function(result) { // result[0] -> res // result[1] -> body }); ``` Or if you pass it an array with names it returns the parameters as a hash: ```javascript let request = RSVP.denodeify(require('request'), ['res', 'body']); request('http://example.com').then(function(result) { // result.res // result.body }); ``` Sometimes you need to retain the `this`: ```javascript let app = require('express')(); let render = RSVP.denodeify(app.render.bind(app)); ``` The denodified function inherits from the original function. It works in all environments, except IE 10 and below. Consequently all properties of the original function are available to you. However, any properties you change on the denodeified function won't be changed on the original function. Example: ```javascript let request = RSVP.denodeify(require('request')), cookieJar = request.jar(); // <- Inheritance is used here request('http://example.com', {jar: cookieJar}).then(function(res) { // cookieJar.cookies holds now the cookies returned by example.com }); ``` Using `denodeify` makes it easier to compose asynchronous operations instead of using callbacks. For example, instead of: ```javascript let fs = require('fs'); fs.readFile('myfile.txt', function(err, data){ if (err) { ... } // Handle error fs.writeFile('myfile2.txt', data, function(err){ if (err) { ... } // Handle error console.log('done') }); }); ``` you can chain the operations together using `then` from the returned promise: ```javascript let fs = require('fs'); let readFile = RSVP.denodeify(fs.readFile); let writeFile = RSVP.denodeify(fs.writeFile); readFile('myfile.txt').then(function(data){ return writeFile('myfile2.txt', data); }).then(function(){ console.log('done') }).catch(function(error){ // Handle error }); ``` @method denodeify @static @for RSVP @param {Function} nodeFunc a 'node-style' function that takes a callback as its last argument. The callback expects an error to be passed as its first argument (if an error occurred, otherwise null), and the value from the operation as its second argument ('function(err, value){ }'). @param {Boolean|Array} [options] An optional paramter that if set to `true` causes the promise to fulfill with the callback's success arguments as an array. This is useful if the node function has multiple success paramters. If you set this paramter to an array with names, the promise will fulfill with a hash with these names as keys and the success parameters as values. @return {Function} a function that wraps `nodeFunc` to return an `RSVP.Promise` @static */ function denodeify(nodeFunc, options) { var fn = function () { var self = this; var l = arguments.length; var args = new Array(l + 1); var promiseInput = false; for (var i = 0; i < l; ++i) { var arg = arguments[i]; if (!promiseInput) { // TODO: clean this up promiseInput = needsPromiseInput(arg); if (promiseInput === GET_THEN_ERROR$1) { var p = new Promise(noop); reject(p, GET_THEN_ERROR$1.value); return p; } else if (promiseInput && promiseInput !== true) { arg = wrapThenable(promiseInput, arg); } } args[i] = arg; } var promise = new Promise(noop); args[l] = function (err, val) { if (err) reject(promise, err);else if (options === undefined) resolve(promise, val);else if (options === true) resolve(promise, arrayResult(arguments));else if (isArray(options)) resolve(promise, makeObject(arguments, options));else resolve(promise, val); }; if (promiseInput) { return handlePromiseInput(promise, args, nodeFunc, self); } else { return handleValueInput(promise, args, nodeFunc, self); } }; fn.__proto__ = nodeFunc; return fn; } function handleValueInput(promise, args, nodeFunc, self) { var result = tryApply(nodeFunc, self, args); if (result === ERROR) { reject(promise, result.value); } return promise; } function handlePromiseInput(promise, args, nodeFunc, self) { return Promise.all(args).then(function (args) { var result = tryApply(nodeFunc, self, args); if (result === ERROR) { reject(promise, result.value); } return promise; }); } function needsPromiseInput(arg) { if (arg && typeof arg === 'object') { if (arg.constructor === Promise) { return true; } else { return getThen$1(arg); } } else { return false; } } /** This is a convenient alias for `RSVP.Promise.all`. @method all @static @for RSVP @param {Array} array Array of promises. @param {String} label An optional label. This is useful for tooling. */ function all$1(array, label) { return Promise.all(array, label); } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var AllSettled = function (_Enumerator) { _inherits(AllSettled, _Enumerator); function AllSettled(Constructor, entries, label) { return _possibleConstructorReturn(this, _Enumerator.call(this, Constructor, entries, false /* don't abort on reject */, label)); } return AllSettled; }(Enumerator); AllSettled.prototype._makeResult = makeSettledResult; /** `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing a fail-fast method, it waits until all the promises have returned and shows you all the results. This is useful if you want to handle multiple promises' failure states together as a set. Returns a promise that is fulfilled when all the given promises have been settled. The return promise is fulfilled with an array of the states of the promises passed into the `promises` array argument. Each state object will either indicate fulfillment or rejection, and provide the corresponding value or reason. The states will take one of the following formats: ```javascript { state: 'fulfilled', value: value } or { state: 'rejected', reason: reason } ``` Example: ```javascript let promise1 = RSVP.Promise.resolve(1); let promise2 = RSVP.Promise.reject(new Error('2')); let promise3 = RSVP.Promise.reject(new Error('3')); let promises = [ promise1, promise2, promise3 ]; RSVP.allSettled(promises).then(function(array){ // array == [ // { state: 'fulfilled', value: 1 }, // { state: 'rejected', reason: Error }, // { state: 'rejected', reason: Error } // ] // Note that for the second item, reason.message will be '2', and for the // third item, reason.message will be '3'. }, function(error) { // Not run. (This block would only be called if allSettled had failed, // for instance if passed an incorrect argument type.) }); ``` @method allSettled @static @for RSVP @param {Array} entries @param {String} label - optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled with an array of the settled states of the constituent promises. */ function allSettled(entries, label) { if (!isArray(entries)) { return Promise.reject(new TypeError("Promise.allSettled must be called with an array"), label); } return new AllSettled(Promise, entries, label).promise; } /** This is a convenient alias for `RSVP.Promise.race`. @method race @static @for RSVP @param {Array} array Array of promises. @param {String} label An optional label. This is useful for tooling. */ function race$1(array, label) { return Promise.race(array, label); } function _possibleConstructorReturn$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var hasOwnProperty = Object.prototype.hasOwnProperty; var PromiseHash = function (_Enumerator) { _inherits$1(PromiseHash, _Enumerator); function PromiseHash(Constructor, object) { var abortOnReject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var label = arguments[3]; return _possibleConstructorReturn$1(this, _Enumerator.call(this, Constructor, object, abortOnReject, label)); } PromiseHash.prototype._init = function _init(Constructor, object) { this._result = {}; this._enumerate(object); if (this._remaining === 0) { fulfill(this.promise, this._result); } }; PromiseHash.prototype._enumerate = function _enumerate(input) { var promise = this.promise; var results = []; for (var key in input) { if (hasOwnProperty.call(input, key)) { results.push({ position: key, entry: input[key] }); } } var length = results.length; this._remaining = length; var result = void 0; for (var i = 0; promise._state === PENDING && i < length; i++) { result = results[i]; this._eachEntry(result.entry, result.position); } }; return PromiseHash; }(Enumerator); /** `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array for its `promises` argument. Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The returned promise is fulfilled with a hash that has the same key names as the `promises` object argument. If any of the values in the object are not promises, they will simply be copied over to the fulfilled object. Example: ```javascript let promises = { myPromise: RSVP.resolve(1), yourPromise: RSVP.resolve(2), theirPromise: RSVP.resolve(3), notAPromise: 4 }; RSVP.hash(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: 1, // yourPromise: 2, // theirPromise: 3, // notAPromise: 4 // } }); ```` If any of the `promises` given to `RSVP.hash` are rejected, the first promise that is rejected will be given as the reason to the rejection handler. Example: ```javascript let promises = { myPromise: RSVP.resolve(1), rejectedPromise: RSVP.reject(new Error('rejectedPromise')), anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')), }; RSVP.hash(promises).then(function(hash){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === 'rejectedPromise' }); ``` An important note: `RSVP.hash` is intended for plain JavaScript objects that are just a set of keys and values. `RSVP.hash` will NOT preserve prototype chains. Example: ```javascript function MyConstructor(){ this.example = RSVP.resolve('Example'); } MyConstructor.prototype = { protoProperty: RSVP.resolve('Proto Property') }; let myObject = new MyConstructor(); RSVP.hash(myObject).then(function(hash){ // protoProperty will not be present, instead you will just have an // object that looks like: // { // example: 'Example' // } // // hash.hasOwnProperty('protoProperty'); // false // 'undefined' === typeof hash.protoProperty }); ``` @method hash @static @for RSVP @param {Object} object @param {String} label optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all properties of `promises` have been fulfilled, or rejected if any of them become rejected. */ function hash(object, label) { if (!isObject(object)) { return Promise.reject(new TypeError("Promise.hash must be called with an object"), label); } return new PromiseHash(Promise, object, label).promise; } function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var HashSettled = function (_PromiseHash) { _inherits$2(HashSettled, _PromiseHash); function HashSettled(Constructor, object, label) { return _possibleConstructorReturn$2(this, _PromiseHash.call(this, Constructor, object, false, label)); } return HashSettled; }(PromiseHash); HashSettled.prototype._makeResult = makeSettledResult; /** `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object instead of an array for its `promises` argument. Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method, but like `RSVP.allSettled`, `hashSettled` waits until all the constituent promises have returned and then shows you all the results with their states and values/reasons. This is useful if you want to handle multiple promises' failure states together as a set. Returns a promise that is fulfilled when all the given promises have been settled, or rejected if the passed parameters are invalid. The returned promise is fulfilled with a hash that has the same key names as the `promises` object argument. If any of the values in the object are not promises, they will be copied over to the fulfilled object and marked with state 'fulfilled'. Example: ```javascript let promises = { myPromise: RSVP.Promise.resolve(1), yourPromise: RSVP.Promise.resolve(2), theirPromise: RSVP.Promise.resolve(3), notAPromise: 4 }; RSVP.hashSettled(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: { state: 'fulfilled', value: 1 }, // yourPromise: { state: 'fulfilled', value: 2 }, // theirPromise: { state: 'fulfilled', value: 3 }, // notAPromise: { state: 'fulfilled', value: 4 } // } }); ``` If any of the `promises` given to `RSVP.hash` are rejected, the state will be set to 'rejected' and the reason for rejection provided. Example: ```javascript let promises = { myPromise: RSVP.Promise.resolve(1), rejectedPromise: RSVP.Promise.reject(new Error('rejection')), anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')), }; RSVP.hashSettled(promises).then(function(hash){ // hash here is an object that looks like: // { // myPromise: { state: 'fulfilled', value: 1 }, // rejectedPromise: { state: 'rejected', reason: Error }, // anotherRejectedPromise: { state: 'rejected', reason: Error }, // } // Note that for rejectedPromise, reason.message == 'rejection', // and for anotherRejectedPromise, reason.message == 'more rejection'. }); ``` An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype chains. Example: ```javascript function MyConstructor(){ this.example = RSVP.Promise.resolve('Example'); } MyConstructor.prototype = { protoProperty: RSVP.Promise.resolve('Proto Property') }; let myObject = new MyConstructor(); RSVP.hashSettled(myObject).then(function(hash){ // protoProperty will not be present, instead you will just have an // object that looks like: // { // example: { state: 'fulfilled', value: 'Example' } // } // // hash.hasOwnProperty('protoProperty'); // false // 'undefined' === typeof hash.protoProperty }); ``` @method hashSettled @for RSVP @param {Object} object @param {String} label optional string that describes the promise. Useful for tooling. @return {Promise} promise that is fulfilled when when all properties of `promises` have been settled. @static */ function hashSettled(object, label) { if (!isObject(object)) { return Promise.reject(new TypeError("RSVP.hashSettled must be called with an object"), label); } return new HashSettled(Promise, object, false, label).promise; } /** `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event loop in order to aid debugging. Promises A+ specifies that any exceptions that occur with a promise must be caught by the promises implementation and bubbled to the last handler. For this reason, it is recommended that you always specify a second rejection handler function to `then`. However, `RSVP.rethrow` will throw the exception outside of the promise, so it bubbles up to your console if in the browser, or domain/cause uncaught exception in Node. `rethrow` will also throw the error again so the error can be handled by the promise per the spec. ```javascript function throws(){ throw new Error('Whoops!'); } let promise = new RSVP.Promise(function(resolve, reject){ throws(); }); promise.catch(RSVP.rethrow).then(function(){ // Code here doesn't run because the promise became rejected due to an // error! }, function (err){ // handle the error here }); ``` The 'Whoops' error will be thrown on the next turn of the event loop and you can watch for it in your console. You can also handle it using a rejection handler given to `.then` or `.catch` on the returned promise. @method rethrow @static @for RSVP @param {Error} reason reason the promise became rejected. @throws Error @static */ function rethrow(reason) { setTimeout(function () { throw reason; }); throw reason; } /** `RSVP.defer` returns an object similar to jQuery's `$.Deferred`. `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s interface. New code should use the `RSVP.Promise` constructor instead. The object returned from `RSVP.defer` is a plain object with three properties: * promise - an `RSVP.Promise`. * reject - a function that causes the `promise` property on this object to become rejected * resolve - a function that causes the `promise` property on this object to become fulfilled. Example: ```javascript let deferred = RSVP.defer(); deferred.resolve("Success!"); deferred.promise.then(function(value){ // value here is "Success!" }); ``` @method defer @static @for RSVP @param {String} label optional string for labeling the promise. Useful for tooling. @return {Object} */ function defer(label) { var deferred = { resolve: undefined, reject: undefined }; deferred.promise = new Promise(function (resolve, reject) { deferred.resolve = resolve; deferred.reject = reject; }, label); return deferred; } /** `RSVP.map` is similar to JavaScript's native `map` method, except that it waits for all promises to become fulfilled before running the `mapFn` on each item in given to `promises`. `RSVP.map` returns a promise that will become fulfilled with the result of running `mapFn` on the values the promises become fulfilled with. For example: ```javascript let promise1 = RSVP.resolve(1); let promise2 = RSVP.resolve(2); let promise3 = RSVP.resolve(3); let promises = [ promise1, promise2, promise3 ]; let mapFn = function(item){ return item + 1; }; RSVP.map(promises, mapFn).then(function(result){ // result is [ 2, 3, 4 ] }); ``` If any of the `promises` given to `RSVP.map` are rejected, the first promise that is rejected will be given as an argument to the returned promise's rejection handler. For example: ```javascript let promise1 = RSVP.resolve(1); let promise2 = RSVP.reject(new Error('2')); let promise3 = RSVP.reject(new Error('3')); let promises = [ promise1, promise2, promise3 ]; let mapFn = function(item){ return item + 1; }; RSVP.map(promises, mapFn).then(function(array){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === '2' }); ``` `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, say you want to get all comments from a set of blog posts, but you need the blog posts first because they contain a url to those comments. ```javscript let mapFn = function(blogPost){ // getComments does some ajax and returns an RSVP.Promise that is fulfilled // with some comments data return getComments(blogPost.comments_url); }; // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled // with some blog post data RSVP.map(getBlogPosts(), mapFn).then(function(comments){ // comments is the result of asking the server for the comments // of all blog posts returned from getBlogPosts() }); ``` @method map @static @for RSVP @param {Array} promises @param {Function} mapFn function to be called on each fulfilled promise. @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled with the result of calling `mapFn` on each fulfilled promise or value when they become fulfilled. The promise will be rejected if any of the given `promises` become rejected. @static */ function map(promises, mapFn, label) { if (!isArray(promises)) { return Promise.reject(new TypeError("RSVP.map must be called with an array"), label); } if (!isFunction(mapFn)) { return Promise.reject(new TypeError("RSVP.map expects a function as a second argument"), label); } return Promise.all(promises, label).then(function (values) { var length = values.length; var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = mapFn(values[i]); } return Promise.all(results, label); }); } /** This is a convenient alias for `RSVP.Promise.resolve`. @method resolve @static @for RSVP @param {*} value value that the returned promise will be resolved with @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve$2(value, label) { return Promise.resolve(value, label); } /** This is a convenient alias for `RSVP.Promise.reject`. @method reject @static @for RSVP @param {*} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject$2(reason, label) { return Promise.reject(reason, label); } /** `RSVP.filter` is similar to JavaScript's native `filter` method, except that it waits for all promises to become fulfilled before running the `filterFn` on each item in given to `promises`. `RSVP.filter` returns a promise that will become fulfilled with the result of running `filterFn` on the values the promises become fulfilled with. For example: ```javascript let promise1 = RSVP.resolve(1); let promise2 = RSVP.resolve(2); let promise3 = RSVP.resolve(3); let promises = [promise1, promise2, promise3]; let filterFn = function(item){ return item > 1; }; RSVP.filter(promises, filterFn).then(function(result){ // result is [ 2, 3 ] }); ``` If any of the `promises` given to `RSVP.filter` are rejected, the first promise that is rejected will be given as an argument to the returned promise's rejection handler. For example: ```javascript let promise1 = RSVP.resolve(1); let promise2 = RSVP.reject(new Error('2')); let promise3 = RSVP.reject(new Error('3')); let promises = [ promise1, promise2, promise3 ]; let filterFn = function(item){ return item > 1; }; RSVP.filter(promises, filterFn).then(function(array){ // Code here never runs because there are rejected promises! }, function(reason) { // reason.message === '2' }); ``` `RSVP.filter` will also wait for any promises returned from `filterFn`. For instance, you may want to fetch a list of users then return a subset of those users based on some asynchronous operation: ```javascript let alice = { name: 'alice' }; let bob = { name: 'bob' }; let users = [ alice, bob ]; let promises = users.map(function(user){ return RSVP.resolve(user); }); let filterFn = function(user){ // Here, Alice has permissions to create a blog post, but Bob does not. return getPrivilegesForUser(user).then(function(privs){ return privs.can_create_blog_post === true; }); }; RSVP.filter(promises, filterFn).then(function(users){ // true, because the server told us only Alice can create a blog post. users.length === 1; // false, because Alice is the only user present in `users` users[0] === bob; }); ``` @method filter @static @for RSVP @param {Array} promises @param {Function} filterFn - function to be called on each resolved value to filter the final results. @param {String} label optional string describing the promise. Useful for tooling. @return {Promise} */ function resolveAll(promises, label) { return Promise.all(promises, label); } function resolveSingle(promise, label) { return Promise.resolve(promise, label).then(function (promises) { return resolveAll(promises, label); }); } function filter(promises, filterFn, label) { if (!isArray(promises) && !(isObject(promises) && promises.then !== undefined)) { return Promise.reject(new TypeError("RSVP.filter must be called with an array or promise"), label); } if (!isFunction(filterFn)) { return Promise.reject(new TypeError("RSVP.filter expects function as a second argument"), label); } var promise = isArray(promises) ? resolveAll(promises, label) : resolveSingle(promises, label); return promise.then(function (values) { var length = values.length; var filtered = new Array(length); for (var i = 0; i < length; i++) { filtered[i] = filterFn(values[i]); } return resolveAll(filtered, label).then(function (filtered) { var results = new Array(length); var newLength = 0; for (var _i = 0; _i < length; _i++) { if (filtered[_i]) { results[newLength] = values[_i]; newLength++; } } results.length = newLength; return results; }); }); } var len = 0; var vertxNext = void 0; function asap(callback, arg) { queue$1[len] = callback; queue$1[len + 1] = arg; len += 2; if (len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush$1(); } } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { var nextTick = process.nextTick; // node version 0.10.x displays a deprecation warning when nextTick is used recursively // setImmediate should be used instead instead var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { nextTick = setImmediate; } return function () { return nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { return node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { return function () { return setTimeout(flush, 1); }; } var queue$1 = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue$1[i]; var arg = queue$1[i + 1]; callback(arg); queue$1[i] = undefined; queue$1[i + 1] = undefined; } len = 0; } function attemptVertex() { try { var r = require; var vertx = r('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush$1 = void 0; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush$1 = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush$1 = useMutationObserver(); } else if (isWorker) { scheduleFlush$1 = useMessageChannel(); } else if (browserWindow === undefined && typeof require === 'function') { scheduleFlush$1 = attemptVertex(); } else { scheduleFlush$1 = useSetTimeout(); } var platform = void 0; /* global self */ if (typeof self === 'object') { platform = self; /* global global */ } else if (typeof global === 'object') { platform = global; } else { throw new Error('no global: `self` or `global` found'); } var _asap$cast$Promise$Ev; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } // defaults config.async = asap; config.after = function (cb) { return setTimeout(cb, 0); }; var cast = resolve$2; var async = function (callback, arg) { return config.async(callback, arg); }; function on() { config['on'].apply(config, arguments); } function off() { config['off'].apply(config, arguments); } // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { var callbacks = window['__PROMISE_INSTRUMENTATION__']; configure('instrument', true); for (var eventName in callbacks) { if (callbacks.hasOwnProperty(eventName)) { on(eventName, callbacks[eventName]); } } } // the default export here is for backwards compat: // https://github.com/tildeio/rsvp.js/issues/434 var rsvp = (_asap$cast$Promise$Ev = { asap: asap, cast: cast, Promise: Promise, EventTarget: EventTarget, all: all$1, allSettled: allSettled, race: race$1, hash: hash, hashSettled: hashSettled, rethrow: rethrow, defer: defer, denodeify: denodeify, configure: configure, on: on, off: off, resolve: resolve$2, reject: reject$2, map: map }, _defineProperty(_asap$cast$Promise$Ev, 'async', async), _defineProperty(_asap$cast$Promise$Ev, 'filter', filter), _asap$cast$Promise$Ev); exports['default'] = rsvp; exports.asap = asap; exports.cast = cast; exports.Promise = Promise; exports.EventTarget = EventTarget; exports.all = all$1; exports.allSettled = allSettled; exports.race = race$1; exports.hash = hash; exports.hashSettled = hashSettled; exports.rethrow = rethrow; exports.defer = defer; exports.denodeify = denodeify; exports.configure = configure; exports.on = on; exports.off = off; exports.resolve = resolve$2; exports.reject = reject$2; exports.map = map; exports.async = async; exports.filter = filter; Object.defineProperty(exports, '__esModule', { value: true }); }))); // var EPUBJS = EPUBJS || {}; EPUBJS.core = {}; var ELEMENT_NODE = 1; var TEXT_NODE = 3; var COMMENT_NODE = 8; var DOCUMENT_NODE = 9; //-- Get a element for an id EPUBJS.core.getEl = function(elem) { return document.getElementById(elem); }; //-- Get all elements for a class EPUBJS.core.getEls = function(classes) { return document.getElementsByClassName(classes); }; EPUBJS.core.request = function(url, type, withCredentials) { var supportsURL = window.URL; var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; var deferred = new RSVP.defer(); var xhr = new XMLHttpRequest(); var uri; //-- Check from PDF.js: // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js var xhrPrototype = XMLHttpRequest.prototype; var handler = function() { var r; if (this.readyState != this.DONE) return; if ((this.status === 200 || this.status === 0) && this.response) { // Android & Firefox reporting 0 for local & blob urls if (type == 'xml'){ // If this.responseXML wasn't set, try to parse using a DOMParser from text if(!this.responseXML) { r = new DOMParser().parseFromString(this.response, "application/xml"); } else { r = this.responseXML; } } else if (type == 'xhtml') { if (!this.responseXML){ r = new DOMParser().parseFromString(this.response, "application/xhtml+xml"); } else { r = this.responseXML; } } else if (type == 'html') { if (!this.responseXML){ r = new DOMParser().parseFromString(this.response, "text/html"); } else { r = this.responseXML; } } else if (type == 'json') { r = JSON.parse(this.response); } else if (type == 'blob') { if (supportsURL) { r = this.response; } else { //-- Safari doesn't support responseType blob, so create a blob from arraybuffer r = new Blob([this.response]); } } else { r = this.response; } deferred.resolve(r); } else { deferred.reject({ message : this.response, stack : new Error().stack }); } }; if (!('overrideMimeType' in xhrPrototype)) { // IE10 might have response, but not overrideMimeType Object.defineProperty(xhrPrototype, 'overrideMimeType', { value: function xmlHttpRequestOverrideMimeType(mimeType) {} }); } xhr.onreadystatechange = handler; xhr.open("GET", url, true); if(withCredentials) { xhr.withCredentials = true; } // If type isn't set, determine it from the file extension if(!type) { uri = EPUBJS.core.uri(url); type = uri.extension; type = { 'htm': 'html' }[type] || type; } if(type == 'blob'){ xhr.responseType = BLOB_RESPONSE; } if(type == "json") { xhr.setRequestHeader("Accept", "application/json"); } if(type == 'xml') { xhr.responseType = "document"; xhr.overrideMimeType('text/xml'); // for OPF parsing } if(type == 'xhtml') { xhr.responseType = "document"; } if(type == 'html') { xhr.responseType = "document"; } if(type == "binary") { xhr.responseType = "arraybuffer"; } xhr.send(); return deferred.promise; }; EPUBJS.core.toArray = function(obj) { var arr = []; for (var member in obj) { var newitm; if ( obj.hasOwnProperty(member) ) { newitm = obj[member]; newitm.ident = member; arr.push(newitm); } } return arr; }; //-- Parse the different parts of a url, returning a object EPUBJS.core.uri = function(url){ var uri = { protocol : '', host : '', path : '', origin : '', directory : '', base : '', filename : '', extension : '', fragment : '', href : url }, blob = url.indexOf('blob:'), doubleSlash = url.indexOf('://'), search = url.indexOf('?'), fragment = url.indexOf("#"), withoutProtocol, dot, firstSlash; if(blob === 0) { uri.protocol = "blob"; uri.base = url.indexOf(0, fragment); return uri; } if(fragment != -1) { uri.fragment = url.slice(fragment + 1); url = url.slice(0, fragment); } if(search != -1) { uri.search = url.slice(search + 1); url = url.slice(0, search); href = uri.href; } if(doubleSlash != -1) { uri.protocol = url.slice(0, doubleSlash); withoutProtocol = url.slice(doubleSlash+3); firstSlash = withoutProtocol.indexOf('/'); if(firstSlash === -1) { uri.host = uri.path; uri.path = ""; } else { uri.host = withoutProtocol.slice(0, firstSlash); uri.path = withoutProtocol.slice(firstSlash); } uri.origin = uri.protocol + "://" + uri.host; uri.directory = EPUBJS.core.folder(uri.path); uri.base = uri.origin + uri.directory; // return origin; } else { uri.path = url; uri.directory = EPUBJS.core.folder(url); uri.base = uri.directory; } //-- Filename uri.filename = url.replace(uri.base, ''); dot = uri.filename.lastIndexOf('.'); if(dot != -1) { uri.extension = uri.filename.slice(dot+1); } return uri; }; //-- Parse out the folder, will return everything before the last slash EPUBJS.core.folder = function(url){ var lastSlash = url.lastIndexOf('/'); if(lastSlash == -1) var folder = ''; folder = url.slice(0, lastSlash + 1); return folder; }; //-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 EPUBJS.core.dataURLToBlob = function(dataURL) { var BASE64_MARKER = ';base64,', parts, contentType, raw, rawLength, uInt8Array; if (dataURL.indexOf(BASE64_MARKER) == -1) { parts = dataURL.split(','); contentType = parts[0].split(':')[1]; raw = parts[1]; return new Blob([raw], {type: contentType}); } parts = dataURL.split(BASE64_MARKER); contentType = parts[0].split(':')[1]; raw = window.atob(parts[1]); rawLength = raw.length; uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], {type: contentType}); }; //-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously EPUBJS.core.addScript = function(src, callback, target) { var s, r; r = false; s = document.createElement('script'); s.type = 'text/javascript'; s.async = false; s.src = src; s.onload = s.onreadystatechange = function() { if ( !r && (!this.readyState || this.readyState == 'complete') ) { r = true; if(callback) callback(); } }; target = target || document.body; target.appendChild(s); }; EPUBJS.core.addScripts = function(srcArr, callback, target) { var total = srcArr.length, curr = 0, cb = function(){ curr++; if(total == curr){ if(callback) callback(); }else{ EPUBJS.core.addScript(srcArr[curr], cb, target); } }; EPUBJS.core.addScript(srcArr[curr], cb, target); }; EPUBJS.core.addCss = function(src, callback, target) { var s, r; r = false; s = document.createElement('link'); s.type = 'text/css'; s.rel = "stylesheet"; s.href = src; s.onload = s.onreadystatechange = function() { if ( !r && (!this.readyState || this.readyState == 'complete') ) { r = true; if(callback) callback(); } }; target = target || document.body; target.appendChild(s); }; EPUBJS.core.prefixed = function(unprefixed) { var vendors = ["Webkit", "Moz", "O", "ms" ], prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), length = vendors.length; if (typeof(document.documentElement.style[unprefixed]) != 'undefined') { return unprefixed; } for ( var i=0; i < length; i++ ) { if (typeof(document.documentElement.style[vendors[i] + upper]) != 'undefined') { return vendors[i] + upper; } } return unprefixed; }; EPUBJS.core.resolveUrl = function(base, path) { var url, segments = [], uri = EPUBJS.core.uri(path), folders = base.split("/"), paths; if(uri.host) { return path; } folders.pop(); paths = path.split("/"); paths.forEach(function(p){ if(p === ".."){ folders.pop(); }else{ segments.push(p); } }); url = folders.concat(segments); return url.join("/"); }; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript EPUBJS.core.uuid = function() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random()*16)%16 | 0; d = Math.floor(d/16); return (c=='x' ? r : (r&0x7|0x8)).toString(16); }); return uuid; }; // Fast quicksort insert for sorted array -- based on: // http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers EPUBJS.core.insert = function(item, array, compareFunction) { var location = EPUBJS.core.locationOf(item, array, compareFunction); array.splice(location, 0, item); return location; }; EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { var start = _start || 0; var end = _end || array.length; var pivot = parseInt(start + (end - start) / 2); var compared; if(!compareFunction){ compareFunction = function(a, b) { if(a > b) return 1; if(a < b) return -1; if(a = b) return 0; }; } if(end-start <= 0) { return pivot; } compared = compareFunction(array[pivot], item); if(end-start === 1) { return compared > 0 ? pivot : pivot + 1; } if(compared === 0) { return pivot; } if(compared === -1) { return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); } else{ return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); } }; EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { var start = _start || 0; var end = _end || array.length; var pivot = parseInt(start + (end - start) / 2); var compared; if(!compareFunction){ compareFunction = function(a, b) { if(a > b) return 1; if(a < b) return -1; if(a = b) return 0; }; } if(end-start <= 0) { return -1; // Not found } compared = compareFunction(array[pivot], item); if(end-start === 1) { return compared === 0 ? pivot : -1; } if(compared === 0) { return pivot; // Found } if(compared === -1) { return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); } else{ return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); } }; EPUBJS.core.queue = function(_scope){ var _q = []; var scope = _scope; // Add an item to the queue var enqueue = function(funcName, args, context) { _q.push({ "funcName" : funcName, "args" : args, "context" : context }); return _q; }; // Run one item var dequeue = function(){ var inwait; if(_q.length) { inwait = _q.shift(); // Defer to any current tasks // setTimeout(function(){ scope[inwait.funcName].apply(inwait.context || scope, inwait.args); // }, 0); } }; // Run All var flush = function(){ while(_q.length) { dequeue(); } }; // Clear all items in wait var clear = function(){ _q = []; }; var length = function(){ return _q.length; }; return { "enqueue" : enqueue, "dequeue" : dequeue, "flush" : flush, "clear" : clear, "length" : length }; }; // From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js /** * Gets an XPath for an element which describes its hierarchical location. */ EPUBJS.core.getElementXPath = function(element) { if (element && element.id) { return '//*[@id="' + element.id + '"]'; } else { return EPUBJS.core.getElementTreeXPath(element); } }; EPUBJS.core.getElementTreeXPath = function(element) { var paths = []; var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); var index, nodeName, tagName, pathIndex; if(element.nodeType === Node.TEXT_NODE){ // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; index = EPUBJS.core.indexOfTextNode(element) + 1; paths.push("text()["+index+"]"); element = element.parentNode; } // Use nodeName (instead of localName) so namespace prefix is included (if any). for (; element && element.nodeType == 1; element = element.parentNode) { index = 0; for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) { // Ignore document type declaration. if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { continue; } if (sibling.nodeName == element.nodeName) { ++index; } } nodeName = element.nodeName.toLowerCase(); tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); pathIndex = (index ? "[" + (index+1) + "]" : ""); paths.splice(0, 0, tagName + pathIndex); } return paths.length ? "./" + paths.join("/") : null; }; EPUBJS.core.nsResolver = function(prefix) { var ns = { 'xhtml' : 'http://www.w3.org/1999/xhtml', 'epub': 'http://www.idpf.org/2007/ops' }; return ns[prefix] || null; }; //https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 EPUBJS.core.cleanStringForXpath = function(str) { var parts = str.match(/[^'"]+|['"]/g); parts = parts.map(function(part){ if (part === "'") { return '\"\'\"'; // output "'" } if (part === '"') { return "\'\"\'"; // output '"' } return "\'" + part + "\'"; }); return "concat(\'\'," + parts.join(",") + ")"; }; EPUBJS.core.indexOfTextNode = function(textNode){ var parent = textNode.parentNode; var children = parent.childNodes; var sib; var index = -1; for (var i = 0; i < children.length; i++) { sib = children[i]; if(sib.nodeType === Node.TEXT_NODE){ index++; } if(sib == textNode) break; } return index; }; // Underscore EPUBJS.core.defaults = function(obj) { for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; EPUBJS.core.extend = function(target) { var sources = [].slice.call(arguments, 1); sources.forEach(function (source) { if(!source) return; Object.getOwnPropertyNames(source).forEach(function(propName) { Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); }); }); return target; }; EPUBJS.core.clone = function(obj) { return EPUBJS.core.isArray(obj) ? obj.slice() : EPUBJS.core.extend({}, obj); }; EPUBJS.core.isElement = function(obj) { return !!(obj && obj.nodeType == 1); }; EPUBJS.core.isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; EPUBJS.core.isString = function(str) { return (typeof str === 'string' || str instanceof String); }; EPUBJS.core.isArray = Array.isArray || function(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; // Lodash EPUBJS.core.values = function(object) { var index = -1; var props, length, result; if(!object) return []; props = Object.keys(object); length = props.length; result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; }; EPUBJS.core.indexOfNode = function(node, typeId) { var parent = node.parentNode; var children = parent.childNodes; var sib; var index = -1; for (var i = 0; i < children.length; i++) { sib = children[i]; if (sib.nodeType === typeId) { index++; } if (sib == node) break; } return index; } EPUBJS.core.indexOfTextNode = function(textNode) { return EPUBJS.core.indexOfNode(textNode, TEXT_NODE); } EPUBJS.core.indexOfElementNode = function(elementNode) { return EPUBJS.core.indexOfNode(elementNode, ELEMENT_NODE); } var EPUBJS = EPUBJS || {}; EPUBJS.reader = {}; EPUBJS.reader.plugins = {}; //-- Attach extra Controllers as plugins (like search?) (function(root, $) { var previousReader = root.ePubReader || {}; var ePubReader = root.ePubReader = function(path, options) { return new EPUBJS.Reader(path, options); }; //exports to multiple environments if (typeof define === 'function' && define.amd) { //AMD define(function(){ return Reader; }); } else if (typeof module != "undefined" && module.exports) { //Node module.exports = ePubReader; } })(window, jQuery); EPUBJS.Reader = function(bookPath, _options) { var reader = this; var book; var plugin; var $viewer = $("#viewer"); var search = window.location.search; var parameters; this.settings = EPUBJS.core.defaults(_options || {}, { bookPath : bookPath, restore : false, reload : false, bookmarks : undefined, annotations : undefined, contained : undefined, bookKey : undefined, styles : undefined, sidebarReflow: false, generatePagination: false, history: true }); // Overide options with search parameters if(search) { parameters = search.slice(1).split("&"); parameters.forEach(function(p){ var split = p.split("="); var name = split[0]; var value = split[1] || ''; reader.settings[name] = decodeURIComponent(value); }); } this.setBookKey(this.settings.bookPath); //-- This could be username + path or any unique string if(this.settings.restore && this.isSaved()) { this.applySavedSettings(); } this.settings.styles = this.settings.styles || { fontSize : "100%" }; this.book = book = new ePub(this.settings.bookPath, this.settings); this.offline = false; this.sidebarOpen = false; if(!this.settings.bookmarks) { this.settings.bookmarks = []; } if(!this.settings.annotations) { this.settings.annotations = []; } if(this.settings.generatePagination) { book.generatePagination($viewer.width(), $viewer.height()); } this.rendition = book.renderTo("viewer", { ignoreClass: "annotator-hl", width: "100%", height: "100%" }); if(this.settings.previousLocationCfi) { this.displayed = this.rendition.display(this.settings.previousLocationCfi); } else { this.displayed = this.rendition.display(); } book.ready.then(function () { reader.ReaderController = EPUBJS.reader.ReaderController.call(reader, book); reader.SettingsController = EPUBJS.reader.SettingsController.call(reader, book); reader.ControlsController = EPUBJS.reader.ControlsController.call(reader, book); reader.SidebarController = EPUBJS.reader.SidebarController.call(reader, book); reader.BookmarksController = EPUBJS.reader.BookmarksController.call(reader, book); reader.NotesController = EPUBJS.reader.NotesController.call(reader, book); window.addEventListener("hashchange", this.hashChanged.bind(this), false); document.addEventListener('keydown', this.adjustFontSize.bind(this), false); this.rendition.on("keydown", this.adjustFontSize.bind(this)); this.rendition.on("keydown", reader.ReaderController.arrowKeys.bind(this)); this.rendition.on("selected", this.selectedRange.bind(this)); }.bind(this)).then(function() { reader.ReaderController.hideLoader(); }.bind(this)); // Call Plugins for(plugin in EPUBJS.reader.plugins) { if(EPUBJS.reader.plugins.hasOwnProperty(plugin)) { reader[plugin] = EPUBJS.reader.plugins[plugin].call(reader, book); } } book.loaded.metadata.then(function(meta) { reader.MetaController = EPUBJS.reader.MetaController.call(reader, meta); }); book.loaded.navigation.then(function(navigation) { reader.TocController = EPUBJS.reader.TocController.call(reader, navigation); }); window.addEventListener("beforeunload", this.unload.bind(this), false); return this; }; EPUBJS.Reader.prototype.adjustFontSize = function(e) { var fontSize; var interval = 2; var PLUS = 187; var MINUS = 189; var ZERO = 48; var MOD = (e.ctrlKey || e.metaKey ); if(!this.settings.styles) return; if(!this.settings.styles.fontSize) { this.settings.styles.fontSize = "100%"; } fontSize = parseInt(this.settings.styles.fontSize.slice(0, -1)); if(MOD && e.keyCode == PLUS) { e.preventDefault(); this.book.setStyle("fontSize", (fontSize + interval) + "%"); } if(MOD && e.keyCode == MINUS){ e.preventDefault(); this.book.setStyle("fontSize", (fontSize - interval) + "%"); } if(MOD && e.keyCode == ZERO){ e.preventDefault(); this.book.setStyle("fontSize", "100%"); } }; EPUBJS.Reader.prototype.addBookmark = function(cfi) { var present = this.isBookmarked(cfi); if(present > -1 ) return; this.settings.bookmarks.push(cfi); this.trigger("reader:bookmarked", cfi); }; EPUBJS.Reader.prototype.removeBookmark = function(cfi) { var bookmark = this.isBookmarked(cfi); if( bookmark === -1 ) return; this.settings.bookmarks.splice(bookmark, 1); this.trigger("reader:unbookmarked", bookmark); }; EPUBJS.Reader.prototype.isBookmarked = function(cfi) { var bookmarks = this.settings.bookmarks; return bookmarks.indexOf(cfi); }; /* EPUBJS.Reader.prototype.searchBookmarked = function(cfi) { var bookmarks = this.settings.bookmarks, len = bookmarks.length, i; for(i = 0; i < len; i++) { if (bookmarks[i]['cfi'] === cfi) return i; } return -1; }; */ EPUBJS.Reader.prototype.clearBookmarks = function() { this.settings.bookmarks = []; }; //-- Notes EPUBJS.Reader.prototype.addNote = function(note) { this.settings.annotations.push(note); }; EPUBJS.Reader.prototype.removeNote = function(note) { var index = this.settings.annotations.indexOf(note); if( index === -1 ) return; delete this.settings.annotations[index]; }; EPUBJS.Reader.prototype.clearNotes = function() { this.settings.annotations = []; }; //-- Settings EPUBJS.Reader.prototype.setBookKey = function(identifier){ if(!this.settings.bookKey) { this.settings.bookKey = "epubjsreader:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; } return this.settings.bookKey; }; //-- Checks if the book setting can be retrieved from localStorage EPUBJS.Reader.prototype.isSaved = function(bookPath) { var storedSettings; if(!localStorage) { return false; } storedSettings = localStorage.getItem(this.settings.bookKey); if(storedSettings === null) { return false; } else { return true; } }; EPUBJS.Reader.prototype.removeSavedSettings = function() { if(!localStorage) { return false; } localStorage.removeItem(this.settings.bookKey); }; EPUBJS.Reader.prototype.applySavedSettings = function() { var stored; if(!localStorage) { return false; } try { stored = JSON.parse(localStorage.getItem(this.settings.bookKey)); } catch (e) { // parsing error of localStorage return false; } if(stored) { // Merge styles if(stored.styles) { this.settings.styles = EPUBJS.core.defaults(this.settings.styles || {}, stored.styles); } // Merge the rest this.settings = EPUBJS.core.defaults(this.settings, stored); return true; } else { return false; } }; EPUBJS.Reader.prototype.saveSettings = function(){ if(this.book) { this.settings.previousLocationCfi = this.rendition.currentLocation().start.cfi; } if(!localStorage) { return false; } localStorage.setItem(this.settings.bookKey, JSON.stringify(this.settings)); }; EPUBJS.Reader.prototype.unload = function(){ if(this.settings.restore && localStorage) { this.saveSettings(); } }; EPUBJS.Reader.prototype.hashChanged = function(){ var hash = window.location.hash.slice(1); this.rendition.display(hash); }; EPUBJS.Reader.prototype.selectedRange = function(cfiRange){ var cfiFragment = "#"+cfiRange; // Update the History Location if(this.settings.history && window.location.hash != cfiFragment) { // Add CFI fragment to the history history.pushState({}, '', cfiFragment); this.currentLocationCfi = cfiRange; } }; //-- Enable binding events to reader RSVP.EventTarget.mixin(EPUBJS.Reader.prototype); EPUBJS.reader.BookmarksController = function() { var reader = this; var book = this.book; var rendition = this.rendition; var $bookmarks = $("#bookmarksView"), $list = $bookmarks.find("#bookmarks"); var docfrag = document.createDocumentFragment(); var show = function() { $bookmarks.show(); }; var hide = function() { $bookmarks.hide(); }; var counter = 0; var createBookmarkItem = function(cfi) { var listitem = document.createElement("li"), link = document.createElement("a"); listitem.id = "bookmark-"+counter; listitem.classList.add('list_item'); var spineItem = book.spine.get(cfi); var tocItem; if (spineItem.index in book.navigation.toc) { tocItem = book.navigation.toc[spineItem.index]; link.textContent = tocItem.label; } else { link.textContent = cfi; } link.href = cfi; link.classList.add('bookmark_link'); link.addEventListener("click", function(event){ var cfi = this.getAttribute('href'); rendition.display(cfi); event.preventDefault(); }, false); listitem.appendChild(link); counter++; return listitem; }; this.settings.bookmarks.forEach(function(cfi) { var bookmark = createBookmarkItem(cfi); docfrag.appendChild(bookmark); }); $list.append(docfrag); this.on("reader:bookmarked", function(cfi) { var item = createBookmarkItem(cfi); $list.append(item); }); this.on("reader:unbookmarked", function(index) { var $item = $("#bookmark-"+index); $item.remove(); }); return { "show" : show, "hide" : hide }; }; EPUBJS.reader.ControlsController = function(book) { var reader = this; var rendition = this.rendition; var $store = $("#store"), $fullscreen = $("#fullscreen"), $fullscreenicon = $("#fullscreenicon"), $cancelfullscreenicon = $("#cancelfullscreenicon"), $slider = $("#slider"), $main = $("#main"), $sidebar = $("#sidebar"), $settings = $("#setting"), $bookmark = $("#bookmark"); /* var goOnline = function() { reader.offline = false; // $store.attr("src", $icon.data("save")); }; var goOffline = function() { reader.offline = true; // $store.attr("src", $icon.data("saved")); }; var fullscreen = false; book.on("book:online", goOnline); book.on("book:offline", goOffline); */ $slider.on("click", function () { if(reader.sidebarOpen) { reader.SidebarController.hide(); $slider.addClass("icon-menu"); $slider.removeClass("icon-right"); } else { reader.SidebarController.show(); $slider.addClass("icon-right"); $slider.removeClass("icon-menu"); } }); if(typeof screenfull !== 'undefined') { $fullscreen.on("click", function() { screenfull.toggle($('#container')[0]); }); if(screenfull.raw) { document.addEventListener(screenfull.raw.fullscreenchange, function() { fullscreen = screenfull.isFullscreen; if(fullscreen) { $fullscreen .addClass("icon-resize-small") .removeClass("icon-resize-full"); } else { $fullscreen .addClass("icon-resize-full") .removeClass("icon-resize-small"); } }); } } $settings.on("click", function() { reader.SettingsController.show(); }); $bookmark.on("click", function() { var cfi = reader.rendition.currentLocation().start.cfi; var bookmarked = reader.isBookmarked(cfi); if(bookmarked === -1) { //-- Add bookmark reader.addBookmark(cfi); $bookmark .addClass("icon-bookmark") .removeClass("icon-bookmark-empty"); } else { //-- Remove Bookmark reader.removeBookmark(cfi); $bookmark .removeClass("icon-bookmark") .addClass("icon-bookmark-empty"); } }); rendition.on('relocated', function(location){ var cfi = location.start.cfi; var cfiFragment = "#" + cfi; //-- Check if bookmarked var bookmarked = reader.isBookmarked(cfi); if(bookmarked === -1) { //-- Not bookmarked $bookmark .removeClass("icon-bookmark") .addClass("icon-bookmark-empty"); } else { //-- Bookmarked $bookmark .addClass("icon-bookmark") .removeClass("icon-bookmark-empty"); } reader.currentLocationCfi = cfi; // Update the History Location if(reader.settings.history && window.location.hash != cfiFragment) { // Add CFI fragment to the history history.pushState({}, '', cfiFragment); } }); return { }; }; EPUBJS.reader.MetaController = function(meta) { var title = meta.title, author = meta.creator; var $title = $("#book-title"), $author = $("#chapter-title"), $dash = $("#title-seperator"); document.title = title+" – "+author; $title.html(title); $author.html(author); $dash.show(); }; EPUBJS.reader.NotesController = function() { var book = this.book; var rendition = this.rendition; var reader = this; var $notesView = $("#notesView"); var $notes = $("#notes"); var $text = $("#note-text"); var $anchor = $("#note-anchor"); var annotations = reader.settings.annotations; var renderer = book.renderer; var popups = []; var epubcfi = new ePub.CFI(); var show = function() { $notesView.show(); }; var hide = function() { $notesView.hide(); } var insertAtPoint = function(e) { var range; var textNode; var offset; var doc = book.renderer.doc; var cfi; var annotation; // standard if (doc.caretPositionFromPoint) { range = doc.caretPositionFromPoint(e.clientX, e.clientY); textNode = range.offsetNode; offset = range.offset; // WebKit } else if (doc.caretRangeFromPoint) { range = doc.caretRangeFromPoint(e.clientX, e.clientY); textNode = range.startContainer; offset = range.startOffset; } if (textNode.nodeType !== 3) { for (var i=0; i < textNode.childNodes.length; i++) { if (textNode.childNodes[i].nodeType == 3) { textNode = textNode.childNodes[i]; break; } } } // Find the end of the sentance offset = textNode.textContent.indexOf(".", offset); if(offset === -1){ offset = textNode.length; // Last item } else { offset += 1; // After the period } cfi = epubcfi.generateCfiFromTextNode(textNode, offset, book.renderer.currentChapter.cfiBase); annotation = { annotatedAt: new Date(), anchor: cfi, body: $text.val() } // add to list reader.addNote(annotation); // attach addAnnotation(annotation); placeMarker(annotation); // clear $text.val(''); $anchor.text("Attach"); $text.prop("disabled", false); rendition.off("click", insertAtPoint); }; var addAnnotation = function(annotation){ var note = document.createElement("li"); var link = document.createElement("a"); note.innerHTML = annotation.body; // note.setAttribute("ref", annotation.anchor); link.innerHTML = " context &#187;"; link.href = "#"+annotation.anchor; link.onclick = function(){ rendition.display(annotation.anchor); return false; }; note.appendChild(link); $notes.append(note); }; var placeMarker = function(annotation){ var doc = book.renderer.doc; var marker = document.createElement("span"); var mark = document.createElement("a"); marker.classList.add("footnotesuperscript", "reader_generated"); marker.style.verticalAlign = "super"; marker.style.fontSize = ".75em"; // marker.style.position = "relative"; marker.style.lineHeight = "1em"; // mark.style.display = "inline-block"; mark.style.padding = "2px"; mark.style.backgroundColor = "#fffa96"; mark.style.borderRadius = "5px"; mark.style.cursor = "pointer"; marker.id = "note-"+EPUBJS.core.uuid(); mark.innerHTML = annotations.indexOf(annotation) + 1 + "[Reader]"; marker.appendChild(mark); epubcfi.addMarker(annotation.anchor, doc, marker); markerEvents(marker, annotation.body); } var markerEvents = function(item, txt){ var id = item.id; var showPop = function(){ var poppos, iheight = renderer.height, iwidth = renderer.width, tip, pop, maxHeight = 225, itemRect, left, top, pos; //-- create a popup with endnote inside of it if(!popups[id]) { popups[id] = document.createElement("div"); popups[id].setAttribute("class", "popup"); pop_content = document.createElement("div"); popups[id].appendChild(pop_content); pop_content.innerHTML = txt; pop_content.setAttribute("class", "pop_content"); renderer.render.document.body.appendChild(popups[id]); //-- TODO: will these leak memory? - Fred popups[id].addEventListener("mouseover", onPop, false); popups[id].addEventListener("mouseout", offPop, false); //-- Add hide on page change rendition.on("locationChanged", hidePop, this); rendition.on("locationChanged", offPop, this); // chapter.book.on("renderer:chapterDestroy", hidePop, this); } pop = popups[id]; //-- get location of item itemRect = item.getBoundingClientRect(); left = itemRect.left; top = itemRect.top; //-- show the popup pop.classList.add("show"); //-- locations of popup popRect = pop.getBoundingClientRect(); //-- position the popup pop.style.left = left - popRect.width / 2 + "px"; pop.style.top = top + "px"; //-- Adjust max height if(maxHeight > iheight / 2.5) { maxHeight = iheight / 2.5; pop_content.style.maxHeight = maxHeight + "px"; } //-- switch above / below if(popRect.height + top >= iheight - 25) { pop.style.top = top - popRect.height + "px"; pop.classList.add("above"); }else{ pop.classList.remove("above"); } //-- switch left if(left - popRect.width <= 0) { pop.style.left = left + "px"; pop.classList.add("left"); }else{ pop.classList.remove("left"); } //-- switch right if(left + popRect.width / 2 >= iwidth) { //-- TEMP MOVE: 300 pop.style.left = left - 300 + "px"; popRect = pop.getBoundingClientRect(); pop.style.left = left - popRect.width + "px"; //-- switch above / below again if(popRect.height + top >= iheight - 25) { pop.style.top = top - popRect.height + "px"; pop.classList.add("above"); }else{ pop.classList.remove("above"); } pop.classList.add("right"); }else{ pop.classList.remove("right"); } } var onPop = function(){ popups[id].classList.add("on"); } var offPop = function(){ popups[id].classList.remove("on"); } var hidePop = function(){ setTimeout(function(){ popups[id].classList.remove("show"); }, 100); } var openSidebar = function(){ reader.ReaderController.slideOut(); show(); }; item.addEventListener("mouseover", showPop, false); item.addEventListener("mouseout", hidePop, false); item.addEventListener("click", openSidebar, false); } $anchor.on("click", function(e){ $anchor.text("Cancel"); $text.prop("disabled", "true"); // listen for selection rendition.on("click", insertAtPoint); }); annotations.forEach(function(note) { addAnnotation(note); }); /* renderer.registerHook("beforeChapterDisplay", function(callback, renderer){ var chapter = renderer.currentChapter; annotations.forEach(function(note) { var cfi = epubcfi.parse(note.anchor); if(cfi.spinePos === chapter.spinePos) { try { placeMarker(note); } catch(e) { console.log("anchoring failed", note.anchor); } } }); callback(); }, true); */ return { "show" : show, "hide" : hide }; }; EPUBJS.reader.ReaderController = function(book) { var $main = $("#main"), $divider = $("#divider"), $loader = $("#loader"), $next = $("#next"), $prev = $("#prev"); var reader = this; var book = this.book; var rendition = this.rendition; var slideIn = function() { var currentPosition = rendition.currentLocation().start.cfi; if (reader.settings.sidebarReflow){ $main.removeClass('single'); $main.one("transitionend", function(){ rendition.resize(); }); } else { $main.removeClass("closed"); } }; var slideOut = function() { var location = rendition.currentLocation(); if (!location) { return; } var currentPosition = location.start.cfi; if (reader.settings.sidebarReflow){ $main.addClass('single'); $main.one("transitionend", function(){ rendition.resize(); }); } else { $main.addClass("closed"); } }; var showLoader = function() { $loader.show(); hideDivider(); }; var hideLoader = function() { $loader.hide(); //-- If the book is using spreads, show the divider // if(book.settings.spreads) { // showDivider(); // } }; var showDivider = function() { $divider.addClass("show"); }; var hideDivider = function() { $divider.removeClass("show"); }; var keylock = false; var arrowKeys = function(e) { if(e.keyCode == 37) { if(book.package.metadata.direction === "rtl") { rendition.next(); } else { rendition.prev(); } $prev.addClass("active"); keylock = true; setTimeout(function(){ keylock = false; $prev.removeClass("active"); }, 100); e.preventDefault(); } if(e.keyCode == 39) { if(book.package.metadata.direction === "rtl") { rendition.prev(); } else { rendition.next(); } $next.addClass("active"); keylock = true; setTimeout(function(){ keylock = false; $next.removeClass("active"); }, 100); e.preventDefault(); } } document.addEventListener('keydown', arrowKeys, false); $next.on("click", function(e){ if(book.package.metadata.direction === "rtl") { rendition.prev(); } else { rendition.next(); } e.preventDefault(); }); $prev.on("click", function(e){ if(book.package.metadata.direction === "rtl") { rendition.next(); } else { rendition.prev(); } e.preventDefault(); }); rendition.on("layout", function(props){ if(props.spread === true) { showDivider(); } else { hideDivider(); } }); rendition.on('relocated', function(location){ if (location.atStart) { $prev.addClass("disabled"); } if (location.atEnd) { $next.addClass("disabled"); } }); return { "slideOut" : slideOut, "slideIn" : slideIn, "showLoader" : showLoader, "hideLoader" : hideLoader, "showDivider" : showDivider, "hideDivider" : hideDivider, "arrowKeys" : arrowKeys }; }; EPUBJS.reader.SettingsController = function() { var book = this.book; var reader = this; var $settings = $("#settings-modal"), $overlay = $(".overlay"); var show = function() { $settings.addClass("md-show"); }; var hide = function() { $settings.removeClass("md-show"); }; var $sidebarReflowSetting = $('#sidebarReflow'); $sidebarReflowSetting.on('click', function() { reader.settings.sidebarReflow = !reader.settings.sidebarReflow; }); $settings.find(".closer").on("click", function() { hide(); }); $overlay.on("click", function() { hide(); }); return { "show" : show, "hide" : hide }; }; EPUBJS.reader.SidebarController = function(book) { var reader = this; var $sidebar = $("#sidebar"), $panels = $("#panels"); var activePanel = "Toc"; var changePanelTo = function(viewName) { var controllerName = viewName + "Controller"; if(activePanel == viewName || typeof reader[controllerName] === 'undefined' ) return; reader[activePanel+ "Controller"].hide(); reader[controllerName].show(); activePanel = viewName; $panels.find('.active').removeClass("active"); $panels.find("#show-" + viewName ).addClass("active"); }; var getActivePanel = function() { return activePanel; }; var show = function() { reader.sidebarOpen = true; reader.ReaderController.slideOut(); $sidebar.addClass("open"); } var hide = function() { reader.sidebarOpen = false; reader.ReaderController.slideIn(); $sidebar.removeClass("open"); } $panels.find(".show_view").on("click", function(event) { var view = $(this).data("view"); changePanelTo(view); event.preventDefault(); }); return { 'show' : show, 'hide' : hide, 'getActivePanel' : getActivePanel, 'changePanelTo' : changePanelTo }; }; EPUBJS.reader.TocController = function(toc) { var book = this.book; var rendition = this.rendition; var $list = $("#tocView"), docfrag = document.createDocumentFragment(); var currentChapter = false; var generateTocItems = function(toc, level) { var container = document.createElement("ul"); if(!level) level = 1; toc.forEach(function(chapter) { var listitem = document.createElement("li"), link = document.createElement("a"); toggle = document.createElement("a"); var subitems; listitem.id = "toc-"+chapter.id; listitem.classList.add('list_item'); link.textContent = chapter.label; link.href = chapter.href; link.classList.add('toc_link'); listitem.appendChild(link); if(chapter.subitems && chapter.subitems.length > 0) { level++; subitems = generateTocItems(chapter.subitems, level); toggle.classList.add('toc_toggle'); listitem.insertBefore(toggle, link); listitem.appendChild(subitems); } container.appendChild(listitem); }); return container; }; var onShow = function() { $list.show(); }; var onHide = function() { $list.hide(); }; var chapterChange = function(e) { var id = e.id, $item = $list.find("#toc-"+id), $current = $list.find(".currentChapter"), $open = $list.find('.openChapter'); if($item.length){ if($item != $current && $item.has(currentChapter).length > 0) { $current.removeClass("currentChapter"); } $item.addClass("currentChapter"); // $open.removeClass("openChapter"); $item.parents('li').addClass("openChapter"); } }; rendition.on('renderered', chapterChange); var tocitems = generateTocItems(toc); docfrag.appendChild(tocitems); $list.append(docfrag); $list.find(".toc_link").on("click", function(event){ var url = this.getAttribute('href'); event.preventDefault(); //-- Provide the Book with the url to show // The Url must be found in the books manifest rendition.display(url); $list.find(".currentChapter") .addClass("openChapter") .removeClass("currentChapter"); $(this).parent('li').addClass("currentChapter"); }); $list.find(".toc_toggle").on("click", function(event){ var $el = $(this).parent('li'), open = $el.hasClass("openChapter"); event.preventDefault(); if(open){ $el.removeClass("openChapter"); } else { $el.addClass("openChapter"); } }); return { "show" : onShow, "hide" : onHide }; }; //# sourceMappingURL=reader.js.map
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/reader.js
reader.js
window.hypothesisConfig = function() { var Annotator = window.Annotator; var $main = $("#main"); function EpubAnnotationSidebar(elem, options) { options = { server: true, origin: true, showHighlights: true, Toolbar: {container: '#annotation-controls'} } Annotator.Host.call(this, elem, options); } EpubAnnotationSidebar.prototype = Object.create(Annotator.Host.prototype); EpubAnnotationSidebar.prototype.show = function() { this.frame.css({ 'margin-left': (-1 * this.frame.width()) + "px" }); this.frame.removeClass('annotator-collapsed'); if (!$main.hasClass('single')) { $main.addClass("single"); this.toolbar.find('[name=sidebar-toggle]').removeClass('h-icon-chevron-left').addClass('h-icon-chevron-right'); this.setVisibleHighlights(true); } }; EpubAnnotationSidebar.prototype.hide = function() { this.frame.css({ 'margin-left': '' }); this.frame.addClass('annotator-collapsed'); if ($main.hasClass('single')) { $main.removeClass("single"); this.toolbar.find('[name=sidebar-toggle]').removeClass('h-icon-chevron-right').addClass('h-icon-chevron-left'); this.setVisibleHighlights(false); } }; return { constructor: EpubAnnotationSidebar, } }; // This is the Epub.js plugin. Annotations are updated on location change. EPUBJS.reader.plugins.HypothesisController = function (Book) { var reader = this; var $main = $("#main"); var updateAnnotations = function () { var annotator = Book.renderer.render.window.annotator; if (annotator && annotator.constructor.$) { var annotations = getVisibleAnnotations(annotator.constructor.$); annotator.showAnnotations(annotations) } }; var getVisibleAnnotations = function ($) { var width = Book.renderer.render.iframe.clientWidth; return $('.annotator-hl').map(function() { var $this = $(this), left = this.getBoundingClientRect().left; if (left >= 0 && left <= width) { return $this.data('annotation'); } }).get(); }; Book.on("renderer:locationChanged", updateAnnotations); return {} };
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/plugins/hypothesis.js
hypothesis.js
EPUBJS.reader.search = {}; // Search Server -- https://github.com/futurepress/epubjs-search EPUBJS.reader.search.SERVER = "https://pacific-cliffs-3579.herokuapp.com"; EPUBJS.reader.search.request = function(q, callback) { var fetch = $.ajax({ dataType: "json", url: EPUBJS.reader.search.SERVER + "/search?q=" + encodeURIComponent(q) }); fetch.fail(function(err) { console.error(err); }); fetch.done(function(results) { callback(results); }); }; EPUBJS.reader.plugins.SearchController = function(Book) { var reader = this; var $searchBox = $("#searchBox"), $searchResults = $("#searchResults"), $searchView = $("#searchView"), iframeDoc; var searchShown = false; var onShow = function() { query(); searchShown = true; $searchView.addClass("shown"); }; var onHide = function() { searchShown = false; $searchView.removeClass("shown"); }; var query = function() { var q = $searchBox.val(); if(q == '') { return; } $searchResults.empty(); $searchResults.append("<li><p>Searching...</p></li>"); EPUBJS.reader.search.request(q, function(data) { var results = data.results; $searchResults.empty(); if(iframeDoc) { $(iframeDoc).find('body').unhighlight(); } if(results.length == 0) { $searchResults.append("<li><p>No Results Found</p></li>"); return; } iframeDoc = $("#viewer iframe")[0].contentDocument; $(iframeDoc).find('body').highlight(q, { element: 'span' }); results.forEach(function(result) { var $li = $("<li></li>"); var $item = $("<a href='"+result.href+"' data-cfi='"+result.cfi+"'><span>"+result.title+"</span><p>"+result.highlight+"</p></a>"); $item.on("click", function(e) { var $this = $(this), cfi = $this.data("cfi"); e.preventDefault(); Book.gotoCfi(cfi+"/1:0"); Book.on("renderer:chapterDisplayed", function() { iframeDoc = $("#viewer iframe")[0].contentDocument; $(iframeDoc).find('body').highlight(q, { element: 'span' }); }) }); $li.append($item); $searchResults.append($li); }); }); }; $searchBox.on("search", function(e) { var q = $searchBox.val(); //-- SearchBox is empty or cleared if(q == '') { $searchResults.empty(); if(reader.SidebarController.getActivePanel() == "Search") { reader.SidebarController.changePanelTo("Toc"); } $(iframeDoc).find('body').unhighlight(); iframeDoc = false; return; } reader.SidebarController.changePanelTo("Search"); e.preventDefault(); }); return { "show" : onShow, "hide" : onHide }; };
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/plugins/search.js
search.js
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){"use strict";var d=a("./utils"),e=a("./support"),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";c.encode=function(a){for(var b,c,e,g,h,i,j,k=[],l=0,m=a.length,n=m,o="string"!==d.getTypeOf(a);l<a.length;)n=m-l,o?(b=a[l++],c=l<m?a[l++]:0,e=l<m?a[l++]:0):(b=a.charCodeAt(l++),c=l<m?a.charCodeAt(l++):0,e=l<m?a.charCodeAt(l++):0),g=b>>2,h=(3&b)<<4|c>>4,i=n>1?(15&c)<<2|e>>6:64,j=n>2?63&e:64,k.push(f.charAt(g)+f.charAt(h)+f.charAt(i)+f.charAt(j));return k.join("")},c.decode=function(a){var b,c,d,g,h,i,j,k=0,l=0,m="data:";if(a.substr(0,m.length)===m)throw new Error("Invalid base64 input, it looks like a data url.");a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");var n=3*a.length/4;if(a.charAt(a.length-1)===f.charAt(64)&&n--,a.charAt(a.length-2)===f.charAt(64)&&n--,n%1!==0)throw new Error("Invalid base64 input, bad content length.");var o;for(o=e.uint8array?new Uint8Array(0|n):new Array(0|n);k<a.length;)g=f.indexOf(a.charAt(k++)),h=f.indexOf(a.charAt(k++)),i=f.indexOf(a.charAt(k++)),j=f.indexOf(a.charAt(k++)),b=g<<2|h>>4,c=(15&h)<<4|i>>2,d=(3&i)<<6|j,o[l++]=b,64!==i&&(o[l++]=c),64!==j&&(o[l++]=d);return o}},{"./support":30,"./utils":32}],2:[function(a,b,c){"use strict";function d(a,b,c,d,e){this.compressedSize=a,this.uncompressedSize=b,this.crc32=c,this.compression=d,this.compressedContent=e}var e=a("./external"),f=a("./stream/DataWorker"),g=a("./stream/DataLengthProbe"),h=a("./stream/Crc32Probe"),g=a("./stream/DataLengthProbe");d.prototype={getContentWorker:function(){var a=new f(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new g("data_length")),b=this;return a.on("end",function(){if(this.streamInfo.data_length!==b.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new f(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(a,b,c){return a.pipe(new h).pipe(new g("uncompressedSize")).pipe(b.compressWorker(c)).pipe(new g("compressedSize")).withStreamInfo("compression",b)},b.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(a,b,c){"use strict";var d=a("./stream/GenericWorker");c.STORE={magic:"\0\0",compressWorker:function(a){return new d("STORE compression")},uncompressWorker:function(){return new d("STORE decompression")}},c.DEFLATE=a("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;c<256;c++){a=c;for(var d=0;d<8;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=h,f=d+c;a^=-1;for(var g=d;g<f;g++)a=a>>>8^e[255&(a^b[g])];return a^-1}function f(a,b,c,d){var e=h,f=d+c;a^=-1;for(var g=d;g<f;g++)a=a>>>8^e[255&(a^b.charCodeAt(g))];return a^-1}var g=a("./utils"),h=d();b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var c="string"!==g.getTypeOf(a);return c?e(0|b,a,a.length,0):f(0|b,a,a.length,0)}},{"./utils":32}],5:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!0,c.date=null,c.compression=null,c.compressionOptions=null,c.comment=null,c.unixPermissions=null,c.dosPermissions=null},{}],6:[function(a,b,c){"use strict";var d=null;d="undefined"!=typeof Promise?Promise:a("lie"),b.exports={Promise:d}},{lie:58}],7:[function(a,b,c){"use strict";function d(a,b){h.call(this,"FlateWorker/"+a),this._pako=null,this._pakoAction=a,this._pakoOptions=b,this.meta={}}var e="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,f=a("pako"),g=a("./utils"),h=a("./stream/GenericWorker"),i=e?"uint8array":"array";c.magic="\b\0",g.inherits(d,h),d.prototype.processChunk=function(a){this.meta=a.meta,null===this._pako&&this._createPako(),this._pako.push(g.transformTo(i,a.data),!1)},d.prototype.flush=function(){h.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},d.prototype.cleanUp=function(){h.prototype.cleanUp.call(this),this._pako=null},d.prototype._createPako=function(){this._pako=new f[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var a=this;this._pako.onData=function(b){a.push({data:b,meta:a.meta})}},c.compressWorker=function(a){return new d("Deflate",a)},c.uncompressWorker=function(){return new d("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:59}],8:[function(a,b,c){"use strict";function d(a,b,c,d){f.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=b,this.zipPlatform=c,this.encodeFileName=d,this.streamFiles=a,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}var e=a("../utils"),f=a("../stream/GenericWorker"),g=a("../utf8"),h=a("../crc32"),i=a("../signature"),j=function(a,b){var c,d="";for(c=0;c<b;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},k=function(a,b){var c=a;return a||(c=b?16893:33204),(65535&c)<<16},l=function(a,b){return 63&(a||0)},m=function(a,b,c,d,f,m){var n,o,p=a.file,q=a.compression,r=m!==g.utf8encode,s=e.transformTo("string",m(p.name)),t=e.transformTo("string",g.utf8encode(p.name)),u=p.comment,v=e.transformTo("string",m(u)),w=e.transformTo("string",g.utf8encode(u)),x=t.length!==p.name.length,y=w.length!==u.length,z="",A="",B="",C=p.dir,D=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};b&&!c||(E.crc32=a.crc32,E.compressedSize=a.compressedSize,E.uncompressedSize=a.uncompressedSize);var F=0;b&&(F|=8),r||!x&&!y||(F|=2048);var G=0,H=0;C&&(G|=16),"UNIX"===f?(H=798,G|=k(p.unixPermissions,C)):(H=20,G|=l(p.dosPermissions,C)),n=D.getUTCHours(),n<<=6,n|=D.getUTCMinutes(),n<<=5,n|=D.getUTCSeconds()/2,o=D.getUTCFullYear()-1980,o<<=4,o|=D.getUTCMonth()+1,o<<=5,o|=D.getUTCDate(),x&&(A=j(1,1)+j(h(s),4)+t,z+="up"+j(A.length,2)+A),y&&(B=j(1,1)+j(h(v),4)+w,z+="uc"+j(B.length,2)+B);var I="";I+="\n\0",I+=j(F,2),I+=q.magic,I+=j(n,2),I+=j(o,2),I+=j(E.crc32,4),I+=j(E.compressedSize,4),I+=j(E.uncompressedSize,4),I+=j(s.length,2),I+=j(z.length,2);var J=i.LOCAL_FILE_HEADER+I+s+z,K=i.CENTRAL_FILE_HEADER+j(H,2)+I+j(v.length,2)+"\0\0\0\0"+j(G,4)+j(d,4)+s+z+v;return{fileRecord:J,dirRecord:K}},n=function(a,b,c,d,f){var g="",h=e.transformTo("string",f(d));return g=i.CENTRAL_DIRECTORY_END+"\0\0\0\0"+j(a,2)+j(a,2)+j(b,4)+j(c,4)+j(h.length,2)+h},o=function(a){var b="";return b=i.DATA_DESCRIPTOR+j(a.crc32,4)+j(a.compressedSize,4)+j(a.uncompressedSize,4)};e.inherits(d,f),d.prototype.push=function(a){var b=a.meta.percent||0,c=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(a):(this.bytesWritten+=a.data.length,f.prototype.push.call(this,{data:a.data,meta:{currentFile:this.currentFile,percent:c?(b+100*(c-d-1))/c:100}}))},d.prototype.openedSource=function(a){this.currentSourceOffset=this.bytesWritten,this.currentFile=a.file.name;var b=this.streamFiles&&!a.file.dir;if(b){var c=m(a,b,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:c.fileRecord,meta:{percent:0}})}else this.accumulate=!0},d.prototype.closedSource=function(a){this.accumulate=!1;var b=this.streamFiles&&!a.file.dir,c=m(a,b,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(c.dirRecord),b)this.push({data:o(a),meta:{percent:100}});else for(this.push({data:c.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},d.prototype.flush=function(){for(var a=this.bytesWritten,b=0;b<this.dirRecords.length;b++)this.push({data:this.dirRecords[b],meta:{percent:100}});var c=this.bytesWritten-a,d=n(this.dirRecords.length,c,a,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},d.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},d.prototype.registerPrevious=function(a){this._sources.push(a);var b=this;return a.on("data",function(a){b.processChunk(a)}),a.on("end",function(){b.closedSource(b.previous.streamInfo),b._sources.length?b.prepareNextSource():b.end()}),a.on("error",function(a){b.error(a)}),this},d.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},d.prototype.error=function(a){var b=this._sources;if(!f.prototype.error.call(this,a))return!1;for(var c=0;c<b.length;c++)try{b[c].error(a)}catch(a){}return!0},d.prototype.lock=function(){f.prototype.lock.call(this);for(var a=this._sources,b=0;b<a.length;b++)a[b].lock()},b.exports=d},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(a,b,c){"use strict";var d=a("../compressions"),e=a("./ZipFileWorker"),f=function(a,b){var c=a||b,e=d[c];if(!e)throw new Error(c+" is not a valid compression method !");return e};c.generateWorker=function(a,b,c){var d=new e(b.streamFiles,c,b.platform,b.encodeFileName),g=0;try{a.forEach(function(a,c){g++;var e=f(c.options.compression,b.compression),h=c.options.compressionOptions||b.compressionOptions||{},i=c.dir,j=c.date;c._compressWorker(e,h).withStreamInfo("file",{name:a,dir:i,date:j,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(d)}),d.entriesCount=g}catch(h){d.error(h)}return d}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(a,b,c){"use strict";function d(){if(!(this instanceof d))return new d;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files={},this.comment=null,this.root="",this.clone=function(){var a=new d;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a}}d.prototype=a("./object"),d.prototype.loadAsync=a("./load"),d.support=a("./support"),d.defaults=a("./defaults"),d.version="3.1.5",d.loadAsync=function(a,b){return(new d).loadAsync(a,b)},d.external=a("./external"),b.exports=d},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(a,b,c){"use strict";function d(a){return new f.Promise(function(b,c){var d=a.decompressed.getContentWorker().pipe(new i);d.on("error",function(a){c(a)}).on("end",function(){d.streamInfo.crc32!==a.decompressed.crc32?c(new Error("Corrupted zip : CRC32 mismatch")):b()}).resume()})}var e=a("./utils"),f=a("./external"),g=a("./utf8"),e=a("./utils"),h=a("./zipEntries"),i=a("./stream/Crc32Probe"),j=a("./nodejsUtils");b.exports=function(a,b){var c=this;return b=e.extend(b||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:g.utf8decode}),j.isNode&&j.isStream(a)?f.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",a,!0,b.optimizedBinaryString,b.base64).then(function(a){var c=new h(b);return c.load(a),c}).then(function(a){var c=[f.Promise.resolve(a)],e=a.files;if(b.checkCRC32)for(var g=0;g<e.length;g++)c.push(d(e[g]));return f.Promise.all(c)}).then(function(a){for(var d=a.shift(),e=d.files,f=0;f<e.length;f++){var g=e[f];c.file(g.fileNameStr,g.decompressed,{binary:!0,optimizedBinaryString:!0,date:g.date,dir:g.dir,comment:g.fileCommentStr.length?g.fileCommentStr:null,unixPermissions:g.unixPermissions,dosPermissions:g.dosPermissions,createFolders:b.createFolders})}return d.zipComment.length&&(c.comment=d.zipComment),c})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(a,b,c){"use strict";function d(a,b){f.call(this,"Nodejs stream input adapter for "+a),this._upstreamEnded=!1,this._bindStream(b)}var e=a("../utils"),f=a("../stream/GenericWorker");e.inherits(d,f),d.prototype._bindStream=function(a){var b=this;this._stream=a,a.pause(),a.on("data",function(a){b.push({data:a,meta:{percent:0}})}).on("error",function(a){b.isPaused?this.generatedError=a:b.error(a)}).on("end",function(){b.isPaused?b._upstreamEnded=!0:b.end()})},d.prototype.pause=function(){return!!f.prototype.pause.call(this)&&(this._stream.pause(),!0)},d.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},b.exports=d},{"../stream/GenericWorker":28,"../utils":32}],13:[function(a,b,c){"use strict";function d(a,b,c){e.call(this,b),this._helper=a;var d=this;a.on("data",function(a,b){d.push(a)||d._helper.pause(),c&&c(b)}).on("error",function(a){d.emit("error",a)}).on("end",function(){d.push(null)})}var e=a("readable-stream").Readable,f=a("../utils");f.inherits(d,e),d.prototype._read=function(){this._helper.resume()},b.exports=d},{"../utils":32,"readable-stream":16}],14:[function(a,b,c){"use strict";b.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(a,b){return new Buffer(a,b)},allocBuffer:function(a){return Buffer.alloc?Buffer.alloc(a):new Buffer(a)},isBuffer:function(a){return Buffer.isBuffer(a)},isStream:function(a){return a&&"function"==typeof a.on&&"function"==typeof a.pause&&"function"==typeof a.resume}}},{}],15:[function(a,b,c){"use strict";function d(a){return"[object RegExp]"===Object.prototype.toString.call(a)}var e=a("./utf8"),f=a("./utils"),g=a("./stream/GenericWorker"),h=a("./stream/StreamHelper"),i=a("./defaults"),j=a("./compressedObject"),k=a("./zipObject"),l=a("./generate"),m=a("./nodejsUtils"),n=a("./nodejs/NodejsStreamInputAdapter"),o=function(a,b,c){var d,e=f.getTypeOf(b),h=f.extend(c||{},i);h.date=h.date||new Date,null!==h.compression&&(h.compression=h.compression.toUpperCase()),"string"==typeof h.unixPermissions&&(h.unixPermissions=parseInt(h.unixPermissions,8)),h.unixPermissions&&16384&h.unixPermissions&&(h.dir=!0),h.dosPermissions&&16&h.dosPermissions&&(h.dir=!0),h.dir&&(a=q(a)),h.createFolders&&(d=p(a))&&r.call(this,d,!0);var l="string"===e&&h.binary===!1&&h.base64===!1;c&&"undefined"!=typeof c.binary||(h.binary=!l);var o=b instanceof j&&0===b.uncompressedSize;(o||h.dir||!b||0===b.length)&&(h.base64=!1,h.binary=!0,b="",h.compression="STORE",e="string");var s=null;s=b instanceof j||b instanceof g?b:m.isNode&&m.isStream(b)?new n(a,b):f.prepareContent(a,b,h.binary,h.optimizedBinaryString,h.base64);var t=new k(a,s,h);this.files[a]=t},p=function(a){"/"===a.slice(-1)&&(a=a.substring(0,a.length-1));var b=a.lastIndexOf("/");return b>0?a.substring(0,b):""},q=function(a){return"/"!==a.slice(-1)&&(a+="/"),a},r=function(a,b){return b="undefined"!=typeof b?b:i.createFolders,a=q(a),this.files[a]||o.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},s={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(a){var b,c,d;for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],c=b.slice(this.root.length,b.length),c&&b.slice(0,this.root.length)===this.root&&a(c,d))},filter:function(a){var b=[];return this.forEach(function(c,d){a(c,d)&&b.push(d)}),b},file:function(a,b,c){if(1===arguments.length){if(d(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}var f=this.files[this.root+a];return f&&!f.dir?f:null}return a=this.root+a,o.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=r.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!==a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d<c.length;d++)delete this.files[c[d].name];return this},generate:function(a){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(a){var b,c={};try{if(c=f.extend(a||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:e.utf8encode}),c.type=c.type.toLowerCase(),c.compression=c.compression.toUpperCase(),"binarystring"===c.type&&(c.type="string"),!c.type)throw new Error("No output type specified.");f.checkSupport(c.type),"darwin"!==c.platform&&"freebsd"!==c.platform&&"linux"!==c.platform&&"sunos"!==c.platform||(c.platform="UNIX"),"win32"===c.platform&&(c.platform="DOS");var d=c.comment||this.comment||"";b=l.generateWorker(this,c,d)}catch(i){b=new g("error"),b.error(i)}return new h(b,c.type||"string",c.mimeType)},generateAsync:function(a,b){return this.generateInternalStream(a).accumulate(b)},generateNodeStream:function(a,b){return a=a||{},a.type||(a.type="nodebuffer"),this.generateInternalStream(a).toNodejsStream(b)}};b.exports=s},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(a,b,c){b.exports=a("stream")},{stream:void 0}],17:[function(a,b,c){"use strict";function d(a){e.call(this,a);for(var b=0;b<this.data.length;b++)a[b]=255&a[b]}var e=a("./DataReader"),f=a("../utils");f.inherits(d,e),d.prototype.byteAt=function(a){return this.data[this.zero+a]},d.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f-this.zero;return-1},d.prototype.readAndCheckSignature=function(a){var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.readData(4);return b===f[0]&&c===f[1]&&d===f[2]&&e===f[3]},d.prototype.readData=function(a){if(this.checkOffset(a),0===a)return[];var b=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./DataReader":18}],18:[function(a,b,c){"use strict";function d(a){this.data=a,this.length=a.length,this.index=0,this.zero=0}var e=a("../utils");d.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.length<this.zero+a||a<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(a){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return e.transformTo("string",this.readData(a))},readData:function(a){},lastIndexOfSignature:function(a){},readAndCheckSignature:function(a){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},b.exports=d},{"../utils":32}],19:[function(a,b,c){"use strict";function d(a){e.call(this,a)}var e=a("./Uint8ArrayReader"),f=a("../utils");f.inherits(d,e),d.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(a,b,c){"use strict";function d(a){e.call(this,a)}var e=a("./DataReader"),f=a("../utils");f.inherits(d,e),d.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},d.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},d.prototype.readAndCheckSignature=function(a){var b=this.readData(4);return a===b},d.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./DataReader":18}],21:[function(a,b,c){"use strict";function d(a){e.call(this,a)}var e=a("./ArrayReader"),f=a("../utils");f.inherits(d,e),d.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,b},b.exports=d},{"../utils":32,"./ArrayReader":17}],22:[function(a,b,c){"use strict";var d=a("../utils"),e=a("../support"),f=a("./ArrayReader"),g=a("./StringReader"),h=a("./NodeBufferReader"),i=a("./Uint8ArrayReader");b.exports=function(a){var b=d.getTypeOf(a);return d.checkSupport(b),"string"!==b||e.uint8array?"nodebuffer"===b?new h(a):e.uint8array?new i(d.transformTo("uint8array",a)):new f(d.transformTo("array",a)):new g(a)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(a,b,c){"use strict";c.LOCAL_FILE_HEADER="PK",c.CENTRAL_FILE_HEADER="PK",c.CENTRAL_DIRECTORY_END="PK",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",c.ZIP64_CENTRAL_DIRECTORY_END="PK",c.DATA_DESCRIPTOR="PK\b"},{}],24:[function(a,b,c){"use strict";function d(a){e.call(this,"ConvertWorker to "+a),this.destType=a}var e=a("./GenericWorker"),f=a("../utils");f.inherits(d,e),d.prototype.processChunk=function(a){this.push({data:f.transformTo(this.destType,a.data),meta:a.meta})},b.exports=d},{"../utils":32,"./GenericWorker":28}],25:[function(a,b,c){"use strict";function d(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}var e=a("./GenericWorker"),f=a("../crc32"),g=a("../utils");g.inherits(d,e),d.prototype.processChunk=function(a){this.streamInfo.crc32=f(a.data,this.streamInfo.crc32||0),this.push(a)},b.exports=d},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(a,b,c){"use strict";function d(a){f.call(this,"DataLengthProbe for "+a),this.propName=a,this.withStreamInfo(a,0)}var e=a("../utils"),f=a("./GenericWorker");e.inherits(d,f),d.prototype.processChunk=function(a){if(a){var b=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=b+a.data.length}f.prototype.processChunk.call(this,a)},b.exports=d},{"../utils":32,"./GenericWorker":28}],27:[function(a,b,c){"use strict";function d(a){f.call(this,"DataWorker");var b=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,a.then(function(a){b.dataIsReady=!0,b.data=a,b.max=a&&a.length||0,b.type=e.getTypeOf(a),b.isPaused||b._tickAndRepeat()},function(a){b.error(a)})}var e=a("../utils"),f=a("./GenericWorker"),g=16384;e.inherits(d,f),d.prototype.cleanUp=function(){f.prototype.cleanUp.call(this),this.data=null},d.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},d.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},d.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var a=g,b=null,c=Math.min(this.max,this.index+a);if(this.index>=this.max)return this.end();switch(this.type){case"string":b=this.data.substring(this.index,c);break;case"uint8array":b=this.data.subarray(this.index,c);break;case"array":case"nodebuffer":b=this.data.slice(this.index,c)}return this.index=c,this.push({data:b,meta:{percent:this.max?this.index/this.max*100:0}})},b.exports=d},{"../utils":32,"./GenericWorker":28}],28:[function(a,b,c){"use strict";function d(a){this.name=a||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}d.prototype={push:function(a){this.emit("data",a)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(a){this.emit("error",a)}return!0},error:function(a){return!this.isFinished&&(this.isPaused?this.generatedError=a:(this.isFinished=!0,this.emit("error",a),this.previous&&this.previous.error(a),this.cleanUp()),!0)},on:function(a,b){return this._listeners[a].push(b),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(a,b){if(this._listeners[a])for(var c=0;c<this._listeners[a].length;c++)this._listeners[a][c].call(this,b)},pipe:function(a){return a.registerPrevious(this)},registerPrevious:function(a){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=a.streamInfo,this.mergeStreamInfo(),this.previous=a;var b=this;return a.on("data",function(a){b.processChunk(a)}),a.on("end",function(){b.end()}),a.on("error",function(a){b.error(a)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;this.isPaused=!1;var a=!1;return this.generatedError&&(this.error(this.generatedError),a=!0),this.previous&&this.previous.resume(),!a},flush:function(){},processChunk:function(a){this.push(a)},withStreamInfo:function(a,b){return this.extraStreamInfo[a]=b,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var a in this.extraStreamInfo)this.extraStreamInfo.hasOwnProperty(a)&&(this.streamInfo[a]=this.extraStreamInfo[a])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var a="Worker "+this.name;return this.previous?this.previous+" -> "+a:a}},b.exports=d},{}],29:[function(a,b,c){"use strict";function d(a,b,c){switch(a){case"blob":return h.newBlob(h.transformTo("arraybuffer",b),c);case"base64":return k.encode(b);default:return h.transformTo(a,b)}}function e(a,b){var c,d=0,e=null,f=0;for(c=0;c<b.length;c++)f+=b[c].length;switch(a){case"string":return b.join("");case"array":return Array.prototype.concat.apply([],b);case"uint8array":for(e=new Uint8Array(f),c=0;c<b.length;c++)e.set(b[c],d),d+=b[c].length;return e;case"nodebuffer":return Buffer.concat(b);default:throw new Error("concat : unsupported type '"+a+"'")}}function f(a,b){return new m.Promise(function(c,f){var g=[],h=a._internalType,i=a._outputType,j=a._mimeType;a.on("data",function(a,c){g.push(a),b&&b(c)}).on("error",function(a){g=[],f(a)}).on("end",function(){try{var a=d(i,e(h,g),j);c(a)}catch(b){f(b)}g=[]}).resume()})}function g(a,b,c){var d=b;switch(b){case"blob":case"arraybuffer":d="uint8array";break;case"base64":d="string"}try{this._internalType=d,this._outputType=b,this._mimeType=c,h.checkSupport(d),this._worker=a.pipe(new i(d)),a.lock()}catch(e){this._worker=new j("error"),this._worker.error(e)}}var h=a("../utils"),i=a("./ConvertWorker"),j=a("./GenericWorker"),k=a("../base64"),l=a("../support"),m=a("../external"),n=null;if(l.nodestream)try{n=a("../nodejs/NodejsStreamOutputAdapter")}catch(o){}g.prototype={accumulate:function(a){return f(this,a)},on:function(a,b){var c=this;return"data"===a?this._worker.on(a,function(a){b.call(c,a.data,a.meta)}):this._worker.on(a,function(){h.delay(b,arguments,c)}),this},resume:function(){return h.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(a){if(h.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new n(this,{objectMode:"nodebuffer"!==this._outputType},a)}},b.exports=g},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(a,b,c){"use strict";if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,c.nodebuffer="undefined"!=typeof Buffer,c.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)c.blob=!1;else{var d=new ArrayBuffer(0);try{c.blob=0===new Blob([d],{type:"application/zip"}).size}catch(e){try{var f=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,g=new f;g.append(d),c.blob=0===g.getBlob("application/zip").size}catch(e){c.blob=!1}}}try{c.nodestream=!!a("readable-stream").Readable}catch(e){c.nodestream=!1}},{"readable-stream":16}],31:[function(a,b,c){"use strict";function d(){i.call(this,"utf-8 decode"),this.leftOver=null}function e(){i.call(this,"utf-8 encode")}for(var f=a("./utils"),g=a("./support"),h=a("./nodejsUtils"),i=a("./stream/GenericWorker"),j=new Array(256),k=0;k<256;k++)j[k]=k>=252?6:k>=248?5:k>=240?4:k>=224?3:k>=192?2:1;j[254]=j[254]=1;var l=function(a){var b,c,d,e,f,h=a.length,i=0;for(e=0;e<h;e++)c=a.charCodeAt(e),55296===(64512&c)&&e+1<h&&(d=a.charCodeAt(e+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),e++)),i+=c<128?1:c<2048?2:c<65536?3:4;for(b=g.uint8array?new Uint8Array(i):new Array(i),f=0,e=0;f<i;e++)c=a.charCodeAt(e),55296===(64512&c)&&e+1<h&&(d=a.charCodeAt(e+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),e++)),c<128?b[f++]=c:c<2048?(b[f++]=192|c>>>6,b[f++]=128|63&c):c<65536?(b[f++]=224|c>>>12,b[f++]=128|c>>>6&63,b[f++]=128|63&c):(b[f++]=240|c>>>18,b[f++]=128|c>>>12&63,b[f++]=128|c>>>6&63,b[f++]=128|63&c);return b},m=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return c<0?b:0===c?b:c+j[a[c]]>b?c:b},n=function(a){var b,c,d,e,g=a.length,h=new Array(2*g);for(c=0,b=0;b<g;)if(d=a[b++],d<128)h[c++]=d;else if(e=j[d],e>4)h[c++]=65533,b+=e-1;else{for(d&=2===e?31:3===e?15:7;e>1&&b<g;)d=d<<6|63&a[b++],e--;e>1?h[c++]=65533:d<65536?h[c++]=d:(d-=65536,h[c++]=55296|d>>10&1023,h[c++]=56320|1023&d)}return h.length!==c&&(h.subarray?h=h.subarray(0,c):h.length=c),f.applyFromCharCode(h)};c.utf8encode=function(a){return g.nodebuffer?h.newBufferFrom(a,"utf-8"):l(a)},c.utf8decode=function(a){return g.nodebuffer?f.transformTo("nodebuffer",a).toString("utf-8"):(a=f.transformTo(g.uint8array?"uint8array":"array",a),n(a))},f.inherits(d,i),d.prototype.processChunk=function(a){var b=f.transformTo(g.uint8array?"uint8array":"array",a.data);if(this.leftOver&&this.leftOver.length){if(g.uint8array){var d=b;b=new Uint8Array(d.length+this.leftOver.length),b.set(this.leftOver,0),b.set(d,this.leftOver.length)}else b=this.leftOver.concat(b);this.leftOver=null}var e=m(b),h=b;e!==b.length&&(g.uint8array?(h=b.subarray(0,e),this.leftOver=b.subarray(e,b.length)):(h=b.slice(0,e),this.leftOver=b.slice(e,b.length))),this.push({data:c.utf8decode(h),meta:a.meta})},d.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:c.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},c.Utf8DecodeWorker=d,f.inherits(e,i),e.prototype.processChunk=function(a){this.push({data:c.utf8encode(a.data),meta:a.meta})},c.Utf8EncodeWorker=e},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(a,b,c){"use strict";function d(a){var b=null;return b=i.uint8array?new Uint8Array(a.length):new Array(a.length),f(a,b)}function e(a){return a}function f(a,b){for(var c=0;c<a.length;++c)b[c]=255&a.charCodeAt(c);return b}function g(a){var b=65536,d=c.getTypeOf(a),e=!0;if("uint8array"===d?e=n.applyCanBeUsed.uint8array:"nodebuffer"===d&&(e=n.applyCanBeUsed.nodebuffer),e)for(;b>1;)try{return n.stringifyByChunk(a,d,b)}catch(f){b=Math.floor(b/2)}return n.stringifyByChar(a)}function h(a,b){for(var c=0;c<a.length;c++)b[c]=a[c]; return b}var i=a("./support"),j=a("./base64"),k=a("./nodejsUtils"),l=a("core-js/library/fn/set-immediate"),m=a("./external");c.newBlob=function(a,b){c.checkSupport("blob");try{return new Blob([a],{type:b})}catch(d){try{var e=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,f=new e;return f.append(a),f.getBlob(b)}catch(d){throw new Error("Bug : can't construct the Blob.")}}};var n={stringifyByChunk:function(a,b,c){var d=[],e=0,f=a.length;if(f<=c)return String.fromCharCode.apply(null,a);for(;e<f;)"array"===b||"nodebuffer"===b?d.push(String.fromCharCode.apply(null,a.slice(e,Math.min(e+c,f)))):d.push(String.fromCharCode.apply(null,a.subarray(e,Math.min(e+c,f)))),e+=c;return d.join("")},stringifyByChar:function(a){for(var b="",c=0;c<a.length;c++)b+=String.fromCharCode(a[c]);return b},applyCanBeUsed:{uint8array:function(){try{return i.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(a){return!1}}(),nodebuffer:function(){try{return i.nodebuffer&&1===String.fromCharCode.apply(null,k.allocBuffer(1)).length}catch(a){return!1}}()}};c.applyFromCharCode=g;var o={};o.string={string:e,array:function(a){return f(a,new Array(a.length))},arraybuffer:function(a){return o.string.uint8array(a).buffer},uint8array:function(a){return f(a,new Uint8Array(a.length))},nodebuffer:function(a){return f(a,k.allocBuffer(a.length))}},o.array={string:g,array:e,arraybuffer:function(a){return new Uint8Array(a).buffer},uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return k.newBufferFrom(a)}},o.arraybuffer={string:function(a){return g(new Uint8Array(a))},array:function(a){return h(new Uint8Array(a),new Array(a.byteLength))},arraybuffer:e,uint8array:function(a){return new Uint8Array(a)},nodebuffer:function(a){return k.newBufferFrom(new Uint8Array(a))}},o.uint8array={string:g,array:function(a){return h(a,new Array(a.length))},arraybuffer:function(a){return a.buffer},uint8array:e,nodebuffer:function(a){return k.newBufferFrom(a)}},o.nodebuffer={string:g,array:function(a){return h(a,new Array(a.length))},arraybuffer:function(a){return o.nodebuffer.uint8array(a).buffer},uint8array:function(a){return h(a,new Uint8Array(a.length))},nodebuffer:e},c.transformTo=function(a,b){if(b||(b=""),!a)return b;c.checkSupport(a);var d=c.getTypeOf(b),e=o[d][a](b);return e},c.getTypeOf=function(a){return"string"==typeof a?"string":"[object Array]"===Object.prototype.toString.call(a)?"array":i.nodebuffer&&k.isBuffer(a)?"nodebuffer":i.uint8array&&a instanceof Uint8Array?"uint8array":i.arraybuffer&&a instanceof ArrayBuffer?"arraybuffer":void 0},c.checkSupport=function(a){var b=i[a.toLowerCase()];if(!b)throw new Error(a+" is not supported by this platform")},c.MAX_VALUE_16BITS=65535,c.MAX_VALUE_32BITS=-1,c.pretty=function(a){var b,c,d="";for(c=0;c<(a||"").length;c++)b=a.charCodeAt(c),d+="\\x"+(b<16?"0":"")+b.toString(16).toUpperCase();return d},c.delay=function(a,b,c){l(function(){a.apply(c||null,b||[])})},c.inherits=function(a,b){var c=function(){};c.prototype=b.prototype,a.prototype=new c},c.extend=function(){var a,b,c={};for(a=0;a<arguments.length;a++)for(b in arguments[a])arguments[a].hasOwnProperty(b)&&"undefined"==typeof c[b]&&(c[b]=arguments[a][b]);return c},c.prepareContent=function(a,b,e,f,g){var h=m.Promise.resolve(b).then(function(a){var b=i.blob&&(a instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(a))!==-1);return b&&"undefined"!=typeof FileReader?new m.Promise(function(b,c){var d=new FileReader;d.onload=function(a){b(a.target.result)},d.onerror=function(a){c(a.target.error)},d.readAsArrayBuffer(a)}):a});return h.then(function(b){var h=c.getTypeOf(b);return h?("arraybuffer"===h?b=c.transformTo("uint8array",b):"string"===h&&(g?b=j.decode(b):e&&f!==!0&&(b=d(b))),b):m.Promise.reject(new Error("Can't read the data of '"+a+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"core-js/library/fn/set-immediate":36}],33:[function(a,b,c){"use strict";function d(a){this.files=[],this.loadOptions=a}var e=a("./reader/readerFor"),f=a("./utils"),g=a("./signature"),h=a("./zipEntry"),i=(a("./utf8"),a("./support"));d.prototype={checkSignature:function(a){if(!this.reader.readAndCheckSignature(a)){this.reader.index-=4;var b=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+f.pretty(b)+", expected "+f.pretty(a)+")")}},isSignature:function(a,b){var c=this.reader.index;this.reader.setIndex(a);var d=this.reader.readString(4),e=d===b;return this.reader.setIndex(c),e},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var a=this.reader.readData(this.zipCommentLength),b=i.uint8array?"uint8array":"array",c=f.transformTo(b,a);this.zipComment=this.loadOptions.decodeFileName(c)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;e<d;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readData(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a<this.files.length;a++)b=this.files[a],this.reader.setIndex(b.localHeaderOffset),this.checkSignature(g.LOCAL_FILE_HEADER),b.readLocalPart(this.reader),b.handleUTF8(),b.processAttributes()},readCentralDir:function(){var a;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(g.CENTRAL_FILE_HEADER);)a=new h({zip64:this.zip64},this.loadOptions),a.readCentralPart(this.reader),this.files.push(a);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var a=this.reader.lastIndexOfSignature(g.CENTRAL_DIRECTORY_END);if(a<0){var b=!this.isSignature(0,g.LOCAL_FILE_HEADER);throw b?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(a);var c=a;if(this.checkSignature(g.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===f.MAX_VALUE_16BITS||this.diskWithCentralDirStart===f.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===f.MAX_VALUE_16BITS||this.centralDirRecords===f.MAX_VALUE_16BITS||this.centralDirSize===f.MAX_VALUE_32BITS||this.centralDirOffset===f.MAX_VALUE_32BITS){if(this.zip64=!0,a=this.reader.lastIndexOfSignature(g.ZIP64_CENTRAL_DIRECTORY_LOCATOR),a<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(a),this.checkSignature(g.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,g.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(g.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(g.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var d=this.centralDirOffset+this.centralDirSize;this.zip64&&(d+=20,d+=12+this.zip64EndOfCentralSize);var e=c-d;if(e>0)this.isSignature(c,g.CENTRAL_FILE_HEADER)||(this.reader.zero=e);else if(e<0)throw new Error("Corrupted zip: missing "+Math.abs(e)+" bytes.")},prepareReader:function(a){this.reader=e(a)},load:function(a){this.prepareReader(a),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},b.exports=d},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(a,b,c){"use strict";function d(a,b){this.options=a,this.loadOptions=b}var e=a("./reader/readerFor"),f=a("./utils"),g=a("./compressedObject"),h=a("./crc32"),i=a("./utf8"),j=a("./compressions"),k=a("./support"),l=0,m=3,n=function(a){for(var b in j)if(j.hasOwnProperty(b)&&j[b].magic===a)return j[b];return null};d.prototype={isEncrypted:function(){return 1===(1&this.bitFlag)},useUTF8:function(){return 2048===(2048&this.bitFlag)},readLocalPart:function(a){var b,c;if(a.skip(22),this.fileNameLength=a.readInt(2),c=a.readInt(2),this.fileName=a.readData(this.fileNameLength),a.skip(c),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(b=n(this.compressionMethod),null===b)throw new Error("Corrupted zip : compression "+f.pretty(this.compressionMethod)+" unknown (inner file : "+f.transformTo("string",this.fileName)+")");this.decompressed=new g(this.compressedSize,this.uncompressedSize,this.crc32,b,a.readData(this.compressedSize))},readCentralPart:function(a){this.versionMadeBy=a.readInt(2),a.skip(2),this.bitFlag=a.readInt(2),this.compressionMethod=a.readString(2),this.date=a.readDate(),this.crc32=a.readInt(4),this.compressedSize=a.readInt(4),this.uncompressedSize=a.readInt(4);var b=a.readInt(2);if(this.extraFieldsLength=a.readInt(2),this.fileCommentLength=a.readInt(2),this.diskNumberStart=a.readInt(2),this.internalFileAttributes=a.readInt(2),this.externalFileAttributes=a.readInt(4),this.localHeaderOffset=a.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");a.skip(b),this.readExtraFields(a),this.parseZIP64ExtraField(a),this.fileComment=a.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var a=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),a===l&&(this.dosPermissions=63&this.externalFileAttributes),a===m&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(a){if(this.extraFields[1]){var b=e(this.extraFields[1].value);this.uncompressedSize===f.MAX_VALUE_32BITS&&(this.uncompressedSize=b.readInt(8)),this.compressedSize===f.MAX_VALUE_32BITS&&(this.compressedSize=b.readInt(8)),this.localHeaderOffset===f.MAX_VALUE_32BITS&&(this.localHeaderOffset=b.readInt(8)),this.diskNumberStart===f.MAX_VALUE_32BITS&&(this.diskNumberStart=b.readInt(4))}},readExtraFields:function(a){var b,c,d,e=a.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});a.index<e;)b=a.readInt(2),c=a.readInt(2),d=a.readData(c),this.extraFields[b]={id:b,length:c,value:d}},handleUTF8:function(){var a=k.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=i.utf8decode(this.fileName),this.fileCommentStr=i.utf8decode(this.fileComment);else{var b=this.findExtraFieldUnicodePath();if(null!==b)this.fileNameStr=b;else{var c=f.transformTo(a,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(c)}var d=this.findExtraFieldUnicodeComment();if(null!==d)this.fileCommentStr=d;else{var e=f.transformTo(a,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(e)}}},findExtraFieldUnicodePath:function(){var a=this.extraFields[28789];if(a){var b=e(a.value);return 1!==b.readInt(1)?null:h(this.fileName)!==b.readInt(4)?null:i.utf8decode(b.readData(a.length-5))}return null},findExtraFieldUnicodeComment:function(){var a=this.extraFields[25461];if(a){var b=e(a.value);return 1!==b.readInt(1)?null:h(this.fileComment)!==b.readInt(4)?null:i.utf8decode(b.readData(a.length-5))}return null}},b.exports=d},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(a,b,c){"use strict";var d=a("./stream/StreamHelper"),e=a("./stream/DataWorker"),f=a("./utf8"),g=a("./compressedObject"),h=a("./stream/GenericWorker"),i=function(a,b,c){this.name=a,this.dir=c.dir,this.date=c.date,this.comment=c.comment,this.unixPermissions=c.unixPermissions,this.dosPermissions=c.dosPermissions,this._data=b,this._dataBinary=c.binary,this.options={compression:c.compression,compressionOptions:c.compressionOptions}};i.prototype={internalStream:function(a){var b=null,c="string";try{if(!a)throw new Error("No output type specified.");c=a.toLowerCase();var e="string"===c||"text"===c;"binarystring"!==c&&"text"!==c||(c="string"),b=this._decompressWorker();var g=!this._dataBinary;g&&!e&&(b=b.pipe(new f.Utf8EncodeWorker)),!g&&e&&(b=b.pipe(new f.Utf8DecodeWorker))}catch(i){b=new h("error"),b.error(i)}return new d(b,c,"")},async:function(a,b){return this.internalStream(a).accumulate(b)},nodeStream:function(a,b){return this.internalStream(a||"nodebuffer").toNodejsStream(b)},_compressWorker:function(a,b){if(this._data instanceof g&&this._data.compression.magic===a.magic)return this._data.getCompressedWorker();var c=this._decompressWorker();return this._dataBinary||(c=c.pipe(new f.Utf8EncodeWorker)),g.createWorkerFrom(c,a,b)},_decompressWorker:function(){return this._data instanceof g?this._data.getContentWorker():this._data instanceof h?this._data:new e(this._data)}};for(var j=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],k=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},l=0;l<j.length;l++)i.prototype[j[l]]=k;b.exports=i},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(a,b,c){a("../modules/web.immediate"),b.exports=a("../modules/_core").setImmediate},{"../modules/_core":40,"../modules/web.immediate":56}],37:[function(a,b,c){b.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},{}],38:[function(a,b,c){var d=a("./_is-object");b.exports=function(a){if(!d(a))throw TypeError(a+" is not an object!");return a}},{"./_is-object":51}],39:[function(a,b,c){var d={}.toString;b.exports=function(a){return d.call(a).slice(8,-1)}},{}],40:[function(a,b,c){var d=b.exports={version:"2.3.0"};"number"==typeof __e&&(__e=d)},{}],41:[function(a,b,c){var d=a("./_a-function");b.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},{"./_a-function":37}],42:[function(a,b,c){b.exports=!a("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":45}],43:[function(a,b,c){var d=a("./_is-object"),e=a("./_global").document,f=d(e)&&d(e.createElement);b.exports=function(a){return f?e.createElement(a):{}}},{"./_global":46,"./_is-object":51}],44:[function(a,b,c){var d=a("./_global"),e=a("./_core"),f=a("./_ctx"),g=a("./_hide"),h="prototype",i=function(a,b,c){var j,k,l,m=a&i.F,n=a&i.G,o=a&i.S,p=a&i.P,q=a&i.B,r=a&i.W,s=n?e:e[b]||(e[b]={}),t=s[h],u=n?d:o?d[b]:(d[b]||{})[h];n&&(c=b);for(j in c)k=!m&&u&&void 0!==u[j],k&&j in s||(l=k?u[j]:c[j],s[j]=n&&"function"!=typeof u[j]?c[j]:q&&k?f(l,d):r&&u[j]==l?function(a){var b=function(b,c,d){if(this instanceof a){switch(arguments.length){case 0:return new a;case 1:return new a(b);case 2:return new a(b,c)}return new a(b,c,d)}return a.apply(this,arguments)};return b[h]=a[h],b}(l):p&&"function"==typeof l?f(Function.call,l):l,p&&((s.virtual||(s.virtual={}))[j]=l,a&i.R&&t&&!t[j]&&g(t,j,l)))};i.F=1,i.G=2,i.S=4,i.P=8,i.B=16,i.W=32,i.U=64,i.R=128,b.exports=i},{"./_core":40,"./_ctx":41,"./_global":46,"./_hide":47}],45:[function(a,b,c){b.exports=function(a){try{return!!a()}catch(b){return!0}}},{}],46:[function(a,b,c){var d=b.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=d)},{}],47:[function(a,b,c){var d=a("./_object-dp"),e=a("./_property-desc");b.exports=a("./_descriptors")?function(a,b,c){return d.f(a,b,e(1,c))}:function(a,b,c){return a[b]=c,a}},{"./_descriptors":42,"./_object-dp":52,"./_property-desc":53}],48:[function(a,b,c){b.exports=a("./_global").document&&document.documentElement},{"./_global":46}],49:[function(a,b,c){b.exports=!a("./_descriptors")&&!a("./_fails")(function(){return 7!=Object.defineProperty(a("./_dom-create")("div"),"a",{get:function(){return 7}}).a})},{"./_descriptors":42,"./_dom-create":43,"./_fails":45}],50:[function(a,b,c){b.exports=function(a,b,c){var d=void 0===c;switch(b.length){case 0:return d?a():a.call(c);case 1:return d?a(b[0]):a.call(c,b[0]);case 2:return d?a(b[0],b[1]):a.call(c,b[0],b[1]);case 3:return d?a(b[0],b[1],b[2]):a.call(c,b[0],b[1],b[2]);case 4:return d?a(b[0],b[1],b[2],b[3]):a.call(c,b[0],b[1],b[2],b[3])}return a.apply(c,b)}},{}],51:[function(a,b,c){b.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},{}],52:[function(a,b,c){var d=a("./_an-object"),e=a("./_ie8-dom-define"),f=a("./_to-primitive"),g=Object.defineProperty;c.f=a("./_descriptors")?Object.defineProperty:function(a,b,c){if(d(a),b=f(b,!0),d(c),e)try{return g(a,b,c)}catch(h){}if("get"in c||"set"in c)throw TypeError("Accessors not supported!");return"value"in c&&(a[b]=c.value),a}},{"./_an-object":38,"./_descriptors":42,"./_ie8-dom-define":49,"./_to-primitive":55}],53:[function(a,b,c){b.exports=function(a,b){return{enumerable:!(1&a),configurable:!(2&a),writable:!(4&a),value:b}}},{}],54:[function(a,b,c){var d,e,f,g=a("./_ctx"),h=a("./_invoke"),i=a("./_html"),j=a("./_dom-create"),k=a("./_global"),l=k.process,m=k.setImmediate,n=k.clearImmediate,o=k.MessageChannel,p=0,q={},r="onreadystatechange",s=function(){var a=+this;if(q.hasOwnProperty(a)){var b=q[a];delete q[a],b()}},t=function(a){s.call(a.data)};m&&n||(m=function(a){for(var b=[],c=1;arguments.length>c;)b.push(arguments[c++]);return q[++p]=function(){h("function"==typeof a?a:Function(a),b)},d(p),p},n=function(a){delete q[a]},"process"==a("./_cof")(l)?d=function(a){l.nextTick(g(s,a,1))}:o?(e=new o,f=e.port2,e.port1.onmessage=t,d=g(f.postMessage,f,1)):k.addEventListener&&"function"==typeof postMessage&&!k.importScripts?(d=function(a){k.postMessage(a+"","*")},k.addEventListener("message",t,!1)):d=r in j("script")?function(a){i.appendChild(j("script"))[r]=function(){i.removeChild(this),s.call(a)}}:function(a){setTimeout(g(s,a,1),0)}),b.exports={set:m,clear:n}},{"./_cof":39,"./_ctx":41,"./_dom-create":43,"./_global":46,"./_html":48,"./_invoke":50}],55:[function(a,b,c){var d=a("./_is-object");b.exports=function(a,b){if(!d(a))return a;var c,e;if(b&&"function"==typeof(c=a.toString)&&!d(e=c.call(a)))return e;if("function"==typeof(c=a.valueOf)&&!d(e=c.call(a)))return e;if(!b&&"function"==typeof(c=a.toString)&&!d(e=c.call(a)))return e;throw TypeError("Can't convert object to primitive value")}},{"./_is-object":51}],56:[function(a,b,c){var d=a("./_export"),e=a("./_task");d(d.G+d.B,{setImmediate:e.set,clearImmediate:e.clear})},{"./_export":44,"./_task":54}],57:[function(a,b,c){(function(a){"use strict";function c(){k=!0;for(var a,b,c=l.length;c;){for(b=l,l=[],a=-1;++a<c;)b[a]();c=l.length}k=!1}function d(a){1!==l.push(a)||k||e()}var e,f=a.MutationObserver||a.WebKitMutationObserver;if(f){var g=0,h=new f(c),i=a.document.createTextNode("");h.observe(i,{characterData:!0}),e=function(){i.data=g=++g%2}}else if(a.setImmediate||"undefined"==typeof a.MessageChannel)e="document"in a&&"onreadystatechange"in a.document.createElement("script")?function(){var b=a.document.createElement("script");b.onreadystatechange=function(){c(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},a.document.documentElement.appendChild(b)}:function(){setTimeout(c,0)};else{var j=new a.MessageChannel;j.port1.onmessage=c,e=function(){j.port2.postMessage(0)}}var k,l=[];b.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],58:[function(a,b,c){"use strict";function d(){}function e(a){if("function"!=typeof a)throw new TypeError("resolver must be a function");this.state=s,this.queue=[],this.outcome=void 0,a!==d&&i(this,a)}function f(a,b,c){this.promise=a,"function"==typeof b&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),"function"==typeof c&&(this.onRejected=c,this.callRejected=this.otherCallRejected)}function g(a,b,c){o(function(){var d;try{d=b(c)}catch(e){return p.reject(a,e)}d===a?p.reject(a,new TypeError("Cannot resolve promise with itself")):p.resolve(a,d)})}function h(a){var b=a&&a.then;if(a&&("object"==typeof a||"function"==typeof a)&&"function"==typeof b)return function(){b.apply(a,arguments)}}function i(a,b){function c(b){f||(f=!0,p.reject(a,b))}function d(b){f||(f=!0,p.resolve(a,b))}function e(){b(d,c)}var f=!1,g=j(e);"error"===g.status&&c(g.value)}function j(a,b){var c={};try{c.value=a(b),c.status="success"}catch(d){c.status="error",c.value=d}return c}function k(a){return a instanceof this?a:p.resolve(new this(d),a)}function l(a){var b=new this(d);return p.reject(b,a)}function m(a){function b(a,b){function d(a){g[b]=a,++h!==e||f||(f=!0,p.resolve(j,g))}c.resolve(a).then(d,function(a){f||(f=!0,p.reject(j,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=new Array(e),h=0,i=-1,j=new this(d);++i<e;)b(a[i],i);return j}function n(a){function b(a){c.resolve(a).then(function(a){f||(f=!0,p.resolve(h,a))},function(a){f||(f=!0,p.reject(h,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=-1,h=new this(d);++g<e;)b(a[g]);return h}var o=a("immediate"),p={},q=["REJECTED"],r=["FULFILLED"],s=["PENDING"];b.exports=e,e.prototype["catch"]=function(a){return this.then(null,a)},e.prototype.then=function(a,b){if("function"!=typeof a&&this.state===r||"function"!=typeof b&&this.state===q)return this;var c=new this.constructor(d);if(this.state!==s){var e=this.state===r?a:b;g(c,e,this.outcome)}else this.queue.push(new f(c,a,b));return c},f.prototype.callFulfilled=function(a){p.resolve(this.promise,a)},f.prototype.otherCallFulfilled=function(a){g(this.promise,this.onFulfilled,a)},f.prototype.callRejected=function(a){p.reject(this.promise,a)},f.prototype.otherCallRejected=function(a){g(this.promise,this.onRejected,a)},p.resolve=function(a,b){var c=j(h,b);if("error"===c.status)return p.reject(a,c.value);var d=c.value;if(d)i(a,d);else{a.state=r,a.outcome=b;for(var e=-1,f=a.queue.length;++e<f;)a.queue[e].callFulfilled(b)}return a},p.reject=function(a,b){a.state=q,a.outcome=b;for(var c=-1,d=a.queue.length;++c<d;)a.queue[c].callRejected(b);return a},e.resolve=k,e.reject=l,e.all=m,e.race=n},{immediate:57}],59:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":60,"./lib/inflate":61,"./lib/utils/common":62,"./lib/zlib/constants":65}],60:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);if(b.header&&h.deflateSetHeader(this.strm,b.header),b.dictionary){var e;if(e="string"==typeof b.dictionary?j.string2buf(b.dictionary):"[object ArrayBuffer]"===m.call(b.dictionary)?new Uint8Array(b.dictionary):b.dictionary,c=h.deflateSetDictionary(this.strm,e),c!==p)throw new Error(k[c]);this._dict_set=!0}}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg||k[c.err];return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d!==r||(this.onEnd(p),e.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":62,"./utils/strings":63,"./zlib/deflate":67,"./zlib/messages":72,"./zlib/zstream":74}],61:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg||k[c.err];return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l,m=this.strm,o=this.options.chunkSize,p=this.options.dictionary,q=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?m.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?m.input=new Uint8Array(a):m.input=a,m.next_in=0,m.avail_in=m.input.length;do{if(0===m.avail_out&&(m.output=new h.Buf8(o),m.next_out=0,m.avail_out=o),c=g.inflate(m,j.Z_NO_FLUSH),c===j.Z_NEED_DICT&&p&&(l="string"==typeof p?i.string2buf(p):"[object ArrayBuffer]"===n.call(p)?new Uint8Array(p):p,c=g.inflateSetDictionary(this.strm,l)),c===j.Z_BUF_ERROR&&q===!0&&(c=j.Z_OK,q=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;m.next_out&&(0!==m.avail_out&&c!==j.Z_STREAM_END&&(0!==m.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(m.output,m.next_out),f=m.next_out-e,k=i.buf2string(m.output,e),m.next_out=f,m.avail_out=o-f,f&&h.arraySet(m.output,m.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(m.output,m.next_out)))),0===m.avail_in&&0===m.avail_out&&(q=!0)}while((m.avail_in>0||0===m.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d!==j.Z_SYNC_FLUSH||(this.onEnd(j.Z_OK),m.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":62,"./utils/strings":63,"./zlib/constants":65,"./zlib/gzheader":68,"./zlib/inflate":70,"./zlib/messages":72,"./zlib/zstream":74}],62:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;b<c;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;b<c;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],63:[function(a,b,c){"use strict";function d(a,b){if(b<65537&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;d<b;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;j<256;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;f<h;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=c<128?1:c<2048?2:c<65536?3:4;for(b=new e.Buf8(i),g=0,f=0;g<i;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),c<128?b[g++]=c:c<2048?(b[g++]=192|c>>>6,b[g++]=128|63&c):c<65536?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;c<d;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;c<h;)if(f=a[c++],f<128)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&c<h;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:f<65536?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return c<0?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":62}],64:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0; }b.exports=d},{}],65:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],66:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;c<256;c++){a=c;for(var d=0;d<8;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;h<g;h++)a=a>>>8^e[255&(a^b[h])];return a^-1}var f=d();b.exports=e},{}],67:[function(a,b,c){"use strict";function d(a,b){return a.msg=I[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(E.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){F._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,E.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=G(a.adler,b,e,c):2===a.state.wrap&&(a.adler=H(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-la?a.strstart-(a.w_size-la):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ka,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&f<m);if(d=ka-(m-f),f=m-ka,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-la)){E.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ja)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ja-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ja)););}while(a.lookahead<la&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===J)return ua;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ua;if(a.strstart-a.block_start>=a.w_size-la&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ua:ua}function o(a,b){for(var c,d;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c)),a.match_length>=ja)if(d=F._tr_tally(a,a.strstart-a.match_start,a.match_length-ja),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ja){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function p(a,b){for(var c,d,e;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ja-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===U||a.match_length===ja&&a.strstart-a.match_start>4096)&&(a.match_length=ja-1)),a.prev_length>=ja&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ja,d=F._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ja),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ja-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ua}else if(a.match_available){if(d=F._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ua}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=F._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ka){if(m(a),a.lookahead<=ka&&b===J)return ua;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ja&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ka;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&e<f);a.match_length=ka-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ja?(c=F._tr_tally(a,1,a.match_length-ja),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===J)return ua;break}if(a.match_length=0,c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=D[a.level].max_lazy,a.good_match=D[a.level].good_length,a.nice_match=D[a.level].nice_length,a.max_chain_length=D[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ja-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=$,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*ha),this.dyn_dtree=new E.Buf16(2*(2*fa+1)),this.bl_tree=new E.Buf16(2*(2*ga+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(ia+1),this.heap=new E.Buf16(2*ea+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*ea+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Z,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?na:sa,a.adler=2===b.wrap?0:1,b.last_flush=J,F._tr_init(b),O):d(a,Q)}function w(a){var b=v(a);return b===O&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?Q:(a.state.gzhead=b,O):Q}function y(a,b,c,e,f,g){if(!a)return Q;var h=1;if(b===T&&(b=6),e<0?(h=0,e=-e):e>15&&(h=2,e-=16),f<1||f>_||c!==$||e<8||e>15||b<0||b>9||g<0||g>X)return d(a,Q);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ja-1)/ja),i.window=new E.Buf8(2*i.w_size),i.head=new E.Buf16(i.hash_size),i.prev=new E.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new E.Buf8(i.pending_buf_size),i.d_buf=1*i.lit_bufsize,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,$,aa,ba,Y)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>N||b<0)return a?d(a,Q):Q;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ta&&b!==M)return d(a,0===a.avail_out?S:Q);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===na)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=H(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=oa):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,ya),h.status=sa);else{var m=$+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=V||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ma),m+=31-m%31,h.status=sa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===oa)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=qa)}else h.status=qa;if(h.status===qa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=ra)}else h.status=ra;if(h.status===ra&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=sa)):h.status=sa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,O}else if(0===a.avail_in&&e(b)<=e(c)&&b!==M)return d(a,S);if(h.status===ta&&0!==a.avail_in)return d(a,S);if(0!==a.avail_in||0!==h.lookahead||b!==J&&h.status!==ta){var o=h.strategy===V?r(h,b):h.strategy===W?q(h,b):D[h.level].func(h,b);if(o!==wa&&o!==xa||(h.status=ta),o===ua||o===wa)return 0===a.avail_out&&(h.last_flush=-1),O;if(o===va&&(b===K?F._tr_align(h):b!==N&&(F._tr_stored_block(h,0,0,!1),b===L&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,O}return b!==M?O:h.wrap<=0?P:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?O:P)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa&&b!==ta?d(a,Q):(a.state=null,b===sa?d(a,R):O)):Q}function C(a,b){var c,d,e,g,h,i,j,k,l=b.length;if(!a||!a.state)return Q;if(c=a.state,g=c.wrap,2===g||1===g&&c.status!==na||c.lookahead)return Q;for(1===g&&(a.adler=G(a.adler,b,l,0)),c.wrap=0,l>=c.w_size&&(0===g&&(f(c.head),c.strstart=0,c.block_start=0,c.insert=0),k=new E.Buf8(c.w_size),E.arraySet(k,b,l-c.w_size,c.w_size,0),b=k,l=c.w_size),h=a.avail_in,i=a.next_in,j=a.input,a.avail_in=l,a.next_in=0,a.input=b,m(c);c.lookahead>=ja;){d=c.strstart,e=c.lookahead-(ja-1);do c.ins_h=(c.ins_h<<c.hash_shift^c.window[d+ja-1])&c.hash_mask,c.prev[d&c.w_mask]=c.head[c.ins_h],c.head[c.ins_h]=d,d++;while(--e);c.strstart=d,c.lookahead=ja-1,m(c)}return c.strstart+=c.lookahead,c.block_start=c.strstart,c.insert=c.lookahead,c.lookahead=0,c.match_length=c.prev_length=ja-1,c.match_available=0,a.next_in=i,a.input=j,a.avail_in=h,c.wrap=g,O}var D,E=a("../utils/common"),F=a("./trees"),G=a("./adler32"),H=a("./crc32"),I=a("./messages"),J=0,K=1,L=3,M=4,N=5,O=0,P=1,Q=-2,R=-3,S=-5,T=-1,U=1,V=2,W=3,X=4,Y=0,Z=2,$=8,_=9,aa=15,ba=8,ca=29,da=256,ea=da+1+ca,fa=30,ga=19,ha=2*ea+1,ia=15,ja=3,ka=258,la=ka+ja+1,ma=32,na=42,oa=69,pa=73,qa=91,ra=103,sa=113,ta=666,ua=1,va=2,wa=3,xa=4,ya=3;D=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateSetDictionary=C,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":62,"./adler32":64,"./crc32":66,"./messages":72,"./trees":73}],68:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],69:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(q<w&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,q<w&&(p+=B[f++]<<q,q+=8,q<w&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(n<w){if(z+=l+n-w,w-=n,w<x){x-=w;do C[h++]=o[z++];while(--w);if(z=0,n<x){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(f<g&&h<j);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=f<g?5+(g-f):5-(f-g),a.avail_out=h<j?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],70:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=L,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new s.Buf32(pa),b.distcode=b.distdyn=new s.Buf32(qa),b.sane=1,b.back=-1,D):G}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):G}function h(a,b){var c,d;return a&&a.state?(d=a.state,b<0?(c=0,b=-b):(c=(b>>4)+1,b<48&&(b&=15)),b&&(b<8||b>15)?G:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):G}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==D&&(a.state=null),c):G}function j(a){return i(a,sa)}function k(a){if(ta){var b;for(q=new s.Buf32(512),r=new s.Buf32(32),b=0;b<144;)a.lens[b++]=8;for(;b<256;)a.lens[b++]=9;for(;b<280;)a.lens[b++]=7;for(;b<288;)a.lens[b++]=8;for(w(y,a.lens,0,288,q,0,a.work,{bits:9}),b=0;b<32;)a.lens[b++]=5;w(z,a.lens,0,32,r,0,a.work,{bits:5}),ta=!1}a.lencode=q,a.lenbits=9,a.distcode=r,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new s.Buf8(f.wsize)),d>=f.wsize?(s.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),s.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(s.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,r,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new s.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return G;c=a.state,c.mode===W&&(c.mode=X),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=D;a:for(;;)switch(c.mode){case L:if(0===c.wrap){c.mode=X;break}for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0),m=0,n=0,c.mode=M;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=ma;break}if((15&m)!==K){a.msg="unknown compression method",c.mode=ma;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=ma;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?U:W,m=0,n=0;break;case M:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==K){a.msg="unknown compression method",c.mode=ma;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=ma;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=N;case N:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=u(c.check,Ba,4,0)),m=0,n=0,c.mode=O;case O:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=P;case P:if(1024&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=Q;case Q:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),s.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=R;case R:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=S;case S:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=T;case T:if(512&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=ma;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=W;break;case U:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=V;case V:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,F;a.adler=c.check=1,c.mode=W;case W:if(b===B||b===C)break a;case X:if(c.last){m>>>=7&n,n-=7&n,c.mode=ja;break}for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=Y;break;case 1:if(k(c),c.mode=ca,b===C){m>>>=2,n-=2;break a}break;case 2:c.mode=_;break;case 3:a.msg="invalid block type",c.mode=ma}m>>>=2,n-=2;break;case Y:for(m>>>=7&n,n-=7&n;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=ma;break}if(c.length=65535&m,m=0,n=0,c.mode=Z,b===C)break a;case Z:c.mode=$;case $:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;s.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=W;break;case _:for(;n<14;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=ma;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.ncode;){for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=w(x,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=ma;break}c.have=0,c.mode=ba;case ba:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(sa<16)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=ma;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=ma;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===ma)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=ma;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=w(y,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=ma;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=w(z,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=ma;break}if(c.mode=ca,b===C)break a;case ca:c.mode=da;case da:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,v(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===W&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ia;break}if(32&ra){c.back=-1,c.mode=W;break}if(64&ra){a.msg="invalid literal/length code",c.mode=ma;break}c.extra=15&ra,c.mode=ea;case ea:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=fa;case fa:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=ma;break}c.offset=sa,c.extra=15&ra,c.mode=ga;case ga:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=ma;break}c.mode=ha;case ha:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=ma;break}q>c.wnext?(q-=c.wnext,r=c.wsize-q):r=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,r=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[r++];while(--q);0===c.length&&(c.mode=da);break;case ia:if(0===j)break a;f[h++]=c.length,j--,c.mode=da;break;case ja:if(c.wrap){for(;n<32;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?u(c.check,f,p,h-p):t(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=ma;break}m=0,n=0}c.mode=ka;case ka:if(c.wrap&&c.flags){for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=ma;break}m=0,n=0}c.mode=la;case la:xa=E;break a;case ma:xa=H;break a;case na:return I;case oa:default:return G}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<ma&&(c.mode<ja||b!==A))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=na,I):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?u(c.check,f,p,a.next_out-p):t(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===W?128:0)+(c.mode===ca||c.mode===Z?256:0),(0===o&&0===p||b===A)&&xa===D&&(xa=J),xa)}function n(a){if(!a||!a.state)return G;var b=a.state;return b.window&&(b.window=null),a.state=null,D}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?G:(c.head=b,b.done=!1,D)):G}function p(a,b){var c,d,e,f=b.length;return a&&a.state?(c=a.state,0!==c.wrap&&c.mode!==V?G:c.mode===V&&(d=1,d=t(d,b,f,0),d!==c.check)?H:(e=l(a,b,f,f))?(c.mode=na,I):(c.havedict=1,D)):G}var q,r,s=a("../utils/common"),t=a("./adler32"),u=a("./crc32"),v=a("./inffast"),w=a("./inftrees"),x=0,y=1,z=2,A=4,B=5,C=6,D=0,E=1,F=2,G=-2,H=-3,I=-4,J=-5,K=8,L=1,M=2,N=3,O=4,P=5,Q=6,R=7,S=8,T=9,U=10,V=11,W=12,X=13,Y=14,Z=15,$=16,_=17,aa=18,ba=19,ca=20,da=21,ea=22,fa=23,ga=24,ha=25,ia=26,ja=27,ka=28,la=29,ma=30,na=31,oa=32,pa=852,qa=592,ra=15,sa=ra,ta=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateSetDictionary=p,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":62,"./adler32":64,"./crc32":66,"./inffast":69,"./inftrees":71}],71:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;D<=e;D++)P[D]=0;for(E=0;E<o;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;F<G&&0===P[F];F++);for(H<F&&(H=F),K=1,D=1;D<=e;D++)if(K<<=1,K-=P[D],K<0)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;D<e;D++)Q[D+1]=Q[D]+P[D];for(E=0;E<o;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(;;){z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;I+J<G&&(K-=P[I+J],!(K<=0));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":62}],72:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],73:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return a<256?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;f<=W;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0, c=a.heap_max+1;c<V;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;d<=W;d++)f[d]=g=g+c[d-1]<<1;for(e=0;e<=b;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;d<Q-1;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;d<16;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;d<T;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;b<=W;b++)g[b]=0;for(a=0;a<=143;)ga[2*a+1]=8,a++,g[8]++;for(;a<=255;)ga[2*a+1]=9,a++,g[9]++;for(;a<=279;)ga[2*a+1]=7,a++,g[7]++;for(;a<=287;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;a<T;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;b<S;b++)a.dyn_ltree[2*b]=0;for(b=0;b<T;b++)a.dyn_dtree[2*b]=0;for(b=0;b<U;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;c<i;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=j<2?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;d<=c;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(h<j?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):h<=10?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;d<=c;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(h<l){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):h<=10?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;e<d;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;b<=31;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;b<R;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,f<=e&&(e=f)):e=f=c+5,c+4<=e&&b!==-1?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":62}],74:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[10])(10)});
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/libs/zip.min.js
zip.min.js
(function () { 'use strict'; var isCommonjs = typeof module !== 'undefined' && module.exports; var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element; var fn = (function () { var val; var valLength; var fnMap = [ [ 'requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror' ], // new WebKit [ 'webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror' ], // old WebKit (Safari 5.1) [ 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror' ], [ 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror' ], [ 'msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError' ] ]; var i = 0; var l = fnMap.length; var ret = {}; for (; i < l; i++) { val = fnMap[i]; if (val && val[1] in document) { for (i = 0, valLength = val.length; i < valLength; i++) { ret[fnMap[0][i]] = val[i]; } return ret; } } return false; })(); var screenfull = { request: function (elem) { var request = fn.requestFullscreen; elem = elem || document.documentElement; // Work around Safari 5.1 bug: reports support for // keyboard in fullscreen even though it doesn't. // Browser sniffing, since the alternative with // setTimeout is even worse. if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) { elem[request](); } else { elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT); } }, exit: function () { document[fn.exitFullscreen](); }, toggle: function (elem) { if (this.isFullscreen) { this.exit(); } else { this.request(elem); } }, raw: fn }; if (!fn) { if (isCommonjs) { module.exports = false; } else { window.screenfull = false; } return; } Object.defineProperties(screenfull, { isFullscreen: { get: function () { return !!document[fn.fullscreenElement]; } }, element: { enumerable: true, get: function () { return document[fn.fullscreenElement]; } }, enabled: { enumerable: true, get: function () { // Coerce to boolean in case of old WebKit return !!document[fn.fullscreenEnabled]; } } }); if (isCommonjs) { module.exports = screenfull; } else { window.screenfull = screenfull; } })();
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/libs/screenfull.js
screenfull.js
!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.localforage=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){(function(a){"use strict";function c(){k=!0;for(var a,b,c=l.length;c;){for(b=l,l=[],a=-1;++a<c;)b[a]();c=l.length}k=!1}function d(a){1!==l.push(a)||k||e()}var e,f=a.MutationObserver||a.WebKitMutationObserver;if(f){var g=0,h=new f(c),i=a.document.createTextNode("");h.observe(i,{characterData:!0}),e=function(){i.data=g=++g%2}}else if(a.setImmediate||"undefined"==typeof a.MessageChannel)e="document"in a&&"onreadystatechange"in a.document.createElement("script")?function(){var b=a.document.createElement("script");b.onreadystatechange=function(){c(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},a.document.documentElement.appendChild(b)}:function(){setTimeout(c,0)};else{var j=new a.MessageChannel;j.port1.onmessage=c,e=function(){j.port2.postMessage(0)}}var k,l=[];b.exports=d}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],2:[function(a,b,c){"use strict";function d(){}function e(a){if("function"!=typeof a)throw new TypeError("resolver must be a function");this.state=s,this.queue=[],this.outcome=void 0,a!==d&&i(this,a)}function f(a,b,c){this.promise=a,"function"==typeof b&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),"function"==typeof c&&(this.onRejected=c,this.callRejected=this.otherCallRejected)}function g(a,b,c){o(function(){var d;try{d=b(c)}catch(b){return p.reject(a,b)}d===a?p.reject(a,new TypeError("Cannot resolve promise with itself")):p.resolve(a,d)})}function h(a){var b=a&&a.then;if(a&&"object"==typeof a&&"function"==typeof b)return function(){b.apply(a,arguments)}}function i(a,b){function c(b){f||(f=!0,p.reject(a,b))}function d(b){f||(f=!0,p.resolve(a,b))}function e(){b(d,c)}var f=!1,g=j(e);"error"===g.status&&c(g.value)}function j(a,b){var c={};try{c.value=a(b),c.status="success"}catch(a){c.status="error",c.value=a}return c}function k(a){return a instanceof this?a:p.resolve(new this(d),a)}function l(a){var b=new this(d);return p.reject(b,a)}function m(a){function b(a,b){function d(a){g[b]=a,++h!==e||f||(f=!0,p.resolve(j,g))}c.resolve(a).then(d,function(a){f||(f=!0,p.reject(j,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=new Array(e),h=0,i=-1,j=new this(d);++i<e;)b(a[i],i);return j}function n(a){function b(a){c.resolve(a).then(function(a){f||(f=!0,p.resolve(h,a))},function(a){f||(f=!0,p.reject(h,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=-1,h=new this(d);++g<e;)b(a[g]);return h}var o=a(1),p={},q=["REJECTED"],r=["FULFILLED"],s=["PENDING"];b.exports=c=e,e.prototype.catch=function(a){return this.then(null,a)},e.prototype.then=function(a,b){if("function"!=typeof a&&this.state===r||"function"!=typeof b&&this.state===q)return this;var c=new this.constructor(d);if(this.state!==s){var e=this.state===r?a:b;g(c,e,this.outcome)}else this.queue.push(new f(c,a,b));return c},f.prototype.callFulfilled=function(a){p.resolve(this.promise,a)},f.prototype.otherCallFulfilled=function(a){g(this.promise,this.onFulfilled,a)},f.prototype.callRejected=function(a){p.reject(this.promise,a)},f.prototype.otherCallRejected=function(a){g(this.promise,this.onRejected,a)},p.resolve=function(a,b){var c=j(h,b);if("error"===c.status)return p.reject(a,c.value);var d=c.value;if(d)i(a,d);else{a.state=r,a.outcome=b;for(var e=-1,f=a.queue.length;++e<f;)a.queue[e].callFulfilled(b)}return a},p.reject=function(a,b){a.state=q,a.outcome=b;for(var c=-1,d=a.queue.length;++c<d;)a.queue[c].callRejected(b);return a},c.resolve=k,c.reject=l,c.all=m,c.race=n},{1:1}],3:[function(a,b,c){(function(b){"use strict";"function"!=typeof b.Promise&&(b.Promise=a(2))}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{2:2}],4:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function e(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(a){}}function f(){try{if(!ga)return!1;var a="undefined"!=typeof openDatabase&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),b="function"==typeof fetch&&fetch.toString().indexOf("[native code")!==-1;return(!a||b)&&"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(a){return!1}}function g(){return"function"==typeof openDatabase}function h(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&localStorage.setItem}catch(a){return!1}}function i(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(f){if("TypeError"!==f.name)throw f;for(var c="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder,d=new c,e=0;e<a.length;e+=1)d.append(a[e]);return d.getBlob(b.type)}}function j(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function k(a,b,c){"function"==typeof b&&a.then(b),"function"==typeof c&&a.catch(c)}function l(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;e<b;e++)d[e]=a.charCodeAt(e);return c}function m(a){return new ja(function(b){var c=a.transaction(ka,"readwrite"),d=i([""]);c.objectStore(ka).put(d,"key"),c.onabort=function(a){a.preventDefault(),a.stopPropagation(),b(!1)},c.oncomplete=function(){var a=navigator.userAgent.match(/Chrome\/(\d+)/),c=navigator.userAgent.match(/Edge\//);b(c||!a||parseInt(a[1],10)>=43)}}).catch(function(){return!1})}function n(a){return"boolean"==typeof ha?ja.resolve(ha):m(a).then(function(a){return ha=a})}function o(a){var b=ia[a.name],c={};c.promise=new ja(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function p(a){var b=ia[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function q(a,b){return new ja(function(c,d){if(a.db){if(!b)return c(a.db);o(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=ga.open.apply(ga,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ka)}catch(c){if("ConstraintError"!==c.name)throw c;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(a){a.preventDefault(),d(f.error)},f.onsuccess=function(){c(f.result),p(a)}})}function r(a){return q(a,!1)}function s(a){return q(a,!0)}function t(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function u(a){return new ja(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function v(a){var b=l(atob(a.data));return i([b],{type:a.type})}function w(a){return a&&a.__local_forage_encoded_blob}function x(a){var b=this,c=b._initReady().then(function(){var a=ia[b._dbInfo.name];if(a&&a.dbReady)return a.dbReady});return k(c,a,a),c}function y(a){function b(){return ja.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ia||(ia={});var f=ia[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},ia[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=x);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady().catch(b))}var j=f.forages.slice(0);return ja.all(g).then(function(){return d.db=f.db,r(d)}).then(function(a){return d.db=a,t(d,c._defaultConfig.version)?s(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<j.length;b++){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function z(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),w(a)&&(a=v(a)),b(a)},g.onerror=function(){d(g.error)}}).catch(d)});return j(d,b),d}function A(a,b){var c=this,d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;w(d)&&(d=v(d));var e=a(d,c.key,h++);void 0!==e?b(e):c.continue()}else b()},g.onerror=function(){d(g.error)}}).catch(d)});return j(d,b),d}function B(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ja(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,"[object Blob]"===la.call(b)?n(f.db).then(function(a){return a?b:u(b)}):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName),h=g.put(b,a);null===b&&(b=void 0),d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}}).catch(e)});return j(e,c),e}function C(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g.delete(a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}}).catch(d)});return j(d,b),d}function D(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}}).catch(c)});return j(c,a),c}function E(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}}).catch(c)});return j(c,a),c}function F(a,b){var c=this,d=new ja(function(b,d){return a<0?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}}).catch(d)});return j(d,b),d}function G(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b.continue()):void a(g)},f.onerror=function(){c(f.error)}}).catch(c)});return j(c,a),c}function H(a){var b,c,d,e,f,g=.75*a.length,h=a.length,i=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var j=new ArrayBuffer(g),k=new Uint8Array(j);for(b=0;b<h;b+=4)c=na.indexOf(a[b]),d=na.indexOf(a[b+1]),e=na.indexOf(a[b+2]),f=na.indexOf(a[b+3]),k[i++]=c<<2|d>>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function I(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=na[c[b]>>2],d+=na[(3&c[b])<<4|c[b+1]>>4],d+=na[(15&c[b+1])<<2|c[b+2]>>6],d+=na[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function J(a,b){var c="";if(a&&(c=Ea.call(a)),a&&("[object ArrayBuffer]"===c||a.buffer&&"[object ArrayBuffer]"===Ea.call(a.buffer))){var d,e=qa;a instanceof ArrayBuffer?(d=a,e+=sa):(d=a.buffer,"[object Int8Array]"===c?e+=ua:"[object Uint8Array]"===c?e+=va:"[object Uint8ClampedArray]"===c?e+=wa:"[object Int16Array]"===c?e+=xa:"[object Uint16Array]"===c?e+=za:"[object Int32Array]"===c?e+=ya:"[object Uint32Array]"===c?e+=Aa:"[object Float32Array]"===c?e+=Ba:"[object Float64Array]"===c?e+=Ca:b(new Error("Failed to get type for BinaryArray"))),b(e+I(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=oa+a.type+"~"+I(this.result);b(qa+ta+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(c){console.error("Couldn't convert value into a JSON string: ",a),b(null,c)}}function K(a){if(a.substring(0,ra)!==qa)return JSON.parse(a);var b,c=a.substring(Da),d=a.substring(ra,Da);if(d===ta&&pa.test(c)){var e=c.match(pa);b=e[1],c=c.substring(e[0].length)}var f=H(c);switch(d){case sa:return f;case ta:return i([f],{type:b});case ua:return new Int8Array(f);case va:return new Uint8Array(f);case wa:return new Uint8ClampedArray(f);case xa:return new Int16Array(f);case za:return new Uint16Array(f);case ya:return new Int32Array(f);case Aa:return new Uint32Array(f);case Ba:return new Float32Array(f);case Ca:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function L(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ja(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(a){return d(a)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Fa,e}function M(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function N(a,b){var c=this,d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;h<g;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function O(a,b,c,d){var e=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var f=new ja(function(f,g){e.ready().then(function(){void 0===b&&(b=null);var h=b,i=e._dbInfo;i.serializer.serialize(b,function(b,j){j?g(j):i.db.transaction(function(c){c.executeSql("INSERT OR REPLACE INTO "+i.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){f(h)},function(a,b){g(b)})},function(b){if(b.code===b.QUOTA_ERR){if(d>0)return void f(O.apply(e,[a,h,c,d-1]));g(b)}})})}).catch(g)});return j(f,c),f}function P(a,b,c){return O.apply(this,[a,b,c,1])}function Q(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function R(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function S(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function T(a,b){var c=this,d=new ja(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function U(a){var b=this,c=new ja(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function V(a){var b=this,c={};if(a)for(var d in a)c[d]=a[d];return c.keyPrefix=c.name+"/",c.storeName!==b._defaultConfig.storeName&&(c.keyPrefix+=c.storeName+"/"),b._dbInfo=c,c.serializer=Fa,ja.resolve()}function W(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=localStorage.length-1;c>=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function X(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function Y(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;h<f;h++){var i=localStorage.key(h);if(0===i.indexOf(d)){var j=localStorage.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return j(d,b),d}function Z(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=localStorage.key(a)}catch(a){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return j(d,b),d}function $(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=localStorage.length,d=[],e=0;e<c;e++)0===localStorage.key(e).indexOf(a.keyPrefix)&&d.push(localStorage.key(e).substring(a.keyPrefix.length));return d});return j(c,a),c}function _(a){var b=this,c=b.keys().then(function(a){return a.length});return j(c,a),c}function aa(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;localStorage.removeItem(b.keyPrefix+a)});return j(d,b),d}function ba(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new ja(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{localStorage.setItem(g.keyPrefix+a,b),e(c)}catch(a){"QuotaExceededError"!==a.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==a.name||f(a),f(a)}})})});return j(e,c),e}function ca(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function da(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(Oa(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function ea(a){for(var b in Ja)if(Ja.hasOwnProperty(b)&&Ja[b]===a)return!0;return!1}var fa="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},ga=e();"undefined"==typeof Promise&&a(3);var ha,ia,ja=Promise,ka="local-forage-detect-blob-support",la=Object.prototype.toString,ma={_driver:"asyncStorage",_initStorage:y,iterate:A,getItem:z,setItem:B,removeItem:C,clear:D,length:E,key:F,keys:G},na="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",oa="~~local_forage_type~",pa=/^~~local_forage_type~([^~]+)~/,qa="__lfsc__:",ra=qa.length,sa="arbf",ta="blob",ua="si08",va="ui08",wa="uic8",xa="si16",ya="si32",za="ur16",Aa="ui32",Ba="fl32",Ca="fl64",Da=ra+sa.length,Ea=Object.prototype.toString,Fa={serialize:J,deserialize:K,stringToBuffer:H,bufferToString:I},Ga={_driver:"webSQLStorage",_initStorage:L,iterate:N,getItem:M,setItem:P,removeItem:Q,clear:R,length:S,key:T,keys:U},Ha={_driver:"localStorageWrapper",_initStorage:V,iterate:Y,getItem:X,setItem:ba,removeItem:aa,clear:W,length:_,key:Z,keys:$},Ia={},Ja={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},Ka=[Ja.INDEXEDDB,Ja.WEBSQL,Ja.LOCALSTORAGE],La=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],Ma={description:"",driver:Ka.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},Na={};Na[Ja.INDEXEDDB]=f(),Na[Ja.WEBSQL]=g(),Na[Ja.LOCALSTORAGE]=h();var Oa=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},Pa=function(){function a(b){d(this,a),this.INDEXEDDB=Ja.INDEXEDDB,this.LOCALSTORAGE=Ja.LOCALSTORAGE,this.WEBSQL=Ja.WEBSQL,this._defaultConfig=da({},Ma),this._config=da({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return a.prototype.config=function(a){if("object"===("undefined"==typeof a?"undefined":fa(a))){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a){if("storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),"version"===b&&"number"!=typeof a[b])return new Error("Database version must be a number.");this._config[b]=a[b]}return!("driver"in a&&a.driver)||this.setDriver(this._config.driver)}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new ja(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),f=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(ea(a._driver))return void c(f);for(var g=La.concat("_initStorage"),h=0;h<g.length;h++){var i=g[h];if(!i||!a[i]||"function"!=typeof a[i])return void c(e)}var j=ja.resolve(!0);"_support"in a&&(j=a._support&&"function"==typeof a._support?a._support():ja.resolve(!!a._support)),j.then(function(c){Na[d]=c,Ia[d]=a,b()},c)}catch(a){c(a)}});return k(d,b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,c){var d=this,e=ja.resolve().then(function(){if(!ea(a)){if(Ia[a])return Ia[a];throw new Error("Driver not found.")}switch(a){case d.INDEXEDDB:return ma;case d.LOCALSTORAGE:return Ha;case d.WEBSQL:return Ga}});return k(e,b,c),e},a.prototype.getSerializer=function(a){var b=ja.resolve(Fa);return k(b,a),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return k(c,a,a),c},a.prototype.setDriver=function(a,b,c){function d(){g._config.driver=g.driver()}function e(a){return g._extend(a),d(),g._ready=g._initStorage(g._config),g._ready}function f(a){return function(){function b(){for(;c<a.length;){var f=a[c];return c++,g._dbInfo=null,g._ready=null,g.getDriver(f).then(e).catch(b)}d();var h=new Error("No available storage method found.");return g._driverSet=ja.reject(h),g._driverSet}var c=0;return b()}}var g=this;Oa(a)||(a=[a]);var h=this._getSupportedDrivers(a),i=null!==this._driverSet?this._driverSet.catch(function(){return ja.resolve()}):ja.resolve();return this._driverSet=i.then(function(){var a=h[0];return g._dbInfo=null,g._ready=null,g.getDriver(a).then(function(a){g._driver=a._driver,d(),g._wrapLibraryMethodsWithReady(),g._initDriver=f(h)})}).catch(function(){d();var a=new Error("No available storage method found.");return g._driverSet=ja.reject(a),g._driverSet}),k(this._driverSet,b,c),this._driverSet},a.prototype.supports=function(a){return!!Na[a]},a.prototype._extend=function(a){da(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<La.length;a++)ca(this,La[a])},a.prototype.createInstance=function(b){return new a(b)},a}(),Qa=new Pa;b.exports=Qa},{3:3}]},{},[4])(4)});
zidan-biji
/zidan-biji-2022.10.15.0.tar.gz/zidan-biji-2022.10.15.0/ZidanBiji/js/libs/localforage.min.js
localforage.min.js
discord.py ========== .. image:: https://discord.com/api/guilds/336642139381301249/embed.png :target: https://discord.gg/r3sSKJJ :alt: Discord server invite .. image:: https://img.shields.io/pypi/v/discord.py.svg :target: https://pypi.python.org/pypi/discord.py :alt: PyPI version info .. image:: https://img.shields.io/pypi/pyversions/discord.py.svg :target: https://pypi.python.org/pypi/discord.py :alt: PyPI supported Python versions A modern, easy to use, feature-rich, and async ready API wrapper for Discord written in Python. `original lib by Rapptz <https://github.com/iDutchy/discord.py>`_ **WARNING: This is not the official discord.py library! This is modified version for my personal purposes, this version is based on experimental version of the original lib! so it may be unstable.** Key Features ------------- - Modern Pythonic API using ``async`` and ``await``. - Proper rate limit handling. - 100% coverage of the supported Discord API. - Optimised in both speed and memory. Installing ---------- **Python 3.5.3 or higher is required** To install the library without full voice support, you can just run the following command: .. code:: sh # Linux/macOS python3 -m pip install -U discord.py # Windows py -3 -m pip install -U discord.py Otherwise to get voice support you should run the following command: .. code:: sh # Linux/macOS python3 -m pip install -U "discord.py[voice]" # Windows py -3 -m pip install -U discord.py[voice] To install the development version, do the following: .. code:: sh $ git clone https://github.com/Rapptz/discord.py $ cd discord.py $ python3 -m pip install -U .[voice] Optional Packages ~~~~~~~~~~~~~~~~~~ * PyNaCl (for voice support) Please note that on Linux installing voice you must install the following packages via your favourite package manager (e.g. ``apt``, ``dnf``, etc) before running the above commands: * libffi-dev (or ``libffi-devel`` on some systems) * python-dev (e.g. ``python3.6-dev`` for Python 3.6) Quick Example -------------- .. code:: py import discord class MyClient(discord.Client): async def on_ready(self): print('Logged on as', self.user) async def on_message(self, message): # don't respond to ourselves if message.author == self.user: return if message.content == 'ping': await message.channel.send('pong') client = MyClient() client.run('token') Bot Example ~~~~~~~~~~~~~ .. code:: py import discord from discord.ext import commands bot = commands.Bot(command_prefix='>') @bot.command() async def ping(ctx): await ctx.send('pong') bot.run('token') You can find more examples in the examples directory. Links ------ - `Documentation <https://discordpy.readthedocs.io/en/latest/index.html>`_ - `Official Discord Server <https://discord.gg/r3sSKJJ>`_ - `Discord API <https://discord.gg/discord-api>`_
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/README.rst
README.rst
import logging import asyncio import json import time import re from urllib.parse import quote as _uriquote import aiohttp from . import utils from .errors import InvalidArgument, HTTPException, Forbidden, NotFound, DiscordServerError from .message import Message from .enums import try_enum, WebhookType from .user import BaseUser, User from .asset import Asset from .mixins import Hashable __all__ = ( 'WebhookAdapter', 'AsyncWebhookAdapter', 'RequestsWebhookAdapter', 'Webhook', 'WebhookMessage', ) log = logging.getLogger(__name__) class WebhookAdapter: """Base class for all webhook adapters. Attributes ------------ webhook: :class:`Webhook` The webhook that owns this adapter. """ BASE = 'https://discord.com/api/v7' def _prepare(self, webhook): self._webhook_id = webhook.id self._webhook_token = webhook.token self._request_url = '{0.BASE}/webhooks/{1}/{2}'.format(self, webhook.id, webhook.token) self.webhook = webhook def is_async(self): return False def request(self, verb, url, payload=None, multipart=None): """Actually does the request. Subclasses must implement this. Parameters ----------- verb: :class:`str` The HTTP verb to use for the request. url: :class:`str` The URL to send the request to. This will have the query parameters already added to it, if any. multipart: Optional[:class:`dict`] A dict containing multipart form data to send with the request. If a filename is being uploaded, then it will be under a ``file`` key which will have a 3-element :class:`tuple` denoting ``(filename, file, content_type)``. payload: Optional[:class:`dict`] The JSON to send with the request, if any. """ raise NotImplementedError() def delete_webhook(self, *, reason=None): return self.request('DELETE', self._request_url, reason=reason) def edit_webhook(self, *, reason=None, **payload): return self.request('PATCH', self._request_url, payload=payload, reason=reason) def edit_webhook_message(self, message_id, payload): return self.request('PATCH', '{}/messages/{}'.format(self._request_url, message_id), payload=payload) def delete_webhook_message(self, message_id): return self.request('DELETE', '{}/messages/{}'.format(self._request_url, message_id)) def handle_execution_response(self, data, *, wait): """Transforms the webhook execution response into something more meaningful. This is mainly used to convert the data into a :class:`Message` if necessary. Subclasses must implement this. Parameters ------------ data The data that was returned from the request. wait: :class:`bool` Whether the webhook execution was asked to wait or not. """ raise NotImplementedError() async def _wrap_coroutine_and_cleanup(self, coro, cleanup): try: return await coro finally: cleanup() def execute_webhook(self, *, payload, wait=False, file=None, files=None): cleanup = None if file is not None: multipart = { 'file': (file.filename, file.fp, 'application/octet-stream'), 'payload_json': utils.to_json(payload) } data = None cleanup = file.close files_to_pass = [file] elif files is not None: multipart = { 'payload_json': utils.to_json(payload) } for i, file in enumerate(files): multipart['file%i' % i] = (file.filename, file.fp, 'application/octet-stream') data = None def _anon(): for f in files: f.close() cleanup = _anon files_to_pass = files else: data = payload multipart = None files_to_pass = None url = '%s?wait=%d' % (self._request_url, wait) maybe_coro = None try: maybe_coro = self.request('POST', url, multipart=multipart, payload=data, files=files_to_pass) finally: if maybe_coro is not None and cleanup is not None: if not asyncio.iscoroutine(maybe_coro): cleanup() else: maybe_coro = self._wrap_coroutine_and_cleanup(maybe_coro, cleanup) # if request raises up there then this should never be `None` return self.handle_execution_response(maybe_coro, wait=wait) class AsyncWebhookAdapter(WebhookAdapter): """A webhook adapter suited for use with aiohttp. .. note:: You are responsible for cleaning up the client session. Parameters ----------- session: :class:`aiohttp.ClientSession` The session to use to send requests. """ def __init__(self, session): self.session = session self.loop = asyncio.get_event_loop() def is_async(self): return True async def request(self, verb, url, payload=None, multipart=None, *, files=None, reason=None): headers = {} data = None files = files or [] if payload: headers['Content-Type'] = 'application/json' data = utils.to_json(payload) if reason: headers['X-Audit-Log-Reason'] = _uriquote(reason, safe='/ ') base_url = url.replace(self._request_url, '/') or '/' _id = self._webhook_id for tries in range(5): for file in files: file.reset(seek=tries) if multipart: data = aiohttp.FormData() for key, value in multipart.items(): if key.startswith('file'): data.add_field(key, value[1], filename=value[0], content_type=value[2]) else: data.add_field(key, value) async with self.session.request(verb, url, headers=headers, data=data) as r: log.debug('Webhook ID %s with %s %s has returned status code %s', _id, verb, base_url, r.status) # Coerce empty strings to return None for hygiene purposes response = (await r.text(encoding='utf-8')) or None if r.headers['Content-Type'] == 'application/json': response = json.loads(response) # check if we have rate limit header information remaining = r.headers.get('X-Ratelimit-Remaining') if remaining == '0' and r.status != 429: delta = utils._parse_ratelimit_header(r) log.debug('Webhook ID %s has been pre-emptively rate limited, waiting %.2f seconds', _id, delta) await asyncio.sleep(delta) if 300 > r.status >= 200: return response # we are being rate limited if r.status == 429: if not r.headers.get('Via'): # Banned by Cloudflare more than likely. raise HTTPException(r, data) retry_after = response['retry_after'] / 1000.0 log.warning('Webhook ID %s is rate limited. Retrying in %.2f seconds', _id, retry_after) await asyncio.sleep(retry_after) continue if r.status in (500, 502): await asyncio.sleep(1 + tries * 2) continue if r.status == 403: raise Forbidden(r, response) elif r.status == 404: raise NotFound(r, response) else: raise HTTPException(r, response) # no more retries if r.status >= 500: raise DiscordServerError(r, response) raise HTTPException(r, response) async def handle_execution_response(self, response, *, wait): data = await response if not wait: return data # transform into Message object # Make sure to coerce the state to the partial one to allow message edits/delete state = _PartialWebhookState(self, self.webhook, parent=self.webhook._state) return WebhookMessage(data=data, state=state, channel=self.webhook.channel) class RequestsWebhookAdapter(WebhookAdapter): """A webhook adapter suited for use with ``requests``. Only versions of :doc:`req:index` higher than 2.13.0 are supported. Parameters ----------- session: Optional[`requests.Session <http://docs.python-requests.org/en/latest/api/#requests.Session>`_] The requests session to use for sending requests. If not given then each request will create a new session. Note if a session is given, the webhook adapter **will not** clean it up for you. You must close the session yourself. sleep: :class:`bool` Whether to sleep the thread when encountering a 429 or pre-emptive rate limit or a 5xx status code. Defaults to ``True``. If set to ``False`` then this will raise an :exc:`HTTPException` instead. """ def __init__(self, session=None, *, sleep=True): import requests self.session = session or requests self.sleep = sleep def request(self, verb, url, payload=None, multipart=None, *, files=None, reason=None): headers = {} data = None files = files or [] if payload: headers['Content-Type'] = 'application/json' data = utils.to_json(payload) if reason: headers['X-Audit-Log-Reason'] = _uriquote(reason, safe='/ ') if multipart is not None: data = {'payload_json': multipart.pop('payload_json')} base_url = url.replace(self._request_url, '/') or '/' _id = self._webhook_id for tries in range(5): for file in files: file.reset(seek=tries) r = self.session.request(verb, url, headers=headers, data=data, files=multipart) r.encoding = 'utf-8' # Coerce empty responses to return None for hygiene purposes response = r.text or None # compatibility with aiohttp r.status = r.status_code log.debug('Webhook ID %s with %s %s has returned status code %s', _id, verb, base_url, r.status) if r.headers['Content-Type'] == 'application/json': response = json.loads(response) # check if we have rate limit header information remaining = r.headers.get('X-Ratelimit-Remaining') if remaining == '0' and r.status != 429 and self.sleep: delta = utils._parse_ratelimit_header(r) log.debug('Webhook ID %s has been pre-emptively rate limited, waiting %.2f seconds', _id, delta) time.sleep(delta) if 300 > r.status >= 200: return response # we are being rate limited if r.status == 429: if self.sleep: if not r.headers.get('Via'): # Banned by Cloudflare more than likely. raise HTTPException(r, data) retry_after = response['retry_after'] / 1000.0 log.warning('Webhook ID %s is rate limited. Retrying in %.2f seconds', _id, retry_after) time.sleep(retry_after) continue else: raise HTTPException(r, response) if self.sleep and r.status in (500, 502): time.sleep(1 + tries * 2) continue if r.status == 403: raise Forbidden(r, response) elif r.status == 404: raise NotFound(r, response) else: raise HTTPException(r, response) # no more retries if r.status >= 500: raise DiscordServerError(r, response) raise HTTPException(r, response) def handle_execution_response(self, response, *, wait): if not wait: return response # transform into Message object # Make sure to coerce the state to the partial one to allow message edits/delete state = _PartialWebhookState(self, self.webhook, parent=self.webhook._state) return WebhookMessage(data=response, state=state, channel=self.webhook.channel) class _FriendlyHttpAttributeErrorHelper: __slots__ = () def __getattr__(self, attr): raise AttributeError('PartialWebhookState does not support http methods.') class _PartialWebhookState: __slots__ = ('loop', 'parent', '_webhook') def __init__(self, adapter, webhook, parent): self._webhook = webhook if isinstance(parent, self.__class__): self.parent = None else: self.parent = parent # Fetch the loop from the adapter if it's there try: self.loop = adapter.loop except AttributeError: self.loop = None def _get_guild(self, guild_id): return None def store_user(self, data): return BaseUser(state=self, data=data) @property def is_bot(self): return True @property def http(self): if self.parent is not None: return self.parent.http # Some data classes assign state.http and that should be kosher # however, using it should result in a late-binding error. return _FriendlyHttpAttributeErrorHelper() def __getattr__(self, attr): if self.parent is not None: return getattr(self.parent, attr) raise AttributeError('PartialWebhookState does not support {0!r}.'.format(attr)) class WebhookMessage(Message): """Represents a message sent from your webhook. This allows you to edit or delete a message sent by your webhook. This inherits from :class:`discord.Message` with changes to :meth:`edit` and :meth:`delete` to work. .. versionadded:: 1.6 """ def edit(self, **fields): """|maybecoro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. .. versionadded:: 1.6 Parameters ------------ content: Optional[:class:`str`] The content to edit the message with or ``None`` to clear it. embeds: List[:class:`Embed`] A list of embeds to edit the message with. embed: Optional[:class:`Embed`] The embed to edit the message with. ``None`` suppresses the embeds. This should not be mixed with the ``embeds`` parameter. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. Raises ------- HTTPException Editing the message failed. Forbidden Edited a message that is not yours. InvalidArgument You specified both ``embed`` and ``embeds`` or the length of ``embeds`` was invalid or there was no token associated with this webhook. """ return self._state._webhook.edit_message(self.id, **fields) def _delete_delay_sync(self, delay): time.sleep(delay) return self._state._webhook.delete_message(self.id) async def _delete_delay_async(self, delay): async def inner_call(): await asyncio.sleep(delay) try: await self._state._webhook.delete_message(self.id) except HTTPException: pass asyncio.ensure_future(inner_call(), loop=self._state.loop) return await asyncio.sleep(0) def delete(self, *, delay=None): """|coro| Deletes the message. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait before deleting the message. If this is a coroutine, the waiting is done in the background and deletion failures are ignored. If this is not a coroutine then the delay blocks the thread. Raises ------ Forbidden You do not have proper permissions to delete the message. NotFound The message was deleted already. HTTPException Deleting the message failed. """ if delay is not None: if self._state._webhook._adapter.is_async(): return self._delete_delay_async(delay) else: return self._delete_delay_sync(delay) return self._state._webhook.delete_message(self.id) class Webhook(Hashable): """Represents a Discord webhook. Webhooks are a form to send messages to channels in Discord without a bot user or authentication. There are two main ways to use Webhooks. The first is through the ones received by the library such as :meth:`.Guild.webhooks` and :meth:`.TextChannel.webhooks`. The ones received by the library will automatically have an adapter bound using the library's HTTP session. Those webhooks will have :meth:`~.Webhook.send`, :meth:`~.Webhook.delete` and :meth:`~.Webhook.edit` as coroutines. The second form involves creating a webhook object manually without having it bound to a websocket connection using the :meth:`~.Webhook.from_url` or :meth:`~.Webhook.partial` classmethods. This form allows finer grained control over how requests are done, allowing you to mix async and sync code using either :doc:`aiohttp <aio:index>` or :doc:`req:index`. For example, creating a webhook from a URL and using :doc:`aiohttp <aio:index>`: .. code-block:: python3 from discord import Webhook, AsyncWebhookAdapter import aiohttp async def foo(): async with aiohttp.ClientSession() as session: webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session)) await webhook.send('Hello World', username='Foo') Or creating a webhook from an ID and token and using :doc:`req:index`: .. code-block:: python3 import requests from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter()) webhook.send('Hello World', username='Foo') .. container:: operations .. describe:: x == y Checks if two webhooks are equal. .. describe:: x != y Checks if two webhooks are not equal. .. describe:: hash(x) Returns the webhooks's hash. .. versionchanged:: 1.4 Webhooks are now comparable and hashable. Attributes ------------ id: :class:`int` The webhook's ID type: :class:`WebhookType` The type of the webhook. .. versionadded:: 1.3 token: Optional[:class:`str`] The authentication token of the webhook. If this is ``None`` then the webhook cannot be used to make requests. guild_id: Optional[:class:`int`] The guild ID this webhook is for. channel_id: Optional[:class:`int`] The channel ID this webhook is for. user: Optional[:class:`abc.User`] The user this webhook was created by. If the webhook was received without authentication then this will be ``None``. name: Optional[:class:`str`] The default name of the webhook. avatar: Optional[:class:`str`] The default avatar of the webhook. """ __slots__ = ('id', 'type', 'guild_id', 'channel_id', 'user', 'name', 'avatar', 'token', '_state', '_adapter') def __init__(self, data, *, adapter, state=None): self.id = int(data['id']) self.type = try_enum(WebhookType, int(data['type'])) self.channel_id = utils._get_as_snowflake(data, 'channel_id') self.guild_id = utils._get_as_snowflake(data, 'guild_id') self.name = data.get('name') self.avatar = data.get('avatar') self.token = data.get('token') self._state = state or _PartialWebhookState(adapter, self, parent=state) self._adapter = adapter self._adapter._prepare(self) user = data.get('user') if user is None: self.user = None elif state is None: self.user = BaseUser(state=None, data=user) else: self.user = User(state=state, data=user) def __repr__(self): return '<Webhook id=%r>' % self.id @property def url(self): """:class:`str` : Returns the webhook's url.""" return 'https://discord.com/api/webhooks/{}/{}'.format(self.id, self.token) @classmethod def partial(cls, id, token, *, adapter): """Creates a partial :class:`Webhook`. Parameters ----------- id: :class:`int` The ID of the webhook. token: :class:`str` The authentication token of the webhook. adapter: :class:`WebhookAdapter` The webhook adapter to use when sending requests. This is typically :class:`AsyncWebhookAdapter` for :doc:`aiohttp <aio:index>` or :class:`RequestsWebhookAdapter` for :doc:`req:index`. Returns -------- :class:`Webhook` A partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. """ if not isinstance(adapter, WebhookAdapter): raise TypeError('adapter must be a subclass of WebhookAdapter') data = { 'id': id, 'type': 1, 'token': token } return cls(data, adapter=adapter) @classmethod def from_url(cls, url, *, adapter): """Creates a partial :class:`Webhook` from a webhook URL. Parameters ------------ url: :class:`str` The URL of the webhook. adapter: :class:`WebhookAdapter` The webhook adapter to use when sending requests. This is typically :class:`AsyncWebhookAdapter` for :doc:`aiohttp <aio:index>` or :class:`RequestsWebhookAdapter` for :doc:`req:index`. Raises ------- InvalidArgument The URL is invalid. Returns -------- :class:`Webhook` A partial :class:`Webhook`. A partial webhook is just a webhook object with an ID and a token. """ m = re.search(r'discord(?:app)?.com/api/webhooks/(?P<id>[0-9]{17,20})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url) if m is None: raise InvalidArgument('Invalid webhook URL given.') data = m.groupdict() data['type'] = 1 return cls(data, adapter=adapter) @classmethod def _as_follower(cls, data, *, channel, user): name = "{} #{}".format(channel.guild, channel) feed = { 'id': data['webhook_id'], 'type': 2, 'name': name, 'channel_id': channel.id, 'guild_id': channel.guild.id, 'user': { 'username': user.name, 'discriminator': user.discriminator, 'id': user.id, 'avatar': user.avatar } } session = channel._state.http._HTTPClient__session return cls(feed, adapter=AsyncWebhookAdapter(session=session)) @classmethod def from_state(cls, data, state): session = state.http._HTTPClient__session return cls(data, adapter=AsyncWebhookAdapter(session=session), state=state) @property def guild(self): """Optional[:class:`Guild`]: The guild this webhook belongs to. If this is a partial webhook, then this will always return ``None``. """ return self._state._get_guild(self.guild_id) @property def channel(self): """Optional[:class:`TextChannel`]: The text channel this webhook belongs to. If this is a partial webhook, then this will always return ``None``. """ guild = self.guild return guild and guild.get_channel(self.channel_id) @property def created_at(self): """:class:`datetime.datetime`: Returns the webhook's creation time in UTC.""" return utils.snowflake_time(self.id) @property def avatar_url(self): """:class:`Asset`: Returns an :class:`Asset` for the avatar the webhook has. If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead. This is equivalent to calling :meth:`avatar_url_as` with the default parameters. """ return self.avatar_url_as() def avatar_url_as(self, *, format=None, size=1024): """Returns an :class:`Asset` for the avatar the webhook has. If the webhook does not have a traditional avatar, an asset for the default avatar is returned instead. The format must be one of 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 1024. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is equivalent to png. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ if self.avatar is None: # Default is always blurple apparently return Asset(self._state, '/embed/avatars/0.png') if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 1024") format = format or 'png' if format not in ('png', 'jpg', 'jpeg'): raise InvalidArgument("format must be one of 'png', 'jpg', or 'jpeg'.") url = '/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(self, format, size) return Asset(self._state, url) def delete(self, *, reason=None): """|maybecoro| Deletes this Webhook. If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is not a coroutine. Parameters ------------ reason: Optional[:class:`str`] The reason for deleting this webhook. Shows up on the audit log. .. versionadded:: 1.4 Raises ------- HTTPException Deleting the webhook failed. NotFound This webhook does not exist. Forbidden You do not have permissions to delete this webhook. InvalidArgument This webhook does not have a token associated with it. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') return self._adapter.delete_webhook(reason=reason) def edit(self, *, reason=None, **kwargs): """|maybecoro| Edits this Webhook. If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is not a coroutine. Parameters ------------ name: Optional[:class:`str`] The webhook's new default name. avatar: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the webhook's new default avatar. reason: Optional[:class:`str`] The reason for editing this webhook. Shows up on the audit log. .. versionadded:: 1.4 Raises ------- HTTPException Editing the webhook failed. NotFound This webhook does not exist. InvalidArgument This webhook does not have a token associated with it. """ if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') payload = {} try: name = kwargs['name'] except KeyError: pass else: if name is not None: payload['name'] = str(name) else: payload['name'] = None try: avatar = kwargs['avatar'] except KeyError: pass else: if avatar is not None: payload['avatar'] = utils._bytes_to_base64_data(avatar) else: payload['avatar'] = None return self._adapter.edit_webhook(reason=reason, **payload) def send(self, content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None, allowed_mentions=None): """|maybecoro| Sends a message using the webhook. If the webhook is constructed with a :class:`RequestsWebhookAdapter` then this is not a coroutine. The content must be a type that can convert to a string through ``str(content)``. To upload a single file, the ``file`` parameter should be used with a single :class:`File` object. If the ``embed`` parameter is provided, it must be of type :class:`Embed` and it must be a rich embed type. You cannot mix the ``embed`` parameter with the ``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send. Parameters ------------ content: :class:`str` The content of the message to send. wait: :class:`bool` Whether the server should wait before sending a response. This essentially means that the return type of this function changes from ``None`` to a :class:`WebhookMessage` if set to ``True``. username: :class:`str` The username to send with this message. If no username is provided then the default username for the webhook is used. avatar_url: Union[:class:`str`, :class:`Asset`] The avatar URL to send with this message. If no avatar URL is provided then the default avatar for the webhook is used. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. file: :class:`File` The file to upload. This cannot be mixed with ``files`` parameter. files: List[:class:`File`] A list of files to send with the content. This cannot be mixed with the ``file`` parameter. embed: :class:`Embed` The rich embed for the content to send. This cannot be mixed with ``embeds`` parameter. embeds: List[:class:`Embed`] A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the ``embed`` parameter. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. .. versionadded:: 1.4 Raises -------- HTTPException Sending the message failed. NotFound This webhook was not found. Forbidden The authorization token for the webhook is incorrect. InvalidArgument You specified both ``embed`` and ``embeds`` or the length of ``embeds`` was invalid or there was no token associated with this webhook. Returns --------- Optional[:class:`WebhookMessage`] The message that was sent. """ payload = {} if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') if files is not None and file is not None: raise InvalidArgument('Cannot mix file and files keyword arguments.') if embeds is not None and embed is not None: raise InvalidArgument('Cannot mix embed and embeds keyword arguments.') if embeds is not None: if len(embeds) > 10: raise InvalidArgument('embeds has a maximum of 10 elements.') payload['embeds'] = [e.to_dict() for e in embeds] if embed is not None: payload['embeds'] = [embed.to_dict()] if content is not None: payload['content'] = str(content) payload['tts'] = tts if avatar_url: payload['avatar_url'] = str(avatar_url) if username: payload['username'] = username previous_mentions = getattr(self._state, 'allowed_mentions', None) if allowed_mentions: if previous_mentions is not None: payload['allowed_mentions'] = previous_mentions.merge(allowed_mentions).to_dict() else: payload['allowed_mentions'] = allowed_mentions.to_dict() elif previous_mentions is not None: payload['allowed_mentions'] = previous_mentions.to_dict() return self._adapter.execute_webhook(wait=wait, file=file, files=files, payload=payload) def execute(self, *args, **kwargs): """An alias for :meth:`~.Webhook.send`.""" return self.send(*args, **kwargs) def edit_message(self, message_id, **fields): """|maybecoro| Edits a message owned by this webhook. This is a lower level interface to :meth:`WebhookMessage.edit` in case you only have an ID. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to edit. content: Optional[:class:`str`] The content to edit the message with or ``None`` to clear it. embeds: List[:class:`Embed`] A list of embeds to edit the message with. embed: Optional[:class:`Embed`] The embed to edit the message with. ``None`` suppresses the embeds. This should not be mixed with the ``embeds`` parameter. allowed_mentions: :class:`AllowedMentions` Controls the mentions being processed in this message. See :meth:`.abc.Messageable.send` for more information. Raises ------- HTTPException Editing the message failed. Forbidden Edited a message that is not yours. InvalidArgument You specified both ``embed`` and ``embeds`` or the length of ``embeds`` was invalid or there was no token associated with this webhook. """ payload = {} if self.token is None: raise InvalidArgument('This webhook does not have a token associated with it') try: content = fields['content'] except KeyError: pass else: if content is not None: content = str(content) payload['content'] = content # Check if the embeds interface is being used try: embeds = fields['embeds'] except KeyError: # Nope pass else: if embeds is None or len(embeds) > 10: raise InvalidArgument('embeds has a maximum of 10 elements') payload['embeds'] = [e.to_dict() for e in embeds] try: embed = fields['embed'] except KeyError: pass else: if 'embeds' in payload: raise InvalidArgument('Cannot mix embed and embeds keyword arguments') if embed is None: payload['embeds'] = [] else: payload['embeds'] = [embed.to_dict()] allowed_mentions = fields.pop('allowed_mentions', None) previous_mentions = getattr(self._state, 'allowed_mentions', None) if allowed_mentions: if previous_mentions is not None: payload['allowed_mentions'] = previous_mentions.merge(allowed_mentions).to_dict() else: payload['allowed_mentions'] = allowed_mentions.to_dict() elif previous_mentions is not None: payload['allowed_mentions'] = previous_mentions.to_dict() return self._adapter.edit_webhook_message(message_id, payload=payload) def delete_message(self, message_id): """|maybecoro| Deletes a message owned by this webhook. This is a lower level interface to :meth:`WebhookMessage.delete` in case you only have an ID. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to delete. Raises ------- HTTPException Deleting the message failed. Forbidden Deleted a message that is not yours. """ return self._adapter.delete_webhook_message(message_id)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/webhook.py
webhook.py
import io from .errors import DiscordException from .errors import InvalidArgument from . import utils VALID_STATIC_FORMATS = frozenset({"jpeg", "jpg", "webp", "png"}) VALID_AVATAR_FORMATS = VALID_STATIC_FORMATS | {"gif"} class Asset: """Represents a CDN asset on Discord. .. container:: operations .. describe:: str(x) Returns the URL of the CDN asset. .. describe:: len(x) Returns the length of the CDN asset's URL. .. describe:: bool(x) Checks if the Asset has a URL. .. describe:: x == y Checks if the asset is equal to another asset. .. describe:: x != y Checks if the asset is not equal to another asset. .. describe:: hash(x) Returns the hash of the asset. """ __slots__ = ('_state', '_url') BASE = 'https://cdn.discordapp.com' def __init__(self, state, url=None): self._state = state self._url = url @classmethod def _from_avatar(cls, state, user, *, format=None, static_format='webp', size=1024): if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 4096") if format is not None and format not in VALID_AVATAR_FORMATS: raise InvalidArgument("format must be None or one of {}".format(VALID_AVATAR_FORMATS)) if format == "gif" and not user.is_avatar_animated(): raise InvalidArgument("non animated avatars do not support gif format") if static_format not in VALID_STATIC_FORMATS: raise InvalidArgument("static_format must be one of {}".format(VALID_STATIC_FORMATS)) if user.avatar is None: return user.default_avatar_url if format is None: format = 'gif' if user.is_avatar_animated() else static_format return cls(state, '/avatars/{0.id}/{0.avatar}.{1}?size={2}'.format(user, format, size)) @classmethod def _from_icon(cls, state, object, path, *, format='webp', size=1024): if object.icon is None: return cls(state) if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 4096") if format not in VALID_STATIC_FORMATS: raise InvalidArgument("format must be None or one of {}".format(VALID_STATIC_FORMATS)) url = '/{0}-icons/{1.id}/{1.icon}.{2}?size={3}'.format(path, object, format, size) return cls(state, url) @classmethod def _from_cover_image(cls, state, obj, *, format='webp', size=1024): if obj.cover_image is None: return cls(state) if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 4096") if format not in VALID_STATIC_FORMATS: raise InvalidArgument("format must be None or one of {}".format(VALID_STATIC_FORMATS)) url = '/app-assets/{0.id}/store/{0.cover_image}.{1}?size={2}'.format(obj, format, size) return cls(state, url) @classmethod def _from_guild_image(cls, state, id, hash, key, *, format='webp', size=1024): if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 4096") if format not in VALID_STATIC_FORMATS: raise InvalidArgument("format must be one of {}".format(VALID_STATIC_FORMATS)) if hash is None: return cls(state) url = '/{key}/{0}/{1}.{2}?size={3}' return cls(state, url.format(id, hash, format, size, key=key)) @classmethod def _from_guild_icon(cls, state, guild, *, format=None, static_format='webp', size=1024): if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 4096") if format is not None and format not in VALID_AVATAR_FORMATS: raise InvalidArgument("format must be one of {}".format(VALID_AVATAR_FORMATS)) if format == "gif" and not guild.is_icon_animated(): raise InvalidArgument("non animated guild icons do not support gif format") if static_format not in VALID_STATIC_FORMATS: raise InvalidArgument("static_format must be one of {}".format(VALID_STATIC_FORMATS)) if guild.icon is None: return cls(state) if format is None: format = 'gif' if guild.is_icon_animated() else static_format return cls(state, '/icons/{0.id}/{0.icon}.{1}?size={2}'.format(guild, format, size)) @classmethod def _from_sticker_url(cls, state, sticker, *, size=1024): if not utils.valid_icon_size(size): raise InvalidArgument("size must be a power of 2 between 16 and 4096") return cls(state, '/stickers/{0.id}/{0.image}.png?size={2}'.format(sticker, format, size)) @classmethod def _from_emoji(cls, state, emoji, *, format=None, static_format='png'): if format is not None and format not in VALID_AVATAR_FORMATS: raise InvalidArgument("format must be None or one of {}".format(VALID_AVATAR_FORMATS)) if format == "gif" and not emoji.animated: raise InvalidArgument("non animated emoji's do not support gif format") if static_format not in VALID_STATIC_FORMATS: raise InvalidArgument("static_format must be one of {}".format(VALID_STATIC_FORMATS)) if format is None: format = 'gif' if emoji.animated else static_format return cls(state, '/emojis/{0.id}.{1}'.format(emoji, format)) def __str__(self): return self.BASE + self._url if self._url is not None else '' def __len__(self): if self._url: return len(self.BASE + self._url) return 0 def __bool__(self): return self._url is not None def __repr__(self): return '<Asset url={0._url!r}>'.format(self) def __eq__(self, other): return isinstance(other, Asset) and self._url == other._url def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self._url) async def read(self): """|coro| Retrieves the content of this asset as a :class:`bytes` object. .. warning:: :class:`PartialEmoji` won't have a connection state if user created, and a URL won't be present if a custom image isn't associated with the asset, e.g. a guild with no custom icon. .. versionadded:: 1.1 Raises ------ DiscordException There was no valid URL or internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns ------- :class:`bytes` The content of the asset. """ if not self._url: raise DiscordException('Invalid asset (no URL provided)') if self._state is None: raise DiscordException('Invalid state (no ConnectionState provided)') return await self._state.http.get_from_cdn(self.BASE + self._url) async def save(self, fp, *, seek_begin=True): """|coro| Saves this asset into a file-like object. Parameters ---------- fp: Union[BinaryIO, :class:`os.PathLike`] Same as in :meth:`Attachment.save`. seek_begin: :class:`bool` Same as in :meth:`Attachment.save`. Raises ------ DiscordException There was no valid URL or internal connection state. HTTPException Downloading the asset failed. NotFound The asset was deleted. Returns -------- :class:`int` The number of bytes written. """ data = await self.read() if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/asset.py
asset.py
import array import ctypes import ctypes.util import logging import math import os.path import struct import sys from .errors import DiscordException log = logging.getLogger(__name__) c_int_ptr = ctypes.POINTER(ctypes.c_int) c_int16_ptr = ctypes.POINTER(ctypes.c_int16) c_float_ptr = ctypes.POINTER(ctypes.c_float) _lib = None class EncoderStruct(ctypes.Structure): pass class DecoderStruct(ctypes.Structure): pass EncoderStructPtr = ctypes.POINTER(EncoderStruct) DecoderStructPtr = ctypes.POINTER(DecoderStruct) ## Some constants from opus_defines.h # Error codes OK = 0 BAD_ARG = -1 # Encoder CTLs APPLICATION_AUDIO = 2049 APPLICATION_VOIP = 2048 APPLICATION_LOWDELAY = 2051 CTL_SET_BITRATE = 4002 CTL_SET_BANDWIDTH = 4008 CTL_SET_FEC = 4012 CTL_SET_PLP = 4014 CTL_SET_SIGNAL = 4024 # Decoder CTLs CTL_SET_GAIN = 4034 CTL_LAST_PACKET_DURATION = 4039 band_ctl = { 'narrow': 1101, 'medium': 1102, 'wide': 1103, 'superwide': 1104, 'full': 1105, } signal_ctl = { 'auto': -1000, 'voice': 3001, 'music': 3002, } def _err_lt(result, func, args): if result < OK: log.info('error has happened in %s', func.__name__) raise OpusError(result) return result def _err_ne(result, func, args): ret = args[-1]._obj if ret.value != OK: log.info('error has happened in %s', func.__name__) raise OpusError(ret.value) return result # A list of exported functions. # The first argument is obviously the name. # The second one are the types of arguments it takes. # The third is the result type. # The fourth is the error handler. exported_functions = [ # Generic ('opus_get_version_string', None, ctypes.c_char_p, None), ('opus_strerror', [ctypes.c_int], ctypes.c_char_p, None), # Encoder functions ('opus_encoder_get_size', [ctypes.c_int], ctypes.c_int, None), ('opus_encoder_create', [ctypes.c_int, ctypes.c_int, ctypes.c_int, c_int_ptr], EncoderStructPtr, _err_ne), ('opus_encode', [EncoderStructPtr, c_int16_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt), ('opus_encode_float', [EncoderStructPtr, c_float_ptr, ctypes.c_int, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int32, _err_lt), ('opus_encoder_ctl', None, ctypes.c_int32, _err_lt), ('opus_encoder_destroy', [EncoderStructPtr], None, None), # Decoder functions ('opus_decoder_get_size', [ctypes.c_int], ctypes.c_int, None), ('opus_decoder_create', [ctypes.c_int, ctypes.c_int, c_int_ptr], DecoderStructPtr, _err_ne), ('opus_decode', [DecoderStructPtr, ctypes.c_char_p, ctypes.c_int32, c_int16_ptr, ctypes.c_int, ctypes.c_int], ctypes.c_int, _err_lt), ('opus_decode_float', [DecoderStructPtr, ctypes.c_char_p, ctypes.c_int32, c_float_ptr, ctypes.c_int, ctypes.c_int], ctypes.c_int, _err_lt), ('opus_decoder_ctl', None, ctypes.c_int32, _err_lt), ('opus_decoder_destroy', [DecoderStructPtr], None, None), ('opus_decoder_get_nb_samples', [DecoderStructPtr, ctypes.c_char_p, ctypes.c_int32], ctypes.c_int, _err_lt), # Packet functions ('opus_packet_get_bandwidth', [ctypes.c_char_p], ctypes.c_int, _err_lt), ('opus_packet_get_nb_channels', [ctypes.c_char_p], ctypes.c_int, _err_lt), ('opus_packet_get_nb_frames', [ctypes.c_char_p, ctypes.c_int], ctypes.c_int, _err_lt), ('opus_packet_get_samples_per_frame', [ctypes.c_char_p, ctypes.c_int], ctypes.c_int, _err_lt), ] def libopus_loader(name): # create the library... lib = ctypes.cdll.LoadLibrary(name) # register the functions... for item in exported_functions: func = getattr(lib, item[0]) try: if item[1]: func.argtypes = item[1] func.restype = item[2] except KeyError: pass try: if item[3]: func.errcheck = item[3] except KeyError: log.exception("Error assigning check function to %s", func) return lib def _load_default(): global _lib try: if sys.platform == 'win32': _basedir = os.path.dirname(os.path.abspath(__file__)) _bitness = struct.calcsize('P') * 8 _target = 'x64' if _bitness > 32 else 'x86' _filename = os.path.join(_basedir, 'bin', 'libopus-0.{}.dll'.format(_target)) _lib = libopus_loader(_filename) else: _lib = libopus_loader(ctypes.util.find_library('opus')) except Exception: _lib = None return _lib is not None def load_opus(name): """Loads the libopus shared library for use with voice. If this function is not called then the library uses the function :func:`ctypes.util.find_library` and then loads that one if available. Not loading a library and attempting to use PCM based AudioSources will lead to voice not working. This function propagates the exceptions thrown. .. warning:: The bitness of the library must match the bitness of your python interpreter. If the library is 64-bit then your python interpreter must be 64-bit as well. Usually if there's a mismatch in bitness then the load will throw an exception. .. note:: On Windows, this function should not need to be called as the binaries are automatically loaded. .. note:: On Windows, the .dll extension is not necessary. However, on Linux the full extension is required to load the library, e.g. ``libopus.so.1``. On Linux however, :func:`ctypes.util.find_library` will usually find the library automatically without you having to call this. Parameters ---------- name: :class:`str` The filename of the shared library. """ global _lib _lib = libopus_loader(name) def is_loaded(): """Function to check if opus lib is successfully loaded either via the :func:`ctypes.util.find_library` call of :func:`load_opus`. This must return ``True`` for voice to work. Returns ------- :class:`bool` Indicates if the opus library has been loaded. """ global _lib return _lib is not None class OpusError(DiscordException): """An exception that is thrown for libopus related errors. Attributes ---------- code: :class:`int` The error code returned. """ def __init__(self, code): self.code = code msg = _lib.opus_strerror(self.code).decode('utf-8') log.info('"%s" has happened', msg) super().__init__(msg) class OpusNotLoaded(DiscordException): """An exception that is thrown for when libopus is not loaded.""" pass class _OpusStruct: SAMPLING_RATE = 48000 CHANNELS = 2 FRAME_LENGTH = 20 # in milliseconds SAMPLE_SIZE = struct.calcsize('h') * CHANNELS SAMPLES_PER_FRAME = int(SAMPLING_RATE / 1000 * FRAME_LENGTH) FRAME_SIZE = SAMPLES_PER_FRAME * SAMPLE_SIZE @staticmethod def get_opus_version() -> str: if not is_loaded() and not _load_default(): raise OpusNotLoaded() return _lib.opus_get_version_string().decode('utf-8') class Encoder(_OpusStruct): def __init__(self, application=APPLICATION_AUDIO): _OpusStruct.get_opus_version() self.application = application self._state = self._create_state() self.set_bitrate(128) self.set_fec(True) self.set_expected_packet_loss_percent(0.15) self.set_bandwidth('full') self.set_signal_type('auto') def __del__(self): if hasattr(self, '_state'): _lib.opus_encoder_destroy(self._state) self._state = None def _create_state(self): ret = ctypes.c_int() return _lib.opus_encoder_create(self.SAMPLING_RATE, self.CHANNELS, self.application, ctypes.byref(ret)) def set_bitrate(self, kbps): kbps = min(512, max(16, int(kbps))) _lib.opus_encoder_ctl(self._state, CTL_SET_BITRATE, kbps * 1024) return kbps def set_bandwidth(self, req): if req not in band_ctl: raise KeyError('%r is not a valid bandwidth setting. Try one of: %s' % (req, ','.join(band_ctl))) k = band_ctl[req] _lib.opus_encoder_ctl(self._state, CTL_SET_BANDWIDTH, k) def set_signal_type(self, req): if req not in signal_ctl: raise KeyError('%r is not a valid signal setting. Try one of: %s' % (req, ','.join(signal_ctl))) k = signal_ctl[req] _lib.opus_encoder_ctl(self._state, CTL_SET_SIGNAL, k) def set_fec(self, enabled=True): _lib.opus_encoder_ctl(self._state, CTL_SET_FEC, 1 if enabled else 0) def set_expected_packet_loss_percent(self, percentage): _lib.opus_encoder_ctl(self._state, CTL_SET_PLP, min(100, max(0, int(percentage * 100)))) def encode(self, pcm, frame_size): max_data_bytes = len(pcm) pcm = ctypes.cast(pcm, c_int16_ptr) data = (ctypes.c_char * max_data_bytes)() ret = _lib.opus_encode(self._state, pcm, frame_size, data, max_data_bytes) return array.array('b', data[:ret]).tobytes() class Decoder(_OpusStruct): def __init__(self): _OpusStruct.get_opus_version() self._state = self._create_state() def __del__(self): if hasattr(self, '_state'): _lib.opus_decoder_destroy(self._state) self._state = None def _create_state(self): ret = ctypes.c_int() return _lib.opus_decoder_create(self.SAMPLING_RATE, self.CHANNELS, ctypes.byref(ret)) @staticmethod def packet_get_nb_frames(data): """Gets the number of frames in an Opus packet""" return _lib.opus_packet_get_nb_frames(data, len(data)) @staticmethod def packet_get_nb_channels(data): """Gets the number of channels in an Opus packet""" return _lib.opus_packet_get_nb_channels(data) @classmethod def packet_get_samples_per_frame(cls, data): """Gets the number of samples per frame from an Opus packet""" return _lib.opus_packet_get_samples_per_frame(data, cls.SAMPLING_RATE) def _set_gain(self, adjustment): """Configures decoder gain adjustment. Scales the decoded output by a factor specified in Q8 dB units. This has a maximum range of -32768 to 32767 inclusive, and returns OPUS_BAD_ARG (-1) otherwise. The default is zero indicating no adjustment. This setting survives decoder reset (irrelevant for now). gain = 10**x/(20.0*256) (from opus_defines.h) """ return _lib.opus_decoder_ctl(self._state, CTL_SET_GAIN, adjustment) def set_gain(self, dB): """Sets the decoder gain in dB, from -128 to 128.""" dB_Q8 = max(-32768, min(32767, round(dB * 256))) # dB * 2^n where n is 8 (Q8) return self._set_gain(dB_Q8) def set_volume(self, mult): """Sets the output volume as a float percent, i.e. 0.5 for 50%, 1.75 for 175%, etc.""" return self.set_gain(20 * math.log10(mult)) # amplitude ratio def _get_last_packet_duration(self): """Gets the duration (in samples) of the last packet successfully decoded or concealed.""" ret = ctypes.c_int32() _lib.opus_decoder_ctl(self._state, CTL_LAST_PACKET_DURATION, ctypes.byref(ret)) return ret.value def decode(self, data, *, fec=False): if data is None and fec: raise OpusError("Invalid arguments: FEC cannot be used with null data") if data is None: frame_size = self._get_last_packet_duration() or self.SAMPLES_PER_FRAME channel_count = self.CHANNELS else: frames = self.packet_get_nb_frames(data) channel_count = self.packet_get_nb_channels(data) samples_per_frame = self.packet_get_samples_per_frame(data) frame_size = frames * samples_per_frame pcm = (ctypes.c_int16 * (frame_size * channel_count))() pcm_ptr = ctypes.cast(pcm, c_int16_ptr) ret = _lib.opus_decode(self._state, data, len(data) if data else 0, pcm_ptr, frame_size, fec) return array.array('h', pcm[:ret * channel_count]).tobytes()
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/opus.py
opus.py
import argparse import sys from pathlib import Path import discord import pkg_resources import aiohttp import platform def show_version(): entries = [] entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info)) version_info = discord.version_info entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info)) if version_info.releaselevel != 'final': pkg = pkg_resources.get_distribution('discord.py') if pkg: entries.append(' - discord.py pkg_resources: v{0}'.format(pkg.version)) entries.append('- aiohttp v{0.__version__}'.format(aiohttp)) uname = platform.uname() entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname)) print('\n'.join(entries)) def core(parser, args): if args.version: show_version() bot_template = """#!/usr/bin/env python3 # -*- coding: utf-8 -*- from discord.ext import commands import discord import config class Bot(commands.{base}): def __init__(self, **kwargs): super().__init__(command_prefix=commands.when_mentioned_or('{prefix}'), **kwargs) for cog in config.cogs: try: self.load_extension(cog) except Exception as exc: print('Could not load extension {{0}} due to {{1.__class__.__name__}}: {{1}}'.format(cog, exc)) async def on_ready(self): print('Logged on as {{0}} (ID: {{0.id}})'.format(self.user)) bot = Bot() # write general commands here bot.run(config.token) """ gitignore_template = """# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # Our configuration files config.py """ cog_template = '''# -*- coding: utf-8 -*- from discord.ext import commands import discord class {name}(commands.Cog{attrs}): """The description for {name} goes here.""" def __init__(self, bot): self.bot = bot {extra} def setup(bot): bot.add_cog({name}(bot)) ''' cog_extras = ''' def cog_unload(self): # clean up logic goes here pass async def cog_check(self, ctx): # checks that apply to every command in here return True async def bot_check(self, ctx): # checks that apply to every command to the bot return True async def bot_check_once(self, ctx): # check that apply to every command but is guaranteed to be called only once return True async def cog_command_error(self, ctx, error): # error handling to every command in here pass async def cog_before_invoke(self, ctx): # called before a command is called here pass async def cog_after_invoke(self, ctx): # called after a command is called here pass ''' # certain file names and directory names are forbidden # see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx # although some of this doesn't apply to Linux, we might as well be consistent _base_table = { '<': '-', '>': '-', ':': '-', '"': '-', # '/': '-', these are fine # '\\': '-', '|': '-', '?': '-', '*': '-', } # NUL (0) and 1-31 are disallowed _base_table.update((chr(i), None) for i in range(32)) translation_table = str.maketrans(_base_table) def to_path(parser, name, *, replace_spaces=False): if isinstance(name, Path): return name if sys.platform == 'win32': forbidden = ('CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', \ 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9') if len(name) <= 4 and name.upper() in forbidden: parser.error('invalid directory name given, use a different one') name = name.translate(translation_table) if replace_spaces: name = name.replace(' ', '-') return Path(name) def newbot(parser, args): new_directory = to_path(parser, args.directory) / to_path(parser, args.name) # as a note exist_ok for Path is a 3.5+ only feature # since we already checked above that we're >3.5 try: new_directory.mkdir(exist_ok=True, parents=True) except OSError as exc: parser.error('could not create our bot directory ({})'.format(exc)) cogs = new_directory / 'cogs' try: cogs.mkdir(exist_ok=True) init = cogs / '__init__.py' init.touch() except OSError as exc: print('warning: could not create cogs directory ({})'.format(exc)) try: with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp: fp.write('token = "place your token here"\ncogs = []\n') except OSError as exc: parser.error('could not create config file ({})'.format(exc)) try: with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp: base = 'Bot' if not args.sharded else 'AutoShardedBot' fp.write(bot_template.format(base=base, prefix=args.prefix)) except OSError as exc: parser.error('could not create bot file ({})'.format(exc)) if not args.no_git: try: with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp: fp.write(gitignore_template) except OSError as exc: print('warning: could not create .gitignore file ({})'.format(exc)) print('successfully made bot at', new_directory) def newcog(parser, args): cog_dir = to_path(parser, args.directory) try: cog_dir.mkdir(exist_ok=True) except OSError as exc: print('warning: could not create cogs directory ({})'.format(exc)) directory = cog_dir / to_path(parser, args.name) directory = directory.with_suffix('.py') try: with open(str(directory), 'w', encoding='utf-8') as fp: attrs = '' extra = cog_extras if args.full else '' if args.class_name: name = args.class_name else: name = str(directory.stem) if '-' in name or '_' in name: translation = str.maketrans('-_', ' ') name = name.translate(translation).title().replace(' ', '') else: name = name.title() if args.display_name: attrs += ', name="{}"'.format(args.display_name) if args.hide_commands: attrs += ', command_attrs=dict(hidden=True)' fp.write(cog_template.format(name=name, extra=extra, attrs=attrs)) except OSError as exc: parser.error('could not create cog file ({})'.format(exc)) else: print('successfully made cog at', directory) def add_newbot_args(subparser): parser = subparser.add_parser('newbot', help='creates a command bot project quickly') parser.set_defaults(func=newbot) parser.add_argument('name', help='the bot project name') parser.add_argument('directory', help='the directory to place it in (default: .)', nargs='?', default=Path.cwd()) parser.add_argument('--prefix', help='the bot prefix (default: $)', default='$', metavar='<prefix>') parser.add_argument('--sharded', help='whether to use AutoShardedBot', action='store_true') parser.add_argument('--no-git', help='do not create a .gitignore file', action='store_true', dest='no_git') def add_newcog_args(subparser): parser = subparser.add_parser('newcog', help='creates a new cog template quickly') parser.set_defaults(func=newcog) parser.add_argument('name', help='the cog name') parser.add_argument('directory', help='the directory to place it in (default: cogs)', nargs='?', default=Path('cogs')) parser.add_argument('--class-name', help='the class name of the cog (default: <name>)', dest='class_name') parser.add_argument('--display-name', help='the cog name (default: <name>)') parser.add_argument('--hide-commands', help='whether to hide all commands in the cog', action='store_true') parser.add_argument('--full', help='add all special methods as well', action='store_true') def parse_args(): parser = argparse.ArgumentParser(prog='discord', description='Tools for helping with discord.py') parser.add_argument('-v', '--version', action='store_true', help='shows the library version') parser.set_defaults(func=core) subparser = parser.add_subparsers(dest='subcommand', title='subcommands') add_newbot_args(subparser) add_newcog_args(subparser) return parser, parser.parse_args() def main(): parser, args = parse_args() args.func(parser, args) if __name__ == '__main__': main()
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/__main__.py
__main__.py
import datetime from .asset import Asset from .enums import ActivityType, try_enum from .colour import Colour from .partial_emoji import PartialEmoji from .utils import _get_as_snowflake __all__ = ( 'BaseActivity', 'Activity', 'Streaming', 'Game', 'Spotify', 'CustomActivity', ) """If curious, this is the current schema for an activity. It's fairly long so I will document it here: All keys are optional. state: str (max: 128), details: str (max: 128) timestamps: dict start: int (min: 1) end: int (min: 1) assets: dict large_image: str (max: 32) large_text: str (max: 128) small_image: str (max: 32) small_text: str (max: 128) party: dict id: str (max: 128), size: List[int] (max-length: 2) elem: int (min: 1) secrets: dict match: str (max: 128) join: str (max: 128) spectate: str (max: 128) instance: bool application_id: str name: str (max: 128) url: str type: int sync_id: str session_id: str flags: int There are also activity flags which are mostly uninteresting for the library atm. t.ActivityFlags = { INSTANCE: 1, JOIN: 2, SPECTATE: 4, JOIN_REQUEST: 8, SYNC: 16, PLAY: 32 } """ class BaseActivity: """The base activity that all user-settable activities inherit from. A user-settable activity is one that can be used in :meth:`Client.change_presence`. The following types currently count as user-settable: - :class:`Activity` - :class:`Game` - :class:`Streaming` - :class:`CustomActivity` Note that although these types are considered user-settable by the library, Discord typically ignores certain combinations of activity depending on what is currently set. This behaviour may change in the future so there are no guarantees on whether Discord will actually let you set these types. .. versionadded:: 1.3 """ __slots__ = ('_created_at',) def __init__(self, **kwargs): self._created_at = kwargs.pop('created_at', None) @property def created_at(self): """Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC. .. versionadded:: 1.3 """ if self._created_at is not None: return datetime.datetime.utcfromtimestamp(self._created_at / 1000) class Activity(BaseActivity): """Represents an activity in Discord. This could be an activity such as streaming, playing, listening or watching. For memory optimisation purposes, some activities are offered in slimmed down versions: - :class:`Game` - :class:`Streaming` Attributes ------------ application_id: :class:`int` The application ID of the game. name: :class:`str` The name of the activity. url: :class:`str` A stream URL that the activity could be doing. type: :class:`ActivityType` The type of activity currently being done. state: :class:`str` The user's current state. For example, "In Game". details: :class:`str` The detail of the user's current activity. timestamps: :class:`dict` A dictionary of timestamps. It contains the following optional keys: - ``start``: Corresponds to when the user started doing the activity in milliseconds since Unix epoch. - ``end``: Corresponds to when the user will finish doing the activity in milliseconds since Unix epoch. assets: :class:`dict` A dictionary representing the images and their hover text of an activity. It contains the following optional keys: - ``large_image``: A string representing the ID for the large image asset. - ``large_text``: A string representing the text when hovering over the large image asset. - ``small_image``: A string representing the ID for the small image asset. - ``small_text``: A string representing the text when hovering over the small image asset. party: :class:`dict` A dictionary representing the activity party. It contains the following optional keys: - ``id``: A string representing the party ID. - ``size``: A list of up to two integer elements denoting (current_size, maximum_size). emoji: Optional[:class:`PartialEmoji`] The emoji that belongs to this activity. """ __slots__ = ('state', 'details', '_created_at', 'timestamps', 'assets', 'party', 'flags', 'sync_id', 'session_id', 'type', 'name', 'url', 'application_id', 'emoji') def __init__(self, **kwargs): super().__init__(**kwargs) self.state = kwargs.pop('state', None) self.details = kwargs.pop('details', None) self.timestamps = kwargs.pop('timestamps', {}) self.assets = kwargs.pop('assets', {}) self.party = kwargs.pop('party', {}) self.application_id = _get_as_snowflake(kwargs, 'application_id') self.name = kwargs.pop('name', None) self.url = kwargs.pop('url', None) self.flags = kwargs.pop('flags', 0) self.sync_id = kwargs.pop('sync_id', None) self.session_id = kwargs.pop('session_id', None) self.type = try_enum(ActivityType, kwargs.pop('type', -1)) emoji = kwargs.pop('emoji', None) if emoji is not None: self.emoji = PartialEmoji.from_dict(emoji) else: self.emoji = None def __repr__(self): attrs = ( 'type', 'name', 'url', 'details', 'application_id', 'session_id', 'emoji', ) mapped = ' '.join('%s=%r' % (attr, getattr(self, attr)) for attr in attrs) return '<Activity %s>' % mapped def to_dict(self): ret = {} for attr in self.__slots__: value = getattr(self, attr, None) if value is None: continue if isinstance(value, dict) and len(value) == 0: continue ret[attr] = value ret['type'] = int(self.type) if self.emoji: ret['emoji'] = self.emoji.to_dict() return ret @property def start(self): """Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC, if applicable.""" try: return datetime.datetime.utcfromtimestamp(self.timestamps['start'] / 1000) except KeyError: return None @property def end(self): """Optional[:class:`datetime.datetime`]: When the user will stop doing this activity in UTC, if applicable.""" try: return datetime.datetime.utcfromtimestamp(self.timestamps['end'] / 1000) except KeyError: return None @property def large_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity if applicable.""" if self.application_id is None: return None try: large_image = self.assets['large_image'] except KeyError: return None else: return Asset.BASE + '/app-assets/{0}/{1}.png'.format(self.application_id, large_image) @property def small_image_url(self): """Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity if applicable.""" if self.application_id is None: return None try: small_image = self.assets['small_image'] except KeyError: return None else: return Asset.BASE + '/app-assets/{0}/{1}.png'.format(self.application_id, small_image) @property def large_image_text(self): """Optional[:class:`str`]: Returns the large image asset hover text of this activity if applicable.""" return self.assets.get('large_text', None) @property def small_image_text(self): """Optional[:class:`str`]: Returns the small image asset hover text of this activity if applicable.""" return self.assets.get('small_text', None) class Game(BaseActivity): """A slimmed down version of :class:`Activity` that represents a Discord game. This is typically displayed via **Playing** on the official Discord client. .. container:: operations .. describe:: x == y Checks if two games are equal. .. describe:: x != y Checks if two games are not equal. .. describe:: hash(x) Returns the game's hash. .. describe:: str(x) Returns the game's name. Parameters ----------- name: :class:`str` The game's name. start: Optional[:class:`datetime.datetime`] A naive UTC timestamp representing when the game started. Keyword-only parameter. Ignored for bots. end: Optional[:class:`datetime.datetime`] A naive UTC timestamp representing when the game ends. Keyword-only parameter. Ignored for bots. Attributes ----------- name: :class:`str` The game's name. """ __slots__ = ('name', '_end', '_start') def __init__(self, name, **extra): super().__init__(**extra) self.name = name try: timestamps = extra['timestamps'] except KeyError: self._extract_timestamp(extra, 'start') self._extract_timestamp(extra, 'end') else: self._start = timestamps.get('start', 0) self._end = timestamps.get('end', 0) def _extract_timestamp(self, data, key): try: dt = data[key] except KeyError: setattr(self, '_' + key, 0) else: setattr(self, '_' + key, dt.timestamp() * 1000.0) @property def type(self): """:class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.playing`. """ return ActivityType.playing @property def start(self): """Optional[:class:`datetime.datetime`]: When the user started playing this game in UTC, if applicable.""" if self._start: return datetime.datetime.utcfromtimestamp(self._start / 1000) return None @property def end(self): """Optional[:class:`datetime.datetime`]: When the user will stop playing this game in UTC, if applicable.""" if self._end: return datetime.datetime.utcfromtimestamp(self._end / 1000) return None def __str__(self): return str(self.name) def __repr__(self): return '<Game name={0.name!r}>'.format(self) def to_dict(self): timestamps = {} if self._start: timestamps['start'] = self._start if self._end: timestamps['end'] = self._end return { 'type': ActivityType.playing.value, 'name': str(self.name), 'timestamps': timestamps } def __eq__(self, other): return isinstance(other, Game) and other.name == self.name def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.name) class Streaming(BaseActivity): """A slimmed down version of :class:`Activity` that represents a Discord streaming status. This is typically displayed via **Streaming** on the official Discord client. .. container:: operations .. describe:: x == y Checks if two streams are equal. .. describe:: x != y Checks if two streams are not equal. .. describe:: hash(x) Returns the stream's hash. .. describe:: str(x) Returns the stream's name. Attributes ----------- platform: :class:`str` Where the user is streaming from (ie. YouTube, Twitch). .. versionadded:: 1.3 name: Optional[:class:`str`] The stream's name. details: Optional[:class:`str`] An alias for :attr:`name` game: Optional[:class:`str`] The game being streamed. .. versionadded:: 1.3 url: :class:`str` The stream's URL. assets: :class:`dict` A dictionary comprising of similar keys than those in :attr:`Activity.assets`. """ __slots__ = ('platform', 'name', 'game', 'url', 'details', 'assets') def __init__(self, *, name, url, **extra): super().__init__(**extra) self.platform = name self.name = extra.pop('details', name) self.game = extra.pop('state', None) self.url = url self.details = extra.pop('details', self.name) # compatibility self.assets = extra.pop('assets', {}) @property def type(self): """:class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.streaming`. """ return ActivityType.streaming def __str__(self): return str(self.name) def __repr__(self): return '<Streaming name={0.name!r}>'.format(self) @property def twitch_name(self): """Optional[:class:`str`]: If provided, the twitch name of the user streaming. This corresponds to the ``large_image`` key of the :attr:`Streaming.assets` dictionary if it starts with ``twitch:``. Typically set by the Discord client. """ try: name = self.assets['large_image'] except KeyError: return None else: return name[7:] if name[:7] == 'twitch:' else None def to_dict(self): ret = { 'type': ActivityType.streaming.value, 'name': str(self.name), 'url': str(self.url), 'assets': self.assets } if self.details: ret['details'] = self.details return ret def __eq__(self, other): return isinstance(other, Streaming) and other.name == self.name and other.url == self.url def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.name) class Spotify: """Represents a Spotify listening activity from Discord. This is a special case of :class:`Activity` that makes it easier to work with the Spotify integration. .. container:: operations .. describe:: x == y Checks if two activities are equal. .. describe:: x != y Checks if two activities are not equal. .. describe:: hash(x) Returns the activity's hash. .. describe:: str(x) Returns the string 'Spotify'. """ __slots__ = ('_state', '_details', '_timestamps', '_assets', '_party', '_sync_id', '_session_id', '_created_at') def __init__(self, **data): self._state = data.pop('state', None) self._details = data.pop('details', None) self._timestamps = data.pop('timestamps', {}) self._assets = data.pop('assets', {}) self._party = data.pop('party', {}) self._sync_id = data.pop('sync_id') self._session_id = data.pop('session_id') self._created_at = data.pop('created_at', None) @property def type(self): """:class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.listening`. """ return ActivityType.listening @property def created_at(self): """Optional[:class:`datetime.datetime`]: When the user started listening in UTC. .. versionadded:: 1.3 """ if self._created_at is not None: return datetime.datetime.utcfromtimestamp(self._created_at / 1000) @property def colour(self): """:class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`. There is an alias for this named :attr:`color`""" return Colour(0x1db954) @property def color(self): """:class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`. There is an alias for this named :attr:`colour`""" return self.colour def to_dict(self): return { 'flags': 48, # SYNC | PLAY 'name': 'Spotify', 'assets': self._assets, 'party': self._party, 'sync_id': self._sync_id, 'session_id': self._session_id, 'timestamps': self._timestamps, 'details': self._details, 'state': self._state } @property def name(self): """:class:`str`: The activity's name. This will always return "Spotify".""" return 'Spotify' def __eq__(self, other): return (isinstance(other, Spotify) and other._session_id == self._session_id and other._sync_id == self._sync_id and other.start == self.start) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self._session_id) def __str__(self): return 'Spotify' def __repr__(self): return '<Spotify title={0.title!r} artist={0.artist!r} track_id={0.track_id!r}>'.format(self) @property def title(self): """:class:`str`: The title of the song being played.""" return self._details @property def artists(self): """List[:class:`str`]: The artists of the song being played.""" return self._state.split('; ') @property def artist(self): """:class:`str`: The artist of the song being played. This does not attempt to split the artist information into multiple artists. Useful if there's only a single artist. """ return self._state @property def album(self): """:class:`str`: The album that the song being played belongs to.""" return self._assets.get('large_text', '') @property def album_cover_url(self): """:class:`str`: The album cover image URL from Spotify's CDN.""" large_image = self._assets.get('large_image', '') if large_image[:8] != 'spotify:': return '' album_image_id = large_image[8:] return 'https://i.scdn.co/image/' + album_image_id @property def track_id(self): """:class:`str`: The track ID used by Spotify to identify this song.""" return self._sync_id @property def start(self): """:class:`datetime.datetime`: When the user started playing this song in UTC.""" return datetime.datetime.utcfromtimestamp(self._timestamps['start'] / 1000) @property def end(self): """:class:`datetime.datetime`: When the user will stop playing this song in UTC.""" return datetime.datetime.utcfromtimestamp(self._timestamps['end'] / 1000) @property def duration(self): """:class:`datetime.timedelta`: The duration of the song being played.""" return self.end - self.start @property def party_id(self): """:class:`str`: The party ID of the listening party.""" return self._party.get('id', '') class CustomActivity(BaseActivity): """Represents a Custom activity from Discord. .. container:: operations .. describe:: x == y Checks if two activities are equal. .. describe:: x != y Checks if two activities are not equal. .. describe:: hash(x) Returns the activity's hash. .. describe:: str(x) Returns the custom status text. .. versionadded:: 1.3 Attributes ----------- name: Optional[:class:`str`] The custom activity's name. emoji: Optional[:class:`PartialEmoji`] The emoji to pass to the activity, if any. """ __slots__ = ('name', 'emoji', 'state') def __init__(self, name, *, emoji=None, **extra): super().__init__(**extra) self.name = name self.state = extra.pop('state', None) if self.name == 'Custom Status': self.name = self.state if emoji is None: self.emoji = emoji elif isinstance(emoji, dict): self.emoji = PartialEmoji.from_dict(emoji) elif isinstance(emoji, str): self.emoji = PartialEmoji(name=emoji) elif isinstance(emoji, PartialEmoji): self.emoji = emoji else: raise TypeError('Expected str, PartialEmoji, or None, received {0!r} instead.'.format(type(emoji))) @property def type(self): """:class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`. It always returns :attr:`ActivityType.custom`. """ return ActivityType.custom def to_dict(self): if self.name == self.state: o = { 'type': ActivityType.custom.value, 'state': self.name, 'name': 'Custom Status', } else: o = { 'type': ActivityType.custom.value, 'name': self.name, } if self.emoji: o['emoji'] = self.emoji.to_dict() return o def __eq__(self, other): return (isinstance(other, CustomActivity) and other.name == self.name and other.emoji == self.emoji) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.name, str(self.emoji))) def __str__(self): if self.emoji: if self.name: return '%s %s' % (self.emoji, self.name) return str(self.emoji) else: return str(self.name) def __repr__(self): return '<CustomActivity name={0.name!r} emoji={0.emoji!r}>'.format(self) def create_activity(data): if not data: return None game_type = try_enum(ActivityType, data.get('type', -1)) if game_type is ActivityType.playing: if 'application_id' in data or 'session_id' in data: return Activity(**data) return Game(**data) elif game_type is ActivityType.custom: try: name = data.pop('name') except KeyError: return Activity(**data) else: return CustomActivity(name=name, **data) elif game_type is ActivityType.streaming: if 'url' in data: return Streaming(**data) return Activity(**data) elif game_type is ActivityType.listening and 'sync_id' in data and 'session_id' in data: return Spotify(**data) return Activity(**data)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/activity.py
activity.py
import threading import traceback import subprocess import audioop import asyncio import logging import shlex import time import json import sys import re from .errors import ClientException from .opus import Encoder as OpusEncoder from .oggparse import OggStream log = logging.getLogger(__name__) __all__ = ( 'AudioSource', 'PCMAudio', 'FFmpegAudio', 'FFmpegPCMAudio', 'FFmpegOpusAudio', 'PCMVolumeTransformer', ) if sys.platform != 'win32': CREATE_NO_WINDOW = 0 else: CREATE_NO_WINDOW = 0x08000000 class AudioSource: """Represents an audio stream. The audio stream can be Opus encoded or not, however if the audio stream is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM. .. warning:: The audio source reads are done in a separate thread. """ def read(self): """Reads 20ms worth of audio. Subclasses must implement this. If the audio is complete, then returning an empty :term:`py:bytes-like object` to signal this is the way to do so. If :meth:`is_opus` method returns ``True``, then it must return 20ms worth of Opus encoded audio. Otherwise, it must be 20ms worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes per frame (20ms worth of audio). Returns -------- :class:`bytes` A bytes like object that represents the PCM or Opus data. """ raise NotImplementedError def is_opus(self): """Checks if the audio source is already encoded in Opus.""" return False def cleanup(self): """Called when clean-up is needed to be done. Useful for clearing buffer data or processes after it is done playing audio. """ pass def __del__(self): self.cleanup() class PCMAudio(AudioSource): """Represents raw 16-bit 48KHz stereo PCM audio source. Attributes ----------- stream: :term:`py:file object` A file-like object that reads byte data representing raw PCM. """ def __init__(self, stream): self.stream = stream def read(self): ret = self.stream.read(OpusEncoder.FRAME_SIZE) if len(ret) != OpusEncoder.FRAME_SIZE: return b'' return ret class FFmpegAudio(AudioSource): """Represents an FFmpeg (or AVConv) based AudioSource. User created AudioSources using FFmpeg differently from how :class:`FFmpegPCMAudio` and :class:`FFmpegOpusAudio` work should subclass this. .. versionadded:: 1.3 """ def __init__(self, source, *, executable='ffmpeg', args, **subprocess_kwargs): self._process = self._stdout = None args = [executable, *args] kwargs = {'stdout': subprocess.PIPE} kwargs.update(subprocess_kwargs) self._process = self._spawn_process(args, **kwargs) self._stdout = self._process.stdout def _spawn_process(self, args, **subprocess_kwargs): process = None try: process = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, **subprocess_kwargs) except FileNotFoundError: executable = args.partition(' ')[0] if isinstance(args, str) else args[0] raise ClientException(executable + ' was not found.') from None except subprocess.SubprocessError as exc: raise ClientException('Popen failed: {0.__class__.__name__}: {0}'.format(exc)) from exc else: return process def cleanup(self): proc = self._process if proc is None: return log.info('Preparing to terminate ffmpeg process %s.', proc.pid) try: proc.kill() except Exception: log.exception("Ignoring error attempting to kill ffmpeg process %s", proc.pid) if proc.poll() is None: log.info('ffmpeg process %s has not terminated. Waiting to terminate...', proc.pid) proc.communicate() log.info('ffmpeg process %s should have terminated with a return code of %s.', proc.pid, proc.returncode) else: log.info('ffmpeg process %s successfully terminated with return code of %s.', proc.pid, proc.returncode) self._process = self._stdout = None class FFmpegPCMAudio(FFmpegAudio): """An audio source from FFmpeg (or AVConv). This launches a sub-process to a specific input file given. .. warning:: You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Parameters ------------ source: Union[:class:`str`, :class:`io.BufferedIOBase`] The input that ffmpeg will take and convert to PCM bytes. If ``pipe`` is ``True`` then this is a file-like object that is passed to the stdin of ffmpeg. executable: :class:`str` The executable name (and path) to use. Defaults to ``ffmpeg``. pipe: :class:`bool` If ``True``, denotes that ``source`` parameter will be passed to the stdin of ffmpeg. Defaults to ``False``. stderr: Optional[:term:`py:file object`] A file-like object to pass to the Popen constructor. Could also be an instance of ``subprocess.PIPE``. before_options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg before the ``-i`` flag. options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg after the ``-i`` flag. Raises -------- ClientException The subprocess failed to be created. """ def __init__(self, source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None): args = [] subprocess_kwargs = {'stdin': source if pipe else subprocess.DEVNULL, 'stderr': stderr} if isinstance(before_options, str): args.extend(shlex.split(before_options)) args.append('-i') args.append('-' if pipe else source) args.extend(('-f', 's16le', '-ar', '48000', '-ac', '2', '-loglevel', 'warning')) if isinstance(options, str): args.extend(shlex.split(options)) args.append('pipe:1') super().__init__(source, executable=executable, args=args, **subprocess_kwargs) def read(self): ret = self._stdout.read(OpusEncoder.FRAME_SIZE) if len(ret) != OpusEncoder.FRAME_SIZE: return b'' return ret def is_opus(self): return False class FFmpegOpusAudio(FFmpegAudio): """An audio source from FFmpeg (or AVConv). This launches a sub-process to a specific input file given. However, rather than producing PCM packets like :class:`FFmpegPCMAudio` does that need to be encoded to Opus, this class produces Opus packets, skipping the encoding step done by the library. Alternatively, instead of instantiating this class directly, you can use :meth:`FFmpegOpusAudio.from_probe` to probe for bitrate and codec information. This can be used to opportunistically skip pointless re-encoding of existing Opus audio data for a boost in performance at the cost of a short initial delay to gather the information. The same can be achieved by passing ``copy`` to the ``codec`` parameter, but only if you know that the input source is Opus encoded beforehand. .. versionadded:: 1.3 .. warning:: You must have the ffmpeg or avconv executable in your path environment variable in order for this to work. Parameters ------------ source: Union[:class:`str`, :class:`io.BufferedIOBase`] The input that ffmpeg will take and convert to Opus bytes. If ``pipe`` is ``True`` then this is a file-like object that is passed to the stdin of ffmpeg. bitrate: :class:`int` The bitrate in kbps to encode the output to. Defaults to ``128``. codec: Optional[:class:`str`] The codec to use to encode the audio data. Normally this would be just ``libopus``, but is used by :meth:`FFmpegOpusAudio.from_probe` to opportunistically skip pointlessly re-encoding Opus audio data by passing ``copy`` as the codec value. Any values other than ``copy``, ``opus``, or ``libopus`` will be considered ``libopus``. Defaults to ``libopus``. .. warning:: Do not provide this parameter unless you are certain that the audio input is already Opus encoded. For typical use :meth:`FFmpegOpusAudio.from_probe` should be used to determine the proper value for this parameter. executable: :class:`str` The executable name (and path) to use. Defaults to ``ffmpeg``. pipe: :class:`bool` If ``True``, denotes that ``source`` parameter will be passed to the stdin of ffmpeg. Defaults to ``False``. stderr: Optional[:term:`py:file object`] A file-like object to pass to the Popen constructor. Could also be an instance of ``subprocess.PIPE``. before_options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg before the ``-i`` flag. options: Optional[:class:`str`] Extra command line arguments to pass to ffmpeg after the ``-i`` flag. Raises -------- ClientException The subprocess failed to be created. """ def __init__(self, source, *, bitrate=128, codec=None, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None): args = [] subprocess_kwargs = {'stdin': source if pipe else subprocess.DEVNULL, 'stderr': stderr} if isinstance(before_options, str): args.extend(shlex.split(before_options)) args.append('-i') args.append('-' if pipe else source) codec = 'copy' if codec in ('opus', 'libopus') else 'libopus' args.extend(('-map_metadata', '-1', '-f', 'opus', '-c:a', codec, '-ar', '48000', '-ac', '2', '-b:a', '%sk' % bitrate, '-loglevel', 'warning')) if isinstance(options, str): args.extend(shlex.split(options)) args.append('pipe:1') super().__init__(source, executable=executable, args=args, **subprocess_kwargs) self._packet_iter = OggStream(self._stdout).iter_packets() @classmethod async def from_probe(cls, source, *, method=None, **kwargs): """|coro| A factory method that creates a :class:`FFmpegOpusAudio` after probing the input source for audio codec and bitrate information. Examples ---------- Use this function to create an :class:`FFmpegOpusAudio` instance instead of the constructor: :: source = await discord.FFmpegOpusAudio.from_probe("song.webm") voice_client.play(source) If you are on Windows and don't have ffprobe installed, use the ``fallback`` method to probe using ffmpeg instead: :: source = await discord.FFmpegOpusAudio.from_probe("song.webm", method='fallback') voice_client.play(source) Using a custom method of determining codec and bitrate: :: def custom_probe(source, executable): # some analysis code here return codec, bitrate source = await discord.FFmpegOpusAudio.from_probe("song.webm", method=custom_probe) voice_client.play(source) Parameters ------------ source Identical to the ``source`` parameter for the constructor. method: Optional[Union[:class:`str`, Callable[:class:`str`, :class:`str`]]] The probing method used to determine bitrate and codec information. As a string, valid values are ``native`` to use ffprobe (or avprobe) and ``fallback`` to use ffmpeg (or avconv). As a callable, it must take two string arguments, ``source`` and ``executable``. Both parameters are the same values passed to this factory function. ``executable`` will default to ``ffmpeg`` if not provided as a keyword argument. kwargs The remaining parameters to be passed to the :class:`FFmpegOpusAudio` constructor, excluding ``bitrate`` and ``codec``. Raises -------- AttributeError Invalid probe method, must be ``'native'`` or ``'fallback'``. TypeError Invalid value for ``probe`` parameter, must be :class:`str` or a callable. Returns -------- :class:`FFmpegOpusAudio` An instance of this class. """ executable = kwargs.get('executable') codec, bitrate = await cls.probe(source, method=method, executable=executable) return cls(source, bitrate=bitrate, codec=codec, **kwargs) @classmethod async def probe(cls, source, *, method=None, executable=None): """|coro| Probes the input source for bitrate and codec information. Parameters ------------ source Identical to the ``source`` parameter for :class:`FFmpegOpusAudio`. method Identical to the ``method`` parameter for :meth:`FFmpegOpusAudio.from_probe`. executable: :class:`str` Identical to the ``executable`` parameter for :class:`FFmpegOpusAudio`. Raises -------- AttributeError Invalid probe method, must be ``'native'`` or ``'fallback'``. TypeError Invalid value for ``probe`` parameter, must be :class:`str` or a callable. Returns --------- Tuple[Optional[:class:`str`], Optional[:class:`int`]] A 2-tuple with the codec and bitrate of the input source. """ method = method or 'native' executable = executable or 'ffmpeg' probefunc = fallback = None if isinstance(method, str): probefunc = getattr(cls, '_probe_codec_' + method, None) if probefunc is None: raise AttributeError("Invalid probe method '%s'" % method) if probefunc is cls._probe_codec_native: fallback = cls._probe_codec_fallback elif callable(method): probefunc = method fallback = cls._probe_codec_fallback else: raise TypeError("Expected str or callable for parameter 'probe', " \ "not '{0.__class__.__name__}'" .format(method)) codec = bitrate = None loop = asyncio.get_event_loop() try: codec, bitrate = await loop.run_in_executor(None, lambda: probefunc(source, executable)) except Exception: if not fallback: log.exception("Probe '%s' using '%s' failed", method, executable) return log.exception("Probe '%s' using '%s' failed, trying fallback", method, executable) try: codec, bitrate = await loop.run_in_executor(None, lambda: fallback(source, executable)) except Exception: log.exception("Fallback probe using '%s' failed", executable) else: log.info("Fallback probe found codec=%s, bitrate=%s", codec, bitrate) else: log.info("Probe found codec=%s, bitrate=%s", codec, bitrate) finally: return codec, bitrate @staticmethod def _probe_codec_native(source, executable='ffmpeg'): exe = executable[:2] + 'probe' if executable in ('ffmpeg', 'avconv') else executable args = [exe, '-v', 'quiet', '-print_format', 'json', '-show_streams', '-select_streams', 'a:0', source] output = subprocess.check_output(args, timeout=20) codec = bitrate = None if output: data = json.loads(output) streamdata = data['streams'][0] codec = streamdata.get('codec_name') bitrate = int(streamdata.get('bit_rate', 0)) bitrate = max(round(bitrate/1000, 0), 512) return codec, bitrate @staticmethod def _probe_codec_fallback(source, executable='ffmpeg'): args = [executable, '-hide_banner', '-i', source] proc = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = proc.communicate(timeout=20) output = out.decode('utf8') codec = bitrate = None codec_match = re.search(r"Stream #0.*?Audio: (\w+)", output) if codec_match: codec = codec_match.group(1) br_match = re.search(r"(\d+) [kK]b/s", output) if br_match: bitrate = max(int(br_match.group(1)), 512) return codec, bitrate def read(self): return next(self._packet_iter, b'') def is_opus(self): return True class PCMVolumeTransformer(AudioSource): """Transforms a previous :class:`AudioSource` to have volume controls. This does not work on audio sources that have :meth:`AudioSource.is_opus` set to ``True``. Parameters ------------ original: :class:`AudioSource` The original AudioSource to transform. volume: :class:`float` The initial volume to set it to. See :attr:`volume` for more info. Raises ------- TypeError Not an audio source. ClientException The audio source is opus encoded. """ def __init__(self, original, volume=1.0): if not isinstance(original, AudioSource): raise TypeError('expected AudioSource not {0.__class__.__name__}.'.format(original)) if original.is_opus(): raise ClientException('AudioSource must not be Opus encoded.') self.original = original self.volume = volume @property def volume(self): """Retrieves or sets the volume as a floating point percentage (e.g. ``1.0`` for 100%).""" return self._volume @volume.setter def volume(self, value): self._volume = max(value, 0.0) def cleanup(self): self.original.cleanup() def read(self): ret = self.original.read() return audioop.mul(ret, 2, min(self._volume, 2.0)) class AudioPlayer(threading.Thread): DELAY = OpusEncoder.FRAME_LENGTH / 1000.0 def __init__(self, source, client, *, after=None): threading.Thread.__init__(self) self.daemon = True self.source = source self.client = client self.after = after self._end = threading.Event() self._resumed = threading.Event() self._resumed.set() # we are not paused self._current_error = None self._connected = client._connected self._lock = threading.Lock() if after is not None and not callable(after): raise TypeError('Expected a callable for the "after" parameter.') def _do_run(self): self.loops = 0 self._start = time.perf_counter() # getattr lookup speed ups play_audio = self.client.send_audio_packet self._speak(True) while not self._end.is_set(): # are we paused? if not self._resumed.is_set(): # wait until we aren't self._resumed.wait() continue # are we disconnected from voice? if not self._connected.is_set(): # wait until we are connected self._connected.wait() # reset our internal data self.loops = 0 self._start = time.perf_counter() self.loops += 1 data = self.source.read() if not data: self.stop() break play_audio(data, encode=not self.source.is_opus()) next_time = self._start + self.DELAY * self.loops delay = max(0, self.DELAY + (next_time - time.perf_counter())) time.sleep(delay) def run(self): try: self._do_run() except Exception as exc: self._current_error = exc self.stop() finally: self.source.cleanup() self._call_after() def _call_after(self): error = self._current_error if self.after is not None: try: self.after(error) except Exception as exc: log.exception('Calling the after function failed.') exc.__context__ = error traceback.print_exception(type(exc), exc, exc.__traceback__) elif error: msg = 'Exception in voice thread {}'.format(self.name) log.exception(msg, exc_info=error) print(msg, file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__) def stop(self): self._end.set() self._resumed.set() self._speak(False) def pause(self, *, update_speaking=True): self._resumed.clear() if update_speaking: self._speak(False) def resume(self, *, update_speaking=True): self.loops = 0 self._start = time.perf_counter() self._resumed.set() if update_speaking: self._speak(True) def is_playing(self): return self._resumed.is_set() and not self._end.is_set() def is_paused(self): return not self._end.is_set() and not self._resumed.is_set() def _set_source(self, source): with self._lock: self.pause(update_speaking=False) self.source = source self.resume(update_speaking=False) def _speak(self, speaking): try: asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.loop) except Exception as e: log.info("Speaking call in player failed: %s", e)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/player.py
player.py
"""Some documentation to refer to: - Our main web socket (mWS) sends opcode 4 with a guild ID and channel ID. - The mWS receives VOICE_STATE_UPDATE and VOICE_SERVER_UPDATE. - We pull the session_id from VOICE_STATE_UPDATE. - We pull the token, endpoint and server_id from VOICE_SERVER_UPDATE. - Then we initiate the voice web socket (vWS) pointing to the endpoint. - We send opcode 0 with the user_id, server_id, session_id and token using the vWS. - The vWS sends back opcode 2 with an ssrc, port, modes(array) and hearbeat_interval. - We send a UDP discovery packet to endpoint:port and receive our IP and our port in LE. - Then we send our IP and port via vWS with opcode 1. - When that's all done, we receive opcode 4 from the vWS. - Finally we can transmit data to endpoint:port. """ import asyncio import socket import logging import struct import threading from . import opus, utils from .backoff import ExponentialBackoff from .gateway import * from .errors import ClientException, ConnectionClosed from .player import AudioPlayer, AudioSource try: import nacl.secret has_nacl = True except ImportError: has_nacl = False log = logging.getLogger(__name__) class VoiceProtocol: """A class that represents the Discord voice protocol. This is an abstract class. The library provides a concrete implementation under :class:`VoiceClient`. This class allows you to implement a protocol to allow for an external method of sending voice, such as Lavalink_ or a native library implementation. These classes are passed to :meth:`abc.Connectable.connect`. .. _Lavalink: https://github.com/freyacodes/Lavalink Parameters ------------ client: :class:`Client` The client (or its subclasses) that started the connection request. channel: :class:`abc.Connectable` The voice channel that is being connected to. """ def __init__(self, client, channel): self.client = client self.channel = channel async def on_voice_state_update(self, data): """|coro| An abstract method that is called when the client's voice state has changed. This corresponds to ``VOICE_STATE_UPDATE``. Parameters ------------ data: :class:`dict` The raw `voice state payload`__. .. _voice_state_update_payload: https://discord.com/developers/docs/resources/voice#voice-state-object __ voice_state_update_payload_ """ raise NotImplementedError async def on_voice_server_update(self, data): """|coro| An abstract method that is called when initially connecting to voice. This corresponds to ``VOICE_SERVER_UPDATE``. Parameters ------------ data: :class:`dict` The raw `voice server update payload`__. .. _voice_server_update_payload: https://discord.com/developers/docs/topics/gateway#voice-server-update-voice-server-update-event-fields __ voice_server_update_payload_ """ raise NotImplementedError async def connect(self, *, timeout, reconnect): """|coro| An abstract method called when the client initiates the connection request. When a connection is requested initially, the library calls the constructor under ``__init__`` and then calls :meth:`connect`. If :meth:`connect` fails at some point then :meth:`disconnect` is called. Within this method, to start the voice connection flow it is recommended to use :meth:`Guild.change_voice_state` to start the flow. After which, :meth:`on_voice_server_update` and :meth:`on_voice_state_update` will be called. The order that these two are called is unspecified. Parameters ------------ timeout: :class:`float` The timeout for the connection. reconnect: :class:`bool` Whether reconnection is expected. """ raise NotImplementedError async def disconnect(self, *, force): """|coro| An abstract method called when the client terminates the connection. See :meth:`cleanup`. Parameters ------------ force: :class:`bool` Whether the disconnection was forced. """ raise NotImplementedError def cleanup(self): """This method *must* be called to ensure proper clean-up during a disconnect. It is advisable to call this from within :meth:`disconnect` when you are completely done with the voice protocol instance. This method removes it from the internal state cache that keeps track of currently alive voice clients. Failure to clean-up will cause subsequent connections to report that it's still connected. """ key_id, _ = self.channel._get_voice_client_key() self.client._connection._remove_voice_client(key_id) class VoiceClient(VoiceProtocol): """Represents a Discord voice connection. You do not create these, you typically get them from e.g. :meth:`VoiceChannel.connect`. Warning -------- In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through :func:`opus.load_opus`. Otherwise, your AudioSources must be opus encoded (e.g. using :class:`FFmpegOpusAudio`) or the library will not be able to transmit audio. Attributes ----------- session_id: :class:`str` The voice connection session ID. token: :class:`str` The voice connection token. endpoint: :class:`str` The endpoint we are connecting to. channel: :class:`abc.Connectable` The voice channel connected to. loop: :class:`asyncio.AbstractEventLoop` The event loop that the voice client is running on. """ def __init__(self, client, channel): if not has_nacl: raise RuntimeError("PyNaCl library needed in order to use voice") super().__init__(client, channel) state = client._connection self.token = None self.socket = None self.loop = state.loop self._state = state # this will be used in the AudioPlayer thread self._connected = threading.Event() self._handshaking = False self._potentially_reconnecting = False self._voice_state_complete = asyncio.Event() self._voice_server_complete = asyncio.Event() self.mode = None self._connections = 0 self.sequence = 0 self.timestamp = 0 self._runner = None self._player = None self.encoder = None self._lite_nonce = 0 self.ws = None warn_nacl = not has_nacl supported_modes = ( 'xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305', ) @property def guild(self): """Optional[:class:`Guild`]: The guild we're connected to, if applicable.""" return getattr(self.channel, 'guild', None) @property def user(self): """:class:`ClientUser`: The user connected to voice (i.e. ourselves).""" return self._state.user def checked_add(self, attr, value, limit): val = getattr(self, attr) if val + value > limit: setattr(self, attr, 0) else: setattr(self, attr, val + value) # connection related async def on_voice_state_update(self, data): self.session_id = data['session_id'] channel_id = data['channel_id'] if not self._handshaking or self._potentially_reconnecting: # If we're done handshaking then we just need to update ourselves # If we're potentially reconnecting due to a 4014, then we need to differentiate # a channel move and an actual force disconnect if channel_id is None: # We're being disconnected so cleanup await self.disconnect() else: guild = self.guild self.channel = channel_id and guild and guild.get_channel(int(channel_id)) else: self._voice_state_complete.set() async def on_voice_server_update(self, data): if self._voice_server_complete.is_set(): log.info('Ignoring extraneous voice server update.') return self.token = data.get('token') self.server_id = int(data['guild_id']) endpoint = data.get('endpoint') if endpoint is None or self.token is None: log.warning('Awaiting endpoint... This requires waiting. ' \ 'If timeout occurred considering raising the timeout and reconnecting.') return self.endpoint, _, _ = endpoint.rpartition(':') if self.endpoint.startswith('wss://'): # Just in case, strip it off since we're going to add it later self.endpoint = self.endpoint[6:] # This gets set later self.endpoint_ip = None self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.setblocking(False) if not self._handshaking: # If we're not handshaking then we need to terminate our previous connection in the websocket await self.ws.close(4000) return self._voice_server_complete.set() async def voice_connect(self): await self.channel.guild.change_voice_state(channel=self.channel) async def voice_disconnect(self): log.info('The voice handshake is being terminated for Channel ID %s (Guild ID %s)', self.channel.id, self.guild.id) await self.channel.guild.change_voice_state(channel=None) def prepare_handshake(self): self._voice_state_complete.clear() self._voice_server_complete.clear() self._handshaking = True log.info('Starting voice handshake... (connection attempt %d)', self._connections + 1) self._connections += 1 def finish_handshake(self): log.info('Voice handshake complete. Endpoint found %s', self.endpoint) self._handshaking = False self._voice_server_complete.clear() self._voice_state_complete.clear() async def connect_websocket(self): ws = await DiscordVoiceWebSocket.from_client(self) self._connected.clear() while ws.secret_key is None: await ws.poll_event() self._connected.set() return ws async def connect(self, *, reconnect, timeout): log.info('Connecting to voice...') self.timeout = timeout for i in range(5): self.prepare_handshake() # This has to be created before we start the flow. futures = [ self._voice_state_complete.wait(), self._voice_server_complete.wait(), ] # Start the connection flow await self.voice_connect() try: await utils.sane_wait_for(futures, timeout=timeout) except asyncio.TimeoutError: await self.disconnect(force=True) raise self.finish_handshake() try: self.ws = await self.connect_websocket() break except (ConnectionClosed, asyncio.TimeoutError): if reconnect: log.exception('Failed to connect to voice... Retrying...') await asyncio.sleep(1 + i * 2.0) await self.voice_disconnect() continue else: raise if self._runner is None: self._runner = self.loop.create_task(self.poll_voice_ws(reconnect)) async def potential_reconnect(self): # Attempt to stop the player thread from playing early self._connected.clear() self.prepare_handshake() self._potentially_reconnecting = True try: # We only care about VOICE_SERVER_UPDATE since VOICE_STATE_UPDATE can come before we get disconnected await asyncio.wait_for(self._voice_server_complete.wait(), timeout=self.timeout) except asyncio.TimeoutError: self._potentially_reconnecting = False await self.disconnect(force=True) return False self.finish_handshake() self._potentially_reconnecting = False try: self.ws = await self.connect_websocket() except (ConnectionClosed, asyncio.TimeoutError): return False else: return True @property def latency(self): """:class:`float`: Latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This could be referred to as the Discord Voice WebSocket latency and is an analogue of user's voice latencies as seen in the Discord client. .. versionadded:: 1.4 """ ws = self.ws return float("inf") if not ws else ws.latency @property def average_latency(self): """:class:`float`: Average of most recent 20 HEARTBEAT latencies in seconds. .. versionadded:: 1.4 """ ws = self.ws return float("inf") if not ws else ws.average_latency async def poll_voice_ws(self, reconnect): backoff = ExponentialBackoff() while True: try: await self.ws.poll_event() except (ConnectionClosed, asyncio.TimeoutError) as exc: if isinstance(exc, ConnectionClosed): # The following close codes are undocumented so I will document them here. # 1000 - normal closure (obviously) # 4014 - voice channel has been deleted. # 4015 - voice server has crashed if exc.code in (1000, 4015): log.info('Disconnecting from voice normally, close code %d.', exc.code) await self.disconnect() break if exc.code == 4014: log.info('Disconnected from voice by force... potentially reconnecting.') successful = await self.potential_reconnect() if not successful: log.info('Reconnect was unsuccessful, disconnecting from voice normally...') await self.disconnect() break else: continue if not reconnect: await self.disconnect() raise retry = backoff.delay() log.exception('Disconnected from voice... Reconnecting in %.2fs.', retry) self._connected.clear() await asyncio.sleep(retry) await self.voice_disconnect() try: await self.connect(reconnect=True, timeout=self.timeout) except asyncio.TimeoutError: # at this point we've retried 5 times... let's continue the loop. log.warning('Could not connect to voice... Retrying...') continue async def disconnect(self, *, force=False): """|coro| Disconnects this voice client from voice. """ if not force and not self.is_connected(): return self.stop() self._connected.clear() try: if self.ws: await self.ws.close() await self.voice_disconnect() finally: self.cleanup() if self.socket: self.socket.close() async def move_to(self, channel): """|coro| Moves you to a different voice channel. Parameters ----------- channel: :class:`abc.Snowflake` The channel to move to. Must be a voice channel. """ await self.channel.guild.change_voice_state(channel=channel) def is_connected(self): """Indicates if the voice client is connected to voice.""" return self._connected.is_set() # audio related def _get_voice_packet(self, data): header = bytearray(12) # Formulate rtp header header[0] = 0x80 header[1] = 0x78 struct.pack_into('>H', header, 2, self.sequence) struct.pack_into('>I', header, 4, self.timestamp) struct.pack_into('>I', header, 8, self.ssrc) encrypt_packet = getattr(self, '_encrypt_' + self.mode) return encrypt_packet(header, data) def _encrypt_xsalsa20_poly1305(self, header, data): box = nacl.secret.SecretBox(bytes(self.secret_key)) nonce = bytearray(24) nonce[:12] = header return header + box.encrypt(bytes(data), bytes(nonce)).ciphertext def _encrypt_xsalsa20_poly1305_suffix(self, header, data): box = nacl.secret.SecretBox(bytes(self.secret_key)) nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) return header + box.encrypt(bytes(data), nonce).ciphertext + nonce def _encrypt_xsalsa20_poly1305_lite(self, header, data): box = nacl.secret.SecretBox(bytes(self.secret_key)) nonce = bytearray(24) nonce[:4] = struct.pack('>I', self._lite_nonce) self.checked_add('_lite_nonce', 1, 4294967295) return header + box.encrypt(bytes(data), bytes(nonce)).ciphertext + nonce[:4] def play(self, source, *, after=None): """Plays an :class:`AudioSource`. The finalizer, ``after`` is called after the source has been exhausted or an error occurred. If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be displayed as if it were raised. Parameters ----------- source: :class:`AudioSource` The audio source we're reading from. after: Callable[[:class:`Exception`], Any] The finalizer that is called after the stream is exhausted. This function must have a single parameter, ``error``, that denotes an optional exception that was raised during playing. Raises ------- ClientException Already playing audio or not connected. TypeError Source is not a :class:`AudioSource` or after is not a callable. OpusNotLoaded Source is not opus encoded and opus is not loaded. """ if not self.is_connected(): raise ClientException('Not connected to voice.') if self.is_playing(): raise ClientException('Already playing audio.') if not isinstance(source, AudioSource): raise TypeError('source must an AudioSource not {0.__class__.__name__}'.format(source)) if not self.encoder and not source.is_opus(): self.encoder = opus.Encoder() self._player = AudioPlayer(source, self, after=after) self._player.start() def is_playing(self): """Indicates if we're currently playing audio.""" return self._player is not None and self._player.is_playing() def is_paused(self): """Indicates if we're playing audio, but if we're paused.""" return self._player is not None and self._player.is_paused() def stop(self): """Stops playing audio.""" if self._player: self._player.stop() self._player = None def pause(self): """Pauses the audio playing.""" if self._player: self._player.pause() def resume(self): """Resumes the audio playing.""" if self._player: self._player.resume() @property def source(self): """Optional[:class:`AudioSource`]: The audio source being played, if playing. This property can also be used to change the audio source currently being played. """ return self._player.source if self._player else None @source.setter def source(self, value): if not isinstance(value, AudioSource): raise TypeError('expected AudioSource not {0.__class__.__name__}.'.format(value)) if self._player is None: raise ValueError('Not playing anything.') self._player._set_source(value) def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: :class:`bytes` The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: :class:`bool` Indicates if ``data`` should be encoded into Opus. Raises ------- ClientException You are not connected. opus.OpusError Encoding the data failed. """ self.checked_add('sequence', 1, 65535) if encode: encoded_data = self.encoder.encode(data, self.encoder.SAMPLES_PER_FRAME) else: encoded_data = data packet = self._get_voice_packet(encoded_data) try: self.socket.sendto(packet, (self.endpoint_ip, self.voice_port)) except BlockingIOError: log.warning('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) self.checked_add('timestamp', opus.Encoder.SAMPLES_PER_FRAME, 4294967295)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/voice_client.py
voice_client.py
from .asset import Asset from . import utils from .partial_emoji import _EmojiTag from .user import User class Emoji(_EmojiTag): """Represents a custom emoji. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y Checks if two emoji are not the same. .. describe:: hash(x) Return the emoji's hash. .. describe:: iter(x) Returns an iterator of ``(field, value)`` pairs. This allows this class to be used as an iterable in list/dict/etc constructions. .. describe:: str(x) Returns the emoji rendered for discord. Attributes ----------- name: :class:`str` The name of the emoji. id: :class:`int` The emoji's ID. require_colons: :class:`bool` If colons are required to use this emoji in the client (:PJSalt: vs PJSalt). animated: :class:`bool` Whether an emoji is animated or not. managed: :class:`bool` If this emoji is managed by a Twitch integration. guild_id: :class:`int` The guild ID the emoji belongs to. available: :class:`bool` Whether the emoji is available for use. user: Optional[:class:`User`] The user that created the emoji. This can only be retrieved using :meth:`Guild.fetch_emoji` and having the :attr:`~Permissions.manage_emojis` permission. """ __slots__ = ('require_colons', 'animated', 'managed', 'id', 'name', '_roles', 'guild_id', '_state', 'user', 'available') def __init__(self, *, guild, state, data): self.guild_id = guild.id self._state = state self._from_data(data) def _from_data(self, emoji): self.require_colons = emoji['require_colons'] self.managed = emoji['managed'] self.id = int(emoji['id']) self.name = emoji['name'] self.animated = emoji.get('animated', False) self.available = emoji.get('available', True) self._roles = utils.SnowflakeList(map(int, emoji.get('roles', []))) user = emoji.get('user') self.user = User(state=self._state, data=user) if user else None def _iterator(self): for attr in self.__slots__: if attr[0] != '_': value = getattr(self, attr, None) if value is not None: yield (attr, value) def __iter__(self): return self._iterator() def __str__(self): if self.animated: return '<a:{0.name}:{0.id}>'.format(self) return "<:{0.name}:{0.id}>".format(self) def __repr__(self): return '<Emoji id={0.id} name={0.name!r} animated={0.animated} managed={0.managed}>'.format(self) def __eq__(self, other): return isinstance(other, _EmojiTag) and self.id == other.id def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return self.id >> 22 @property def created_at(self): """:class:`datetime.datetime`: Returns the emoji's creation time in UTC.""" return utils.snowflake_time(self.id) @property def url(self): """:class:`Asset`: Returns the asset of the emoji. This is equivalent to calling :meth:`url_as` with the default parameters (i.e. png/gif detection). """ return self.url_as(format=None) @property def roles(self): """List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji. If roles is empty, the emoji is unrestricted. """ guild = self.guild if guild is None: return [] return [role for role in guild.roles if self._roles.has(role.id)] @property def guild(self): """:class:`Guild`: The guild this emoji belongs to.""" return self._state._get_guild(self.guild_id) def url_as(self, *, format=None, static_format="png"): """Returns an :class:`Asset` for the emoji's url. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif'. 'gif' is only valid for animated emojis. .. versionadded:: 1.6 Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the emojis to. If the format is ``None``, then it is automatically detected as either 'gif' or static_format, depending on whether the emoji is animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated emoji's to. Defaults to 'png' Raises ------- InvalidArgument Bad image format passed to ``format`` or ``static_format``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_emoji(self._state, self, format=format, static_format=static_format) def is_usable(self): """:class:`bool`: Whether the bot can use this emoji. .. versionadded:: 1.3 """ if not self.available: return False if not self._roles: return True emoji_roles, my_roles = self._roles, self.guild.me._roles return any(my_roles.has(role_id) for role_id in emoji_roles) async def delete(self, *, reason=None): """|coro| Deletes the custom emoji. You must have :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to delete emojis. HTTPException An error occurred deleting the emoji. """ await self._state.http.delete_custom_emoji(self.guild.id, self.id, reason=reason) async def edit(self, *, name=None, roles=None, reason=None): r"""|coro| Edits the custom emoji. You must have :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The new emoji name. roles: Optional[list[:class:`Role`]] A :class:`list` of :class:`Role`\s that can use this emoji. Leave empty to make it available to everyone. reason: Optional[:class:`str`] The reason for editing this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to edit emojis. HTTPException An error occurred editing the emoji. """ name = name or self.name if roles: roles = [role.id for role in roles] await self._state.http.edit_custom_emoji(self.guild.id, self.id, name=name, roles=roles, reason=reason)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/emoji.py
emoji.py
import abc import sys import copy import asyncio from .iterators import HistoryIterator from .context_managers import Typing from .enums import ChannelType from .errors import InvalidArgument, ClientException from .mentions import AllowedMentions from .permissions import PermissionOverwrite, Permissions from .role import Role from .invite import Invite from .file import File from .voice_client import VoiceClient, VoiceProtocol from . import utils class _Undefined: def __repr__(self): return 'see-below' _undefined = _Undefined() class Snowflake(metaclass=abc.ABCMeta): """An ABC that details the common operations on a Discord model. Almost all :ref:`Discord models <discord_api_models>` meet this abstract base class. If you want to create a snowflake on your own, consider using :class:`.Object`. Attributes ----------- id: :class:`int` The model's unique ID. """ __slots__ = () @property @abc.abstractmethod def created_at(self): """:class:`datetime.datetime`: Returns the model's creation time as a naive datetime in UTC.""" raise NotImplementedError @classmethod def __subclasshook__(cls, C): if cls is Snowflake: mro = C.__mro__ for attr in ('created_at', 'id'): for base in mro: if attr in base.__dict__: break else: return NotImplemented return True return NotImplemented class User(metaclass=abc.ABCMeta): """An ABC that details the common operations on a Discord user. The following implement this ABC: - :class:`~discord.User` - :class:`~discord.ClientUser` - :class:`~discord.Member` This ABC must also implement :class:`~discord.abc.Snowflake`. Attributes ----------- name: :class:`str` The user's username. discriminator: :class:`str` The user's discriminator. avatar: Optional[:class:`str`] The avatar hash the user has. bot: :class:`bool` If the user is a bot account. """ __slots__ = () @property @abc.abstractmethod def display_name(self): """:class:`str`: Returns the user's display name.""" raise NotImplementedError @property @abc.abstractmethod def mention(self): """:class:`str`: Returns a string that allows you to mention the given user.""" raise NotImplementedError @classmethod def __subclasshook__(cls, C): if cls is User: if Snowflake.__subclasshook__(C) is NotImplemented: return NotImplemented mro = C.__mro__ for attr in ('display_name', 'mention', 'name', 'avatar', 'discriminator', 'bot'): for base in mro: if attr in base.__dict__: break else: return NotImplemented return True return NotImplemented class PrivateChannel(metaclass=abc.ABCMeta): """An ABC that details the common operations on a private Discord channel. The following implement this ABC: - :class:`~discord.DMChannel` - :class:`~discord.GroupChannel` This ABC must also implement :class:`~discord.abc.Snowflake`. Attributes ----------- me: :class:`~discord.ClientUser` The user presenting yourself. """ __slots__ = () @classmethod def __subclasshook__(cls, C): if cls is PrivateChannel: if Snowflake.__subclasshook__(C) is NotImplemented: return NotImplemented mro = C.__mro__ for base in mro: if 'me' in base.__dict__: return True return NotImplemented return NotImplemented class _Overwrites: __slots__ = ('id', 'allow', 'deny', 'type') def __init__(self, **kwargs): self.id = kwargs.pop('id') self.allow = int(kwargs.pop('allow_new', 0)) self.deny = int(kwargs.pop('deny_new', 0)) self.type = sys.intern(kwargs.pop('type')) def _asdict(self): return { 'id': self.id, 'allow': str(self.allow), 'deny': str(self.deny), 'type': self.type, } class GuildChannel: """An ABC that details the common operations on a Discord guild channel. The following implement this ABC: - :class:`~discord.TextChannel` - :class:`~discord.VoiceChannel` - :class:`~discord.CategoryChannel` - :class:`~discord.StageChannel` This ABC must also implement :class:`~discord.abc.Snowflake`. Attributes ----------- name: :class:`str` The channel name. guild: :class:`~discord.Guild` The guild the channel belongs to. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. """ __slots__ = () def __str__(self): return self.name @property def _sorting_bucket(self): raise NotImplementedError async def _move(self, position, parent_id=None, lock_permissions=False, *, reason): if position < 0: raise InvalidArgument('Channel position cannot be less than 0.') http = self._state.http bucket = self._sorting_bucket channels = [c for c in self.guild.channels if c._sorting_bucket == bucket] channels.sort(key=lambda c: c.position) try: # remove ourselves from the channel list channels.remove(self) except ValueError: # not there somehow lol return else: index = next((i for i, c in enumerate(channels) if c.position >= position), len(channels)) # add ourselves at our designated position channels.insert(index, self) payload = [] for index, c in enumerate(channels): d = {'id': c.id, 'position': index} if parent_id is not _undefined and c.id == self.id: d.update(parent_id=parent_id, lock_permissions=lock_permissions) payload.append(d) await http.bulk_channel_update(self.guild.id, payload, reason=reason) self.position = position if parent_id is not _undefined: self.category_id = int(parent_id) if parent_id else None async def _edit(self, options, reason): try: parent = options.pop('category') except KeyError: parent_id = _undefined else: parent_id = parent and parent.id try: options['rate_limit_per_user'] = options.pop('slowmode_delay') except KeyError: pass try: rtc_region = options.pop('rtc_region') except KeyError: pass else: options['rtc_region'] = None if rtc_region is None else str(rtc_region) lock_permissions = options.pop('sync_permissions', False) try: position = options.pop('position') except KeyError: if parent_id is not _undefined: if lock_permissions: category = self.guild.get_channel(parent_id) options['permission_overwrites'] = [c._asdict() for c in category._overwrites] options['parent_id'] = parent_id elif lock_permissions and self.category_id is not None: # if we're syncing permissions on a pre-existing channel category without changing it # we need to update the permissions to point to the pre-existing category category = self.guild.get_channel(self.category_id) options['permission_overwrites'] = [c._asdict() for c in category._overwrites] else: await self._move(position, parent_id=parent_id, lock_permissions=lock_permissions, reason=reason) overwrites = options.get('overwrites', None) if overwrites is not None: perms = [] for target, perm in overwrites.items(): if not isinstance(perm, PermissionOverwrite): raise InvalidArgument('Expected PermissionOverwrite received {0.__name__}'.format(type(perm))) allow, deny = perm.pair() payload = { 'allow': allow.value, 'deny': deny.value, 'id': target.id } if isinstance(target, Role): payload['type'] = 'role' else: payload['type'] = 'member' perms.append(payload) options['permission_overwrites'] = perms try: ch_type = options['type'] except KeyError: pass else: if not isinstance(ch_type, ChannelType): raise InvalidArgument('type field must be of type ChannelType') options['type'] = ch_type.value if options: data = await self._state.http.edit_channel(self.id, reason=reason, **options) self._update(self.guild, data) def _fill_overwrites(self, data): self._overwrites = [] everyone_index = 0 everyone_id = self.guild.id for index, overridden in enumerate(data.get('permission_overwrites', [])): overridden_id = int(overridden.pop('id')) self._overwrites.append(_Overwrites(id=overridden_id, **overridden)) if overridden['type'] == 'member': continue if overridden_id == everyone_id: # the @everyone role is not guaranteed to be the first one # in the list of permission overwrites, however the permission # resolution code kind of requires that it is the first one in # the list since it is special. So we need the index so we can # swap it to be the first one. everyone_index = index # do the swap tmp = self._overwrites if tmp: tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index] @property def changed_roles(self): """List[:class:`~discord.Role`]: Returns a list of roles that have been overridden from their default values in the :attr:`~discord.Guild.roles` attribute.""" ret = [] g = self.guild for overwrite in filter(lambda o: o.type == 'role', self._overwrites): role = g.get_role(overwrite.id) if role is None: continue role = copy.copy(role) role.permissions.handle_overwrite(overwrite.allow, overwrite.deny) ret.append(role) return ret @property def mention(self): """:class:`str`: The string that allows you to mention the channel.""" return '<#%s>' % self.id @property def created_at(self): """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return utils.snowflake_time(self.id) def overwrites_for(self, obj): """Returns the channel-specific overwrites for a member or a role. Parameters ----------- obj: Union[:class:`~discord.Role`, :class:`~discord.abc.User`] The role or user denoting whose overwrite to get. Returns --------- :class:`~discord.PermissionOverwrite` The permission overwrites for this object. """ if isinstance(obj, User): predicate = lambda p: p.type == 'member' elif isinstance(obj, Role): predicate = lambda p: p.type == 'role' else: predicate = lambda p: True for overwrite in filter(predicate, self._overwrites): if overwrite.id == obj.id: allow = Permissions(overwrite.allow) deny = Permissions(overwrite.deny) return PermissionOverwrite.from_pair(allow, deny) return PermissionOverwrite() @property def overwrites(self): """Returns all of the channel's overwrites. This is returned as a dictionary where the key contains the target which can be either a :class:`~discord.Role` or a :class:`~discord.Member` and the value is the overwrite as a :class:`~discord.PermissionOverwrite`. Returns -------- Mapping[Union[:class:`~discord.Role`, :class:`~discord.Member`], :class:`~discord.PermissionOverwrite`] The channel's permission overwrites. """ ret = {} for ow in self._overwrites: allow = Permissions(ow.allow) deny = Permissions(ow.deny) overwrite = PermissionOverwrite.from_pair(allow, deny) if ow.type == 'role': target = self.guild.get_role(ow.id) elif ow.type == 'member': target = self.guild.get_member(ow.id) # TODO: There is potential data loss here in the non-chunked # case, i.e. target is None because get_member returned nothing. # This can be fixed with a slight breaking change to the return type, # i.e. adding discord.Object to the list of it # However, for now this is an acceptable compromise. if target is not None: ret[target] = overwrite return ret @property def category(self): """Optional[:class:`~discord.CategoryChannel`]: The category this channel belongs to. If there is no category then this is ``None``. """ return self.guild.get_channel(self.category_id) @property def permissions_synced(self): """:class:`bool`: Whether or not the permissions for this channel are synced with the category it belongs to. If there is no category then this is ``False``. .. versionadded:: 1.3 """ category = self.guild.get_channel(self.category_id) return bool(category and category.overwrites == self.overwrites) def permissions_for(self, member): """Handles permission resolution for the current :class:`~discord.Member`. This function takes into consideration the following cases: - Guild owner - Guild roles - Channel overrides - Member overrides Parameters ---------- member: :class:`~discord.Member` The member to resolve permissions for. Returns ------- :class:`~discord.Permissions` The resolved permissions for the member. """ # The current cases can be explained as: # Guild owner get all permissions -- no questions asked. Otherwise... # The @everyone role gets the first application. # After that, the applied roles that the user has in the channel # (or otherwise) are then OR'd together. # After the role permissions are resolved, the member permissions # have to take into effect. # After all that is done.. you have to do the following: # If manage permissions is True, then all permissions are set to True. # The operation first takes into consideration the denied # and then the allowed. if self.guild.owner_id == member.id: return Permissions.all() default = self.guild.default_role base = Permissions(default.permissions.value) roles = member._roles get_role = self.guild.get_role # Apply guild roles that the member has. for role_id in roles: role = get_role(role_id) if role is not None: base.value |= role._permissions # Guild-wide Administrator -> True for everything # Bypass all channel-specific overrides if base.administrator: return Permissions.all() # Apply @everyone allow/deny first since it's special try: maybe_everyone = self._overwrites[0] if maybe_everyone.id == self.guild.id: base.handle_overwrite(allow=maybe_everyone.allow, deny=maybe_everyone.deny) remaining_overwrites = self._overwrites[1:] else: remaining_overwrites = self._overwrites except IndexError: remaining_overwrites = self._overwrites denies = 0 allows = 0 # Apply channel specific role permission overwrites for overwrite in remaining_overwrites: if overwrite.type == 'role' and roles.has(overwrite.id): denies |= overwrite.deny allows |= overwrite.allow base.handle_overwrite(allow=allows, deny=denies) # Apply member specific permission overwrites for overwrite in remaining_overwrites: if overwrite.type == 'member' and overwrite.id == member.id: base.handle_overwrite(allow=overwrite.allow, deny=overwrite.deny) break # if you can't send a message in a channel then you can't have certain # permissions as well if not base.send_messages: base.send_tts_messages = False base.mention_everyone = False base.embed_links = False base.attach_files = False # if you can't read a channel then you have no permissions there if not base.read_messages: denied = Permissions.all_channel() base.value &= ~denied.value return base async def delete(self, *, reason=None): """|coro| Deletes the channel. You must have :attr:`~Permissions.manage_channels` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this channel. Shows up on the audit log. Raises ------- ~discord.Forbidden You do not have proper permissions to delete the channel. ~discord.NotFound The channel was not found or was already deleted. ~discord.HTTPException Deleting the channel failed. """ await self._state.http.delete_channel(self.id, reason=reason) async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **permissions): r"""|coro| Sets the channel specific permission overwrites for a target in the channel. The ``target`` parameter should either be a :class:`~discord.Member` or a :class:`~discord.Role` that belongs to guild. The ``overwrite`` parameter, if given, must either be ``None`` or :class:`~discord.PermissionOverwrite`. For convenience, you can pass in keyword arguments denoting :class:`~discord.Permissions` attributes. If this is done, then you cannot mix the keyword arguments with the ``overwrite`` parameter. If the ``overwrite`` parameter is ``None``, then the permission overwrites are deleted. You must have the :attr:`~Permissions.manage_roles` permission to use this. Examples ---------- Setting allow and deny: :: await message.channel.set_permissions(message.author, read_messages=True, send_messages=False) Deleting overwrites :: await channel.set_permissions(member, overwrite=None) Using :class:`~discord.PermissionOverwrite` :: overwrite = discord.PermissionOverwrite() overwrite.send_messages = False overwrite.read_messages = True await channel.set_permissions(member, overwrite=overwrite) Parameters ----------- target: Union[:class:`~discord.Member`, :class:`~discord.Role`] The member or role to overwrite permissions for. overwrite: Optional[:class:`~discord.PermissionOverwrite`] The permissions to allow and deny to the target, or ``None`` to delete the overwrite. \*\*permissions A keyword argument list of permissions to set for ease of use. Cannot be mixed with ``overwrite``. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. Raises ------- ~discord.Forbidden You do not have permissions to edit channel specific permissions. ~discord.HTTPException Editing channel specific permissions failed. ~discord.NotFound The role or member being edited is not part of the guild. ~discord.InvalidArgument The overwrite parameter invalid or the target type was not :class:`~discord.Role` or :class:`~discord.Member`. """ http = self._state.http if isinstance(target, User): perm_type = 'member' elif isinstance(target, Role): perm_type = 'role' else: raise InvalidArgument('target parameter must be either Member or Role') if isinstance(overwrite, _Undefined): if len(permissions) == 0: raise InvalidArgument('No overwrite provided.') try: overwrite = PermissionOverwrite(**permissions) except (ValueError, TypeError): raise InvalidArgument('Invalid permissions given to keyword arguments.') else: if len(permissions) > 0: raise InvalidArgument('Cannot mix overwrite and keyword arguments.') # TODO: wait for event if overwrite is None: await http.delete_channel_permissions(self.id, target.id, reason=reason) elif isinstance(overwrite, PermissionOverwrite): (allow, deny) = overwrite.pair() await http.edit_channel_permissions(self.id, target.id, allow.value, deny.value, perm_type, reason=reason) else: raise InvalidArgument('Invalid overwrite type provided.') async def _clone_impl(self, base_attrs, *, name=None, reason=None): base_attrs['permission_overwrites'] = [ x._asdict() for x in self._overwrites ] base_attrs['parent_id'] = self.category_id base_attrs['name'] = name or self.name guild_id = self.guild.id cls = self.__class__ data = await self._state.http.create_channel(guild_id, self.type.value, reason=reason, **base_attrs) obj = cls(state=self._state, guild=self.guild, data=data) # temporarily add it to the cache self.guild._channels[obj.id] = obj return obj async def clone(self, *, name=None, reason=None): """|coro| Clones this channel. This creates a channel with the same properties as this channel. You must have the :attr:`~discord.Permissions.manage_channels` permission to do this. .. versionadded:: 1.1 Parameters ------------ name: Optional[:class:`str`] The name of the new channel. If not provided, defaults to this channel name. reason: Optional[:class:`str`] The reason for cloning this channel. Shows up on the audit log. Raises ------- ~discord.Forbidden You do not have the proper permissions to create this channel. ~discord.HTTPException Creating the channel failed. Returns -------- :class:`.abc.GuildChannel` The channel that was created. """ raise NotImplementedError async def move(self, **kwargs): """|coro| A rich interface to help move a channel relative to other channels. If exact position movement is required, :meth:`edit` should be used instead. You must have the :attr:`~discord.Permissions.manage_channels` permission to do this. .. note:: Voice channels will always be sorted below text channels. This is a Discord limitation. .. versionadded:: 1.7 Parameters ------------ beginning: :class:`bool` Whether to move the channel to the beginning of the channel list (or category if given). This is mutually exclusive with ``end``, ``before``, and ``after``. end: :class:`bool` Whether to move the channel to the end of the channel list (or category if given). This is mutually exclusive with ``beginning``, ``before``, and ``after``. before: :class:`~discord.abc.Snowflake` The channel that should be before our current channel. This is mutually exclusive with ``beginning``, ``end``, and ``after``. after: :class:`~discord.abc.Snowflake` The channel that should be after our current channel. This is mutually exclusive with ``beginning``, ``end``, and ``before``. offset: :class:`int` The number of channels to offset the move by. For example, an offset of ``2`` with ``beginning=True`` would move it 2 after the beginning. A positive number moves it below while a negative number moves it above. Note that this number is relative and computed after the ``beginning``, ``end``, ``before``, and ``after`` parameters. category: Optional[:class:`~discord.abc.Snowflake`] The category to move this channel under. If ``None`` is given then it moves it out of the category. This parameter is ignored if moving a category channel. sync_permissions: :class:`bool` Whether to sync the permissions with the category (if given). reason: :class:`str` The reason for the move. Raises ------- InvalidArgument An invalid position was given or a bad mix of arguments were passed. Forbidden You do not have permissions to move the channel. HTTPException Moving the channel failed. """ if not kwargs: return beginning, end = kwargs.get('beginning'), kwargs.get('end') before, after = kwargs.get('before'), kwargs.get('after') offset = kwargs.get('offset', 0) if sum(bool(a) for a in (beginning, end, before, after)) > 1: raise InvalidArgument('Only one of [before, after, end, beginning] can be used.') bucket = self._sorting_bucket parent_id = kwargs.get('category', ...) if parent_id not in (..., None): parent_id = parent_id.id channels = [ ch for ch in self.guild.channels if ch._sorting_bucket == bucket and ch.category_id == parent_id ] else: channels = [ ch for ch in self.guild.channels if ch._sorting_bucket == bucket and ch.category_id == self.category_id ] channels.sort(key=lambda c: (c.position, c.id)) try: # Try to remove ourselves from the channel list channels.remove(self) except ValueError: # If we're not there then it's probably due to not being in the category pass index = None if beginning: index = 0 elif end: index = len(channels) elif before: index = next((i for i, c in enumerate(channels) if c.id == before.id), None) elif after: index = next((i + 1 for i, c in enumerate(channels) if c.id == after.id), None) if index is None: raise InvalidArgument('Could not resolve appropriate move position') channels.insert(max((index + offset), 0), self) payload = [] lock_permissions = kwargs.get('sync_permissions', False) reason = kwargs.get('reason') for index, channel in enumerate(channels): d = { 'id': channel.id, 'position': index } if parent_id is not ... and channel.id == self.id: d.update(parent_id=parent_id, lock_permissions=lock_permissions) payload.append(d) await self._state.http.bulk_channel_update(self.guild.id, payload, reason=reason) async def create_invite(self, *, reason=None, **fields): """|coro| Creates an instant invite from a text or voice channel. You must have the :attr:`~Permissions.create_instant_invite` permission to do this. Parameters ------------ max_age: :class:`int` How long the invite should last in seconds. If it's 0 then the invite doesn't expire. Defaults to ``0``. max_uses: :class:`int` How many uses the invite could be used for. If it's 0 then there are unlimited uses. Defaults to ``0``. temporary: :class:`bool` Denotes that the invite grants temporary membership (i.e. they get kicked after they disconnect). Defaults to ``False``. unique: :class:`bool` Indicates if a unique invite URL should be created. Defaults to True. If this is set to ``False`` then it will return a previously created invite. reason: Optional[:class:`str`] The reason for creating this invite. Shows up on the audit log. Raises ------- ~discord.HTTPException Invite creation failed. ~discord.NotFound The channel that was passed is a category or an invalid channel. Returns -------- :class:`~discord.Invite` The invite that was created. """ data = await self._state.http.create_invite(self.id, reason=reason, **fields) return Invite.from_incomplete(data=data, state=self._state) async def invites(self): """|coro| Returns a list of all active instant invites from this channel. You must have :attr:`~Permissions.manage_channels` to get this information. Raises ------- ~discord.Forbidden You do not have proper permissions to get the information. ~discord.HTTPException An error occurred while fetching the information. Returns ------- List[:class:`~discord.Invite`] The list of invites that are currently active. """ state = self._state data = await state.http.invites_from_channel(self.id) result = [] for invite in data: invite['channel'] = self invite['guild'] = self.guild result.append(Invite(state=state, data=invite)) return result class Messageable(metaclass=abc.ABCMeta): """An ABC that details the common operations on a model that can send messages. The following implement this ABC: - :class:`~discord.TextChannel` - :class:`~discord.DMChannel` - :class:`~discord.GroupChannel` - :class:`~discord.User` - :class:`~discord.Member` - :class:`~discord.ext.commands.Context` """ __slots__ = () @abc.abstractmethod async def _get_channel(self): raise NotImplementedError async def send(self, content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None): """|coro| Sends a message to the destination with the content given. The content must be a type that can convert to a string through ``str(content)``. If the content is set to ``None`` (the default), then the ``embed`` parameter must be provided. To upload a single file, the ``file`` parameter should be used with a single :class:`~discord.File` object. To upload multiple files, the ``files`` parameter should be used with a :class:`list` of :class:`~discord.File` objects. **Specifying both parameters will lead to an exception**. If the ``embed`` parameter is provided, it must be of type :class:`~discord.Embed` and it must be a rich embed type. Parameters ------------ content: :class:`str` The content of the message to send. tts: :class:`bool` Indicates if the message should be sent using text-to-speech. embed: :class:`~discord.Embed` The rich embed for the content. file: :class:`~discord.File` The file to upload. files: List[:class:`~discord.File`] A list of files to upload. Must be a maximum of 10. nonce: :class:`int` The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. delete_after: :class:`float` If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored. allowed_mentions: :class:`~discord.AllowedMentions` Controls the mentions being processed in this message. If this is passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`. If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` are used instead. .. versionadded:: 1.4 reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`] A reference to the :class:`~discord.Message` to which you are replying, this can be created using :meth:`~discord.Message.to_reference` or passed directly as a :class:`~discord.Message`. You can control whether this mentions the author of the referenced message using the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions`` or by setting ``mention_author``. .. versionadded:: 1.6 mention_author: Optional[:class:`bool`] If set, overrides the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions``. .. versionadded:: 1.6 Raises -------- ~discord.HTTPException Sending the message failed. ~discord.Forbidden You do not have the proper permissions to send the message. ~discord.InvalidArgument The ``files`` list is not of the appropriate size, you specified both ``file`` and ``files``, or the ``reference`` object is not a :class:`~discord.Message` or :class:`~discord.MessageReference`. Returns --------- :class:`~discord.Message` The message that was sent. """ channel = await self._get_channel() state = self._state content = str(content) if content is not None else None if embed is not None: embed = embed.to_dict() if allowed_mentions is not None: if state.allowed_mentions is not None: allowed_mentions = state.allowed_mentions.merge(allowed_mentions).to_dict() else: allowed_mentions = allowed_mentions.to_dict() else: allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict() if mention_author is not None: allowed_mentions = allowed_mentions or AllowedMentions().to_dict() allowed_mentions['replied_user'] = bool(mention_author) if reference is not None: try: reference = reference.to_message_reference_dict() except AttributeError: raise InvalidArgument('reference parameter must be Message or MessageReference') from None if file is not None and files is not None: raise InvalidArgument('cannot pass both file and files parameter to send()') if file is not None: if not isinstance(file, File): raise InvalidArgument('file parameter must be File') try: data = await state.http.send_files(channel.id, files=[file], allowed_mentions=allowed_mentions, content=content, tts=tts, embed=embed, nonce=nonce, message_reference=reference) finally: file.close() elif files is not None: if len(files) > 10: raise InvalidArgument('files parameter must be a list of up to 10 elements') elif not all(isinstance(file, File) for file in files): raise InvalidArgument('files parameter must be a list of File') try: data = await state.http.send_files(channel.id, files=files, content=content, tts=tts, embed=embed, nonce=nonce, allowed_mentions=allowed_mentions, message_reference=reference) finally: for f in files: f.close() else: data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce, allowed_mentions=allowed_mentions, message_reference=reference) ret = state.create_message(channel=channel, data=data) if delete_after is not None: await ret.delete(delay=delete_after) return ret async def trigger_typing(self): """|coro| Triggers a *typing* indicator to the destination. *Typing* indicator will go away after 10 seconds, or after a message is sent. """ channel = await self._get_channel() await self._state.http.send_typing(channel.id) def typing(self): """Returns a context manager that allows you to type for an indefinite period of time. This is useful for denoting long computations in your bot. .. note:: This is both a regular context manager and an async context manager. This means that both ``with`` and ``async with`` work with this. Example Usage: :: async with channel.typing(): # do expensive stuff here await channel.send('done!') """ return Typing(self) async def fetch_message(self, id): """|coro| Retrieves a single :class:`~discord.Message` from the destination. This can only be used by bot accounts. Parameters ------------ id: :class:`int` The message ID to look for. Raises -------- ~discord.NotFound The specified message was not found. ~discord.Forbidden You do not have the permissions required to get a message. ~discord.HTTPException Retrieving the message failed. Returns -------- :class:`~discord.Message` The message asked for. """ channel = await self._get_channel() data = await self._state.http.get_message(channel.id, id) return self._state.create_message(channel=channel, data=data) async def pins(self): """|coro| Retrieves all messages that are currently pinned in the channel. .. note:: Due to a limitation with the Discord API, the :class:`.Message` objects returned by this method do not contain complete :attr:`.Message.reactions` data. Raises ------- ~discord.HTTPException Retrieving the pinned messages failed. Returns -------- List[:class:`~discord.Message`] The messages that are currently pinned. """ channel = await self._get_channel() state = self._state data = await state.http.pins_from(channel.id) return [state.create_message(channel=channel, data=m) for m in data] def history(self, *, limit=100, before=None, after=None, around=None, oldest_first=None): """Returns an :class:`~discord.AsyncIterator` that enables receiving the destination's message history. You must have :attr:`~Permissions.read_message_history` permissions to use this. Examples --------- Usage :: counter = 0 async for message in channel.history(limit=200): if message.author == client.user: counter += 1 Flattening into a list: :: messages = await channel.history(limit=123).flatten() # messages is now a list of Message... All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of messages to retrieve. If ``None``, retrieves every message in the channel. Note, however, that this would make it a slow operation. before: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve messages before this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. after: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve messages after this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. around: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve messages around this date or message. If a date is provided it must be a timezone-naive datetime representing UTC time. When using this argument, the maximum limit is 101. Note that if the limit is an even number then this will return at most limit + 1 messages. oldest_first: Optional[:class:`bool`] If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if ``after`` is specified, otherwise ``False``. Raises ------ ~discord.Forbidden You do not have permissions to get channel message history. ~discord.HTTPException The request to get message history failed. Yields ------- :class:`~discord.Message` The message with the message data parsed. """ return HistoryIterator(self, limit=limit, before=before, after=after, around=around, oldest_first=oldest_first) class Connectable(metaclass=abc.ABCMeta): """An ABC that details the common operations on a channel that can connect to a voice server. The following implement this ABC: - :class:`~discord.VoiceChannel` """ __slots__ = () @abc.abstractmethod def _get_voice_client_key(self): raise NotImplementedError @abc.abstractmethod def _get_voice_state_pair(self): raise NotImplementedError async def connect(self, *, timeout=60.0, reconnect=True, cls=VoiceClient): """|coro| Connects to voice and creates a :class:`VoiceClient` to establish your connection to the voice server. Parameters ----------- timeout: :class:`float` The timeout in seconds to wait for the voice endpoint. reconnect: :class:`bool` Whether the bot should automatically attempt a reconnect if a part of the handshake fails or the gateway goes down. cls: Type[:class:`VoiceProtocol`] A type that subclasses :class:`~discord.VoiceProtocol` to connect with. Defaults to :class:`~discord.VoiceClient`. Raises ------- asyncio.TimeoutError Could not connect to the voice channel in time. ~discord.ClientException You are already connected to a voice channel. ~discord.opus.OpusNotLoaded The opus library has not been loaded. Returns -------- :class:`~discord.VoiceProtocol` A voice client that is fully connected to the voice server. """ key_id, _ = self._get_voice_client_key() state = self._state if state._get_voice_client(key_id): raise ClientException('Already connected to a voice channel.') client = state._get_client() voice = cls(client, self) if not isinstance(voice, VoiceProtocol): raise TypeError('Type must meet VoiceProtocol abstract base class.') state._add_voice_client(key_id, voice) try: await voice.connect(timeout=timeout, reconnect=reconnect) except asyncio.TimeoutError: try: await voice.disconnect(force=True) except Exception: # we don't care if disconnect failed because connection failed pass raise # re-raise return voice
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/abc.py
abc.py
import asyncio import json import logging import sys from urllib.parse import quote as _uriquote import weakref import aiohttp from .errors import HTTPException, Forbidden, NotFound, LoginFailure, DiscordServerError, GatewayNotFound from .gateway import DiscordClientWebSocketResponse from . import __version__, utils log = logging.getLogger(__name__) async def json_or_text(response): text = await response.text(encoding='utf-8') try: if response.headers['content-type'] == 'application/json': return json.loads(text) except KeyError: # Thanks Cloudflare pass return text class Route: BASE = 'https://discord.com/api/v7' def __init__(self, method, path, **parameters): self.path = path self.method = method url = (self.BASE + self.path) if parameters: self.url = url.format(**{k: _uriquote(v) if isinstance(v, str) else v for k, v in parameters.items()}) else: self.url = url # major parameters: self.channel_id = parameters.get('channel_id') self.guild_id = parameters.get('guild_id') @property def bucket(self): # the bucket is just method + path w/ major parameters return '{0.channel_id}:{0.guild_id}:{0.path}'.format(self) class MaybeUnlock: def __init__(self, lock): self.lock = lock self._unlock = True def __enter__(self): return self def defer(self): self._unlock = False def __exit__(self, type, value, traceback): if self._unlock: self.lock.release() # For some reason, the Discord voice websocket expects this header to be # completely lowercase while aiohttp respects spec and does it as case-insensitive aiohttp.hdrs.WEBSOCKET = 'websocket' class HTTPClient: """Represents an HTTP client sending HTTP requests to the Discord API.""" SUCCESS_LOG = '{method} {url} has received {text}' REQUEST_LOG = '{method} {url} with {json} has returned {status}' def __init__(self, connector=None, *, proxy=None, proxy_auth=None, loop=None, unsync_clock=True): self.loop = asyncio.get_event_loop() if loop is None else loop self.connector = connector self.__session = None # filled in static_login self._locks = weakref.WeakValueDictionary() self._global_over = asyncio.Event() self._global_over.set() self.token = None self.bot_token = False self.proxy = proxy self.proxy_auth = proxy_auth self.use_clock = not unsync_clock user_agent = 'DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}' self.user_agent = user_agent.format(__version__, sys.version_info, aiohttp.__version__) def recreate(self): if self.__session.closed: self.__session = aiohttp.ClientSession(connector=self.connector, ws_response_class=DiscordClientWebSocketResponse) async def ws_connect(self, url, *, compress=0): kwargs = { 'proxy_auth': self.proxy_auth, 'proxy': self.proxy, 'max_msg_size': 0, 'timeout': 30.0, 'autoclose': False, 'headers': { 'User-Agent': self.user_agent, }, 'compress': compress } return await self.__session.ws_connect(url, **kwargs) async def request(self, route, *, files=None, form=None, **kwargs): bucket = route.bucket method = route.method url = route.url lock = self._locks.get(bucket) if lock is None: lock = asyncio.Lock() if bucket is not None: self._locks[bucket] = lock # header creation headers = { 'User-Agent': self.user_agent, 'X-Ratelimit-Precision': 'millisecond', } if self.token is not None: headers['Authorization'] = 'Bot ' + self.token if self.bot_token else self.token # some checking if it's a JSON request if 'json' in kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) try: reason = kwargs.pop('reason') except KeyError: pass else: if reason: headers['X-Audit-Log-Reason'] = _uriquote(reason, safe='/ ') kwargs['headers'] = headers # Proxy support if self.proxy is not None: kwargs['proxy'] = self.proxy if self.proxy_auth is not None: kwargs['proxy_auth'] = self.proxy_auth if not self._global_over.is_set(): # wait until the global lock is complete await self._global_over.wait() await lock.acquire() with MaybeUnlock(lock) as maybe_lock: for tries in range(5): if files: for f in files: f.reset(seek=tries) if form: form_data = aiohttp.FormData() for params in form: form_data.add_field(**params) kwargs['data'] = form_data try: async with self.__session.request(method, url, **kwargs) as r: log.debug('%s %s with %s has returned %s', method, url, kwargs.get('data'), r.status) # even errors have text involved in them so this is safe to call data = await json_or_text(r) # check if we have rate limit header information remaining = r.headers.get('X-Ratelimit-Remaining') if remaining == '0' and r.status != 429: # we've depleted our current bucket delta = utils._parse_ratelimit_header(r, use_clock=self.use_clock) log.debug('A rate limit bucket has been exhausted (bucket: %s, retry: %s).', bucket, delta) maybe_lock.defer() self.loop.call_later(delta, lock.release) # the request was successful so just return the text/json if 300 > r.status >= 200: log.debug('%s %s has received %s', method, url, data) return data # we are being rate limited if r.status == 429: if not r.headers.get('Via'): # Banned by Cloudflare more than likely. raise HTTPException(r, data) fmt = 'We are being rate limited. Retrying in %.2f seconds. Handled under the bucket "%s"' # sleep a bit retry_after = data['retry_after'] / 1000.0 log.warning(fmt, retry_after, bucket) # check if it's a global rate limit is_global = data.get('global', False) if is_global: log.warning('Global rate limit has been hit. Retrying in %.2f seconds.', retry_after) self._global_over.clear() await asyncio.sleep(retry_after) log.debug('Done sleeping for the rate limit. Retrying...') # release the global lock now that the # global rate limit has passed if is_global: self._global_over.set() log.debug('Global rate limit is now over.') continue # we've received a 500 or 502, unconditional retry if r.status in {500, 502}: await asyncio.sleep(1 + tries * 2) continue # the usual error cases if r.status == 403: raise Forbidden(r, data) elif r.status == 404: raise NotFound(r, data) elif r.status == 503: raise DiscordServerError(r, data) else: raise HTTPException(r, data) # This is handling exceptions from the request except OSError as e: # Connection reset by peer if tries < 4 and e.errno in (54, 10054): continue raise # We've run out of retries, raise. if r.status >= 500: raise DiscordServerError(r, data) raise HTTPException(r, data) async def get_from_cdn(self, url): async with self.__session.get(url) as resp: if resp.status == 200: return await resp.read() elif resp.status == 404: raise NotFound(resp, 'asset not found') elif resp.status == 403: raise Forbidden(resp, 'cannot retrieve asset') else: raise HTTPException(resp, 'failed to get asset') # state management async def close(self): if self.__session: await self.__session.close() def _token(self, token, *, bot=True): self.token = token self.bot_token = bot self._ack_token = None # login management async def static_login(self, token, *, bot): # Necessary to get aiohttp to stop complaining about session creation self.__session = aiohttp.ClientSession(connector=self.connector, ws_response_class=DiscordClientWebSocketResponse) old_token, old_bot = self.token, self.bot_token self._token(token, bot=bot) try: data = await self.request(Route('GET', '/users/@me')) except HTTPException as exc: self._token(old_token, bot=old_bot) if exc.response.status == 401: raise LoginFailure('Improper token has been passed.') from exc raise return data def logout(self): return self.request(Route('POST', '/auth/logout')) # Group functionality def start_group(self, user_id, recipients): payload = { 'recipients': recipients } return self.request(Route('POST', '/users/{user_id}/channels', user_id=user_id), json=payload) def leave_group(self, channel_id): return self.request(Route('DELETE', '/channels/{channel_id}', channel_id=channel_id)) def add_group_recipient(self, channel_id, user_id): r = Route('PUT', '/channels/{channel_id}/recipients/{user_id}', channel_id=channel_id, user_id=user_id) return self.request(r) def remove_group_recipient(self, channel_id, user_id): r = Route('DELETE', '/channels/{channel_id}/recipients/{user_id}', channel_id=channel_id, user_id=user_id) return self.request(r) def edit_group(self, channel_id, **options): valid_keys = ('name', 'icon') payload = { k: v for k, v in options.items() if k in valid_keys } return self.request(Route('PATCH', '/channels/{channel_id}', channel_id=channel_id), json=payload) def convert_group(self, channel_id): return self.request(Route('POST', '/channels/{channel_id}/convert', channel_id=channel_id)) # Message management def start_private_message(self, user_id): payload = { 'recipient_id': user_id } return self.request(Route('POST', '/users/@me/channels'), json=payload) def send_message(self, channel_id, content, *, tts=False, embed=None, nonce=None, allowed_mentions=None, message_reference=None): r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id) payload = {} if content: payload['content'] = content if tts: payload['tts'] = True if embed: payload['embed'] = embed if nonce: payload['nonce'] = nonce if allowed_mentions: payload['allowed_mentions'] = allowed_mentions if message_reference: payload['message_reference'] = message_reference return self.request(r, json=payload) def send_typing(self, channel_id): return self.request(Route('POST', '/channels/{channel_id}/typing', channel_id=channel_id)) def send_files(self, channel_id, *, files, content=None, tts=False, embed=None, nonce=None, allowed_mentions=None, message_reference=None): r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id) form = [] payload = {'tts': tts} if content: payload['content'] = content if embed: payload['embed'] = embed if nonce: payload['nonce'] = nonce if allowed_mentions: payload['allowed_mentions'] = allowed_mentions if message_reference: payload['message_reference'] = message_reference form.append({'name': 'payload_json', 'value': utils.to_json(payload)}) if len(files) == 1: file = files[0] form.append({ 'name': 'file', 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream' }) else: for index, file in enumerate(files): form.append({ 'name': 'file%s' % index, 'value': file.fp, 'filename': file.filename, 'content_type': 'application/octet-stream' }) return self.request(r, form=form, files=files) async def ack_message(self, channel_id, message_id): r = Route('POST', '/channels/{channel_id}/messages/{message_id}/ack', channel_id=channel_id, message_id=message_id) data = await self.request(r, json={'token': self._ack_token}) self._ack_token = data['token'] def ack_guild(self, guild_id): return self.request(Route('POST', '/guilds/{guild_id}/ack', guild_id=guild_id)) def delete_message(self, channel_id, message_id, *, reason=None): r = Route('DELETE', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id) return self.request(r, reason=reason) def delete_messages(self, channel_id, message_ids, *, reason=None): r = Route('POST', '/channels/{channel_id}/messages/bulk_delete', channel_id=channel_id) payload = { 'messages': message_ids } return self.request(r, json=payload, reason=reason) def edit_message(self, channel_id, message_id, **fields): r = Route('PATCH', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id) return self.request(r, json=fields) def add_reaction(self, channel_id, message_id, emoji): r = Route('PUT', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me', channel_id=channel_id, message_id=message_id, emoji=emoji) return self.request(r) def remove_reaction(self, channel_id, message_id, emoji, member_id): r = Route('DELETE', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/{member_id}', channel_id=channel_id, message_id=message_id, member_id=member_id, emoji=emoji) return self.request(r) def remove_own_reaction(self, channel_id, message_id, emoji): r = Route('DELETE', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me', channel_id=channel_id, message_id=message_id, emoji=emoji) return self.request(r) def get_reaction_users(self, channel_id, message_id, emoji, limit, after=None): r = Route('GET', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}', channel_id=channel_id, message_id=message_id, emoji=emoji) params = {'limit': limit} if after: params['after'] = after return self.request(r, params=params) def clear_reactions(self, channel_id, message_id): r = Route('DELETE', '/channels/{channel_id}/messages/{message_id}/reactions', channel_id=channel_id, message_id=message_id) return self.request(r) def clear_single_reaction(self, channel_id, message_id, emoji): r = Route('DELETE', '/channels/{channel_id}/messages/{message_id}/reactions/{emoji}', channel_id=channel_id, message_id=message_id, emoji=emoji) return self.request(r) def get_message(self, channel_id, message_id): r = Route('GET', '/channels/{channel_id}/messages/{message_id}', channel_id=channel_id, message_id=message_id) return self.request(r) def get_channel(self, channel_id): r = Route('GET', '/channels/{channel_id}', channel_id=channel_id) return self.request(r) def logs_from(self, channel_id, limit, before=None, after=None, around=None): params = { 'limit': limit } if before is not None: params['before'] = before if after is not None: params['after'] = after if around is not None: params['around'] = around return self.request(Route('GET', '/channels/{channel_id}/messages', channel_id=channel_id), params=params) def publish_message(self, channel_id, message_id): return self.request(Route('POST', '/channels/{channel_id}/messages/{message_id}/crosspost', channel_id=channel_id, message_id=message_id)) def pin_message(self, channel_id, message_id, reason=None): return self.request(Route('PUT', '/channels/{channel_id}/pins/{message_id}', channel_id=channel_id, message_id=message_id), reason=reason) def unpin_message(self, channel_id, message_id, reason=None): return self.request(Route('DELETE', '/channels/{channel_id}/pins/{message_id}', channel_id=channel_id, message_id=message_id), reason=reason) def pins_from(self, channel_id): return self.request(Route('GET', '/channels/{channel_id}/pins', channel_id=channel_id)) # Member management def kick(self, user_id, guild_id, reason=None): r = Route('DELETE', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) if reason: # thanks aiohttp r.url = '{0.url}?reason={1}'.format(r, _uriquote(reason)) return self.request(r) def ban(self, user_id, guild_id, delete_message_days=1, reason=None): r = Route('PUT', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id) params = { 'delete_message_days': delete_message_days, } if reason: # thanks aiohttp r.url = '{0.url}?reason={1}'.format(r, _uriquote(reason)) return self.request(r, params=params) def unban(self, user_id, guild_id, *, reason=None): r = Route('DELETE', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id) return self.request(r, reason=reason) def guild_voice_state(self, user_id, guild_id, *, mute=None, deafen=None, reason=None): r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) payload = {} if mute is not None: payload['mute'] = mute if deafen is not None: payload['deaf'] = deafen return self.request(r, json=payload, reason=reason) def edit_profile(self, password, username, avatar, **fields): payload = { 'password': password, 'username': username, 'avatar': avatar } if 'email' in fields: payload['email'] = fields['email'] if 'new_password' in fields: payload['new_password'] = fields['new_password'] return self.request(Route('PATCH', '/users/@me'), json=payload) def change_my_nickname(self, guild_id, nickname, *, reason=None): r = Route('PATCH', '/guilds/{guild_id}/members/@me/nick', guild_id=guild_id) payload = { 'nick': nickname } return self.request(r, json=payload, reason=reason) def change_nickname(self, guild_id, user_id, nickname, *, reason=None): r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) payload = { 'nick': nickname } return self.request(r, json=payload, reason=reason) def edit_my_voice_state(self, guild_id, payload): r = Route('PATCH', '/guilds/{guild_id}/voice-states/@me', guild_id=guild_id) return self.request(r, json=payload) def edit_voice_state(self, guild_id, user_id, payload): r = Route('PATCH', '/guilds/{guild_id}/voice-states/{user_id}', guild_id=guild_id, user_id=user_id) return self.request(r, json=payload) def edit_member(self, guild_id, user_id, *, reason=None, **fields): r = Route('PATCH', '/guilds/{guild_id}/members/{user_id}', guild_id=guild_id, user_id=user_id) return self.request(r, json=fields, reason=reason) # Channel management def edit_channel(self, channel_id, *, reason=None, **options): r = Route('PATCH', '/channels/{channel_id}', channel_id=channel_id) valid_keys = ('name', 'parent_id', 'topic', 'bitrate', 'nsfw', 'user_limit', 'position', 'permission_overwrites', 'rate_limit_per_user', 'type', 'rtc_region') payload = { k: v for k, v in options.items() if k in valid_keys } return self.request(r, reason=reason, json=payload) def bulk_channel_update(self, guild_id, data, *, reason=None): r = Route('PATCH', '/guilds/{guild_id}/channels', guild_id=guild_id) return self.request(r, json=data, reason=reason) def create_channel(self, guild_id, channel_type, *, reason=None, **options): payload = { 'type': channel_type } valid_keys = ('name', 'parent_id', 'topic', 'bitrate', 'nsfw', 'user_limit', 'position', 'permission_overwrites', 'rate_limit_per_user', 'rtc_region') payload.update({ k: v for k, v in options.items() if k in valid_keys and v is not None }) return self.request(Route('POST', '/guilds/{guild_id}/channels', guild_id=guild_id), json=payload, reason=reason) def delete_channel(self, channel_id, *, reason=None): return self.request(Route('DELETE', '/channels/{channel_id}', channel_id=channel_id), reason=reason) # Webhook management def create_webhook(self, channel_id, *, name, avatar=None, reason=None): payload = { 'name': name } if avatar is not None: payload['avatar'] = avatar r = Route('POST', '/channels/{channel_id}/webhooks', channel_id=channel_id) return self.request(r, json=payload, reason=reason) def channel_webhooks(self, channel_id): return self.request(Route('GET', '/channels/{channel_id}/webhooks', channel_id=channel_id)) def guild_webhooks(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/webhooks', guild_id=guild_id)) def get_webhook(self, webhook_id): return self.request(Route('GET', '/webhooks/{webhook_id}', webhook_id=webhook_id)) def follow_webhook(self, channel_id, webhook_channel_id, reason=None): payload = { 'webhook_channel_id': str(webhook_channel_id) } return self.request(Route('POST', '/channels/{channel_id}/followers', channel_id=channel_id), json=payload, reason=reason) # Guild management def get_guilds(self, limit, before=None, after=None): params = { 'limit': limit } if before: params['before'] = before if after: params['after'] = after return self.request(Route('GET', '/users/@me/guilds'), params=params) def leave_guild(self, guild_id): return self.request(Route('DELETE', '/users/@me/guilds/{guild_id}', guild_id=guild_id)) def get_guild(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}', guild_id=guild_id)) def delete_guild(self, guild_id): return self.request(Route('DELETE', '/guilds/{guild_id}', guild_id=guild_id)) def create_guild(self, name, region, icon): payload = { 'name': name, 'icon': icon, 'region': region } return self.request(Route('POST', '/guilds'), json=payload) def edit_guild(self, guild_id, *, reason=None, **fields): valid_keys = ('name', 'region', 'icon', 'afk_timeout', 'owner_id', 'afk_channel_id', 'splash', 'verification_level', 'system_channel_id', 'default_message_notifications', 'description', 'explicit_content_filter', 'banner', 'system_channel_flags', 'rules_channel_id', 'public_updates_channel_id', 'preferred_locale',) payload = { k: v for k, v in fields.items() if k in valid_keys } return self.request(Route('PATCH', '/guilds/{guild_id}', guild_id=guild_id), json=payload, reason=reason) def get_template(self, code): return self.request(Route('GET', '/guilds/templates/{code}', code=code)) def guild_templates(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/templates', guild_id=guild_id)) def create_template(self, guild_id, payload): return self.request(Route('POST', '/guilds/{guild_id}/templates', guild_id=guild_id), json=payload) def sync_template(self, guild_id, code): return self.request(Route('PUT', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code)) def edit_template(self, guild_id, code, payload): valid_keys = ( 'name', 'description', ) payload = { k: v for k, v in payload.items() if k in valid_keys } return self.request(Route('PATCH', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code), json=payload) def delete_template(self, guild_id, code): return self.request(Route('DELETE', '/guilds/{guild_id}/templates/{code}', guild_id=guild_id, code=code)) def create_from_template(self, code, name, region, icon): payload = { 'name': name, 'icon': icon, 'region': region } return self.request(Route('POST', '/guilds/templates/{code}', code=code), json=payload) def get_bans(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/bans', guild_id=guild_id)) def get_ban(self, user_id, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id)) def get_vanity_code(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/vanity-url', guild_id=guild_id)) def change_vanity_code(self, guild_id, code, *, reason=None): payload = {'code': code} return self.request(Route('PATCH', '/guilds/{guild_id}/vanity-url', guild_id=guild_id), json=payload, reason=reason) def get_all_guild_channels(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/channels', guild_id=guild_id)) def get_members(self, guild_id, limit, after): params = { 'limit': limit, } if after: params['after'] = after r = Route('GET', '/guilds/{guild_id}/members', guild_id=guild_id) return self.request(r, params=params) def get_member(self, guild_id, member_id): return self.request(Route('GET', '/guilds/{guild_id}/members/{member_id}', guild_id=guild_id, member_id=member_id)) def prune_members(self, guild_id, days, compute_prune_count, roles, *, reason=None): payload = { 'days': days, 'compute_prune_count': 'true' if compute_prune_count else 'false' } if roles: payload['include_roles'] = ', '.join(roles) return self.request(Route('POST', '/guilds/{guild_id}/prune', guild_id=guild_id), json=payload, reason=reason) def estimate_pruned_members(self, guild_id, days, roles): params = { 'days': days } if roles: params['include_roles'] = ', '.join(roles) return self.request(Route('GET', '/guilds/{guild_id}/prune', guild_id=guild_id), params=params) def get_all_custom_emojis(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/emojis', guild_id=guild_id)) def get_custom_emoji(self, guild_id, emoji_id): return self.request(Route('GET', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id)) def create_custom_emoji(self, guild_id, name, image, *, roles=None, reason=None): payload = { 'name': name, 'image': image, 'roles': roles or [] } r = Route('POST', '/guilds/{guild_id}/emojis', guild_id=guild_id) return self.request(r, json=payload, reason=reason) def delete_custom_emoji(self, guild_id, emoji_id, *, reason=None): r = Route('DELETE', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id) return self.request(r, reason=reason) def edit_custom_emoji(self, guild_id, emoji_id, *, name, roles=None, reason=None): payload = { 'name': name, 'roles': roles or [] } r = Route('PATCH', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id) return self.request(r, json=payload, reason=reason) def get_all_integrations(self, guild_id): r = Route('GET', '/guilds/{guild_id}/integrations', guild_id=guild_id) return self.request(r) def create_integration(self, guild_id, type, id): payload = { 'type': type, 'id': id } r = Route('POST', '/guilds/{guild_id}/integrations', guild_id=guild_id) return self.request(r, json=payload) def edit_integration(self, guild_id, integration_id, **payload): r = Route('PATCH', '/guilds/{guild_id}/integrations/{integration_id}', guild_id=guild_id, integration_id=integration_id) return self.request(r, json=payload) def sync_integration(self, guild_id, integration_id): r = Route('POST', '/guilds/{guild_id}/integrations/{integration_id}/sync', guild_id=guild_id, integration_id=integration_id) return self.request(r) def delete_integration(self, guild_id, integration_id): r = Route('DELETE', '/guilds/{guild_id}/integrations/{integration_id}', guild_id=guild_id, integration_id=integration_id) return self.request(r) def get_audit_logs(self, guild_id, limit=100, before=None, after=None, user_id=None, action_type=None): params = {'limit': limit} if before: params['before'] = before if after: params['after'] = after if user_id: params['user_id'] = user_id if action_type: params['action_type'] = action_type r = Route('GET', '/guilds/{guild_id}/audit-logs', guild_id=guild_id) return self.request(r, params=params) def get_widget(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/widget.json', guild_id=guild_id)) # Invite management def create_invite(self, channel_id, *, reason=None, **options): r = Route('POST', '/channels/{channel_id}/invites', channel_id=channel_id) payload = { 'max_age': options.get('max_age', 0), 'max_uses': options.get('max_uses', 0), 'temporary': options.get('temporary', False), 'unique': options.get('unique', True) } return self.request(r, reason=reason, json=payload) def get_invite(self, invite_id, *, with_counts=True): params = { 'with_counts': int(with_counts) } return self.request(Route('GET', '/invites/{invite_id}', invite_id=invite_id), params=params) def invites_from(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/invites', guild_id=guild_id)) def invites_from_channel(self, channel_id): return self.request(Route('GET', '/channels/{channel_id}/invites', channel_id=channel_id)) def delete_invite(self, invite_id, *, reason=None): return self.request(Route('DELETE', '/invites/{invite_id}', invite_id=invite_id), reason=reason) # Role management def get_roles(self, guild_id): return self.request(Route('GET', '/guilds/{guild_id}/roles', guild_id=guild_id)) def edit_role(self, guild_id, role_id, *, reason=None, **fields): r = Route('PATCH', '/guilds/{guild_id}/roles/{role_id}', guild_id=guild_id, role_id=role_id) valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable') payload = { k: v for k, v in fields.items() if k in valid_keys } return self.request(r, json=payload, reason=reason) def delete_role(self, guild_id, role_id, *, reason=None): r = Route('DELETE', '/guilds/{guild_id}/roles/{role_id}', guild_id=guild_id, role_id=role_id) return self.request(r, reason=reason) def replace_roles(self, user_id, guild_id, role_ids, *, reason=None): return self.edit_member(guild_id=guild_id, user_id=user_id, roles=role_ids, reason=reason) def create_role(self, guild_id, *, reason=None, **fields): r = Route('POST', '/guilds/{guild_id}/roles', guild_id=guild_id) return self.request(r, json=fields, reason=reason) def move_role_position(self, guild_id, positions, *, reason=None): r = Route('PATCH', '/guilds/{guild_id}/roles', guild_id=guild_id) return self.request(r, json=positions, reason=reason) def add_role(self, guild_id, user_id, role_id, *, reason=None): r = Route('PUT', '/guilds/{guild_id}/members/{user_id}/roles/{role_id}', guild_id=guild_id, user_id=user_id, role_id=role_id) return self.request(r, reason=reason) def remove_role(self, guild_id, user_id, role_id, *, reason=None): r = Route('DELETE', '/guilds/{guild_id}/members/{user_id}/roles/{role_id}', guild_id=guild_id, user_id=user_id, role_id=role_id) return self.request(r, reason=reason) def edit_channel_permissions(self, channel_id, target, allow, deny, type, *, reason=None): payload = { 'id': target, 'allow': allow, 'deny': deny, 'type': type } r = Route('PUT', '/channels/{channel_id}/permissions/{target}', channel_id=channel_id, target=target) return self.request(r, json=payload, reason=reason) def delete_channel_permissions(self, channel_id, target, *, reason=None): r = Route('DELETE', '/channels/{channel_id}/permissions/{target}', channel_id=channel_id, target=target) return self.request(r, reason=reason) # Voice management def move_member(self, user_id, guild_id, channel_id, *, reason=None): return self.edit_member(guild_id=guild_id, user_id=user_id, channel_id=channel_id, reason=reason) # Relationship related def remove_relationship(self, user_id): r = Route('DELETE', '/users/@me/relationships/{user_id}', user_id=user_id) return self.request(r) def add_relationship(self, user_id, type=None): r = Route('PUT', '/users/@me/relationships/{user_id}', user_id=user_id) payload = {} if type is not None: payload['type'] = type return self.request(r, json=payload) def send_friend_request(self, username, discriminator): r = Route('POST', '/users/@me/relationships') payload = { 'username': username, 'discriminator': int(discriminator) } return self.request(r, json=payload) # Misc def application_info(self): return self.request(Route('GET', '/oauth2/applications/@me')) async def get_gateway(self, *, encoding='json', v=6, zlib=True): try: data = await self.request(Route('GET', '/gateway')) except HTTPException as exc: raise GatewayNotFound() from exc if zlib: value = '{0}?encoding={1}&v={2}&compress=zlib-stream' else: value = '{0}?encoding={1}&v={2}' return value.format(data['url'], encoding, v) async def get_bot_gateway(self, *, encoding='json', v=6, zlib=True): try: data = await self.request(Route('GET', '/gateway/bot')) except HTTPException as exc: raise GatewayNotFound() from exc if zlib: value = '{0}?encoding={1}&v={2}&compress=zlib-stream' else: value = '{0}?encoding={1}&v={2}' return data['shards'], value.format(data['url'], encoding, v) def get_user(self, user_id): return self.request(Route('GET', '/users/{user_id}', user_id=user_id)) def get_user_profile(self, user_id): return self.request(Route('GET', '/users/{user_id}/profile', user_id=user_id)) def get_mutual_friends(self, user_id): return self.request(Route('GET', '/users/{user_id}/relationships', user_id=user_id)) def change_hypesquad_house(self, house_id): payload = {'house_id': house_id} return self.request(Route('POST', '/hypesquad/online'), json=payload) def leave_hypesquad_house(self): return self.request(Route('DELETE', '/hypesquad/online')) def edit_settings(self, **payload): return self.request(Route('PATCH', '/users/@me/settings'), json=payload)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/http.py
http.py
import asyncio import datetime import re import io from . import utils from .reaction import Reaction from .emoji import Emoji from .partial_emoji import PartialEmoji from .calls import CallMessage from .enums import MessageType, ChannelType, try_enum from .errors import InvalidArgument, ClientException, HTTPException from .embeds import Embed from .member import Member from .flags import MessageFlags from .file import File from .utils import escape_mentions from .guild import Guild from .mixins import Hashable from .sticker import Sticker __all__ = ( 'Attachment', 'Message', 'PartialMessage', 'MessageReference', 'DeletedReferencedMessage', ) def convert_emoji_reaction(emoji): if isinstance(emoji, Reaction): emoji = emoji.emoji if isinstance(emoji, Emoji): return '%s:%s' % (emoji.name, emoji.id) if isinstance(emoji, PartialEmoji): return emoji._as_reaction() if isinstance(emoji, str): # Reactions can be in :name:id format, but not <:name:id>. # No existing emojis have <> in them, so this should be okay. return emoji.strip('<>') raise InvalidArgument('emoji argument must be str, Emoji, or Reaction not {.__class__.__name__}.'.format(emoji)) class Attachment(Hashable): """Represents an attachment from Discord. .. container:: operations .. describe:: str(x) Returns the URL of the attachment. .. describe:: x == y Checks if the attachment is equal to another attachment. .. describe:: x != y Checks if the attachment is not equal to another attachment. .. describe:: hash(x) Returns the hash of the attachment. .. versionchanged:: 1.7 Attachment can now be casted to :class:`str` and is hashable. Attributes ------------ id: :class:`int` The attachment ID. size: :class:`int` The attachment size in bytes. height: Optional[:class:`int`] The attachment's height, in pixels. Only applicable to images and videos. width: Optional[:class:`int`] The attachment's width, in pixels. Only applicable to images and videos. filename: :class:`str` The attachment's filename. url: :class:`str` The attachment URL. If the message this attachment was attached to is deleted, then this will 404. proxy_url: :class:`str` The proxy URL. This is a cached version of the :attr:`~Attachment.url` in the case of images. When the message is deleted, this URL might be valid for a few minutes or not valid at all. content_type: Optional[:class:`str`] The attachment's `media type <https://en.wikipedia.org/wiki/Media_type>`_ .. versionadded:: 1.7 """ __slots__ = ('id', 'size', 'height', 'width', 'filename', 'url', 'proxy_url', '_http', 'content_type') def __init__(self, *, data, state): self.id = int(data['id']) self.size = data['size'] self.height = data.get('height') self.width = data.get('width') self.filename = data['filename'] self.url = data.get('url') self.proxy_url = data.get('proxy_url') self._http = state.http self.content_type = data.get('content_type') def is_spoiler(self): """:class:`bool`: Whether this attachment contains a spoiler.""" return self.filename.startswith('SPOILER_') def __repr__(self): return '<Attachment id={0.id} filename={0.filename!r} url={0.url!r}>'.format(self) def __str__(self): return self.url or '' async def save(self, fp, *, seek_begin=True, use_cached=False): """|coro| Saves this attachment into a file-like object. Parameters ----------- fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. seek_begin: :class:`bool` Whether to seek to the beginning of the file after saving is successfully done. use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments. Raises -------- HTTPException Saving the attachment failed. NotFound The attachment was deleted. Returns -------- :class:`int` The number of bytes written. """ data = await self.read(use_cached=use_cached) if isinstance(fp, io.IOBase) and fp.writable(): written = fp.write(data) if seek_begin: fp.seek(0) return written else: with open(fp, 'wb') as f: return f.write(data) async def read(self, *, use_cached=False): """|coro| Retrieves the content of this attachment as a :class:`bytes` object. .. versionadded:: 1.1 Parameters ----------- use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments. Raises ------ HTTPException Downloading the attachment failed. Forbidden You do not have permissions to access this attachment NotFound The attachment was deleted. Returns ------- :class:`bytes` The contents of the attachment. """ url = self.proxy_url if use_cached else self.url data = await self._http.get_from_cdn(url) return data async def to_file(self, *, use_cached=False, spoiler=False): """|coro| Converts the attachment into a :class:`File` suitable for sending via :meth:`abc.Messageable.send`. .. versionadded:: 1.3 Parameters ----------- use_cached: :class:`bool` Whether to use :attr:`proxy_url` rather than :attr:`url` when downloading the attachment. This will allow attachments to be saved after deletion more often, compared to the regular URL which is generally deleted right after the message is deleted. Note that this can still fail to download deleted attachments if too much time has passed and it does not work on some types of attachments. .. versionadded:: 1.4 spoiler: :class:`bool` Whether the file is a spoiler. .. versionadded:: 1.4 Raises ------ HTTPException Downloading the attachment failed. Forbidden You do not have permissions to access this attachment NotFound The attachment was deleted. Returns ------- :class:`File` The attachment as a file suitable for sending. """ data = await self.read(use_cached=use_cached) return File(io.BytesIO(data), filename=self.filename, spoiler=spoiler) class DeletedReferencedMessage: """A special sentinel type that denotes whether the resolved message referenced message had since been deleted. The purpose of this class is to separate referenced messages that could not be fetched and those that were previously fetched but have since been deleted. .. versionadded:: 1.6 """ __slots__ = ('_parent') def __init__(self, parent): self._parent = parent @property def id(self): """:class:`int`: The message ID of the deleted referenced message.""" return self._parent.message_id @property def channel_id(self): """:class:`int`: The channel ID of the deleted referenced message.""" return self._parent.channel_id @property def guild_id(self): """Optional[:class:`int`]: The guild ID of the deleted referenced message.""" return self._parent.guild_id class MessageReference: """Represents a reference to a :class:`~discord.Message`. .. versionadded:: 1.5 .. versionchanged:: 1.6 This class can now be constructed by users. Attributes ----------- message_id: Optional[:class:`int`] The id of the message referenced. channel_id: :class:`int` The channel id of the message referenced. guild_id: Optional[:class:`int`] The guild id of the message referenced. fail_if_not_exists: :class:`bool` Whether replying to the referenced message should raise :class:`HTTPException` if the message no longer exists or Discord could not fetch the message. .. versionadded:: 1.7 resolved: Optional[Union[:class:`Message`, :class:`DeletedReferencedMessage`]] The message that this reference resolved to. If this is ``None`` then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type :class:`DeletedReferencedMessage`. Currently, this is mainly the replied to message when a user replies to a message. .. versionadded:: 1.6 """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'fail_if_not_exists', 'resolved', '_state') def __init__(self, *, message_id, channel_id, guild_id=None, fail_if_not_exists=True): self._state = None self.resolved = None self.message_id = message_id self.channel_id = channel_id self.guild_id = guild_id self.fail_if_not_exists = fail_if_not_exists @classmethod def with_state(cls, state, data): self = cls.__new__(cls) self.message_id = utils._get_as_snowflake(data, 'message_id') self.channel_id = int(data.pop('channel_id')) self.guild_id = utils._get_as_snowflake(data, 'guild_id') self.fail_if_not_exists = data.get('fail_if_not_exists', True) self._state = state self.resolved = None return self @classmethod def from_message(cls, message, *, fail_if_not_exists=True): """Creates a :class:`MessageReference` from an existing :class:`~discord.Message`. .. versionadded:: 1.6 Parameters ---------- message: :class:`~discord.Message` The message to be converted into a reference. fail_if_not_exists: :class:`bool` Whether replying to the referenced message should raise :class:`HTTPException` if the message no longer exists or Discord could not fetch the message. .. versionadded:: 1.7 Returns ------- :class:`MessageReference` A reference to the message. """ self = cls(message_id=message.id, channel_id=message.channel.id, guild_id=getattr(message.guild, 'id', None), fail_if_not_exists=fail_if_not_exists) self._state = message._state return self @property def cached_message(self): """Optional[:class:`~discord.Message`]: The cached message, if found in the internal message cache.""" return self._state._get_message(self.message_id) @property def jump_url(self): """:class:`str`: Returns a URL that allows the client to jump to the referenced message. .. versionadded:: 1.7 """ guild_id = self.guild_id if self.guild_id is not None else '@me' return 'https://discord.com/channels/{0}/{1.channel_id}/{1.message_id}'.format(guild_id, self) def __repr__(self): return '<MessageReference message_id={0.message_id!r} channel_id={0.channel_id!r} guild_id={0.guild_id!r}>'.format(self) def to_dict(self): result = {'message_id': self.message_id} if self.message_id is not None else {} result['channel_id'] = self.channel_id if self.guild_id is not None: result['guild_id'] = self.guild_id if self.fail_if_not_exists is not None: result['fail_if_not_exists'] = self.fail_if_not_exists return result to_message_reference_dict = to_dict def flatten_handlers(cls): prefix = len('_handle_') handlers = [ (key[prefix:], value) for key, value in cls.__dict__.items() if key.startswith('_handle_') and key != '_handle_member' ] # store _handle_member last handlers.append(('member', cls._handle_member)) cls._HANDLERS = handlers cls._CACHED_SLOTS = [ attr for attr in cls.__slots__ if attr.startswith('_cs_') ] return cls @flatten_handlers class Message(Hashable): r"""Represents a message from Discord. .. container:: operations .. describe:: x == y Checks if two messages are equal. .. describe:: x != y Checks if two messages are not equal. .. describe:: hash(x) Returns the message's hash. Attributes ----------- tts: :class:`bool` Specifies if the message was done with text-to-speech. This can only be accurately received in :func:`on_message` due to a discord limitation. type: :class:`MessageType` The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for :attr:`system_content`. author: :class:`abc.User` A :class:`Member` that sent the message. If :attr:`channel` is a private channel or the user has the left the guild, then it is a :class:`User` instead. content: :class:`str` The actual contents of the message. nonce The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord's servers and is only used ephemerally. embeds: List[:class:`Embed`] A list of embeds the message has. channel: Union[:class:`abc.Messageable`] The :class:`TextChannel` that the message was sent from. Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message. call: Optional[:class:`CallMessage`] The call that the message refers to. This is only applicable to messages of type :attr:`MessageType.call`. .. deprecated:: 1.7 reference: Optional[:class:`~discord.MessageReference`] The message that this message references. This is only applicable to messages of type :attr:`MessageType.pins_add`, crossposted messages created by a followed channel integration, or message replies. .. versionadded:: 1.5 mention_everyone: :class:`bool` Specifies if the message mentions everyone. .. note:: This does not check if the ``@everyone`` or the ``@here`` text is in the message itself. Rather this boolean indicates if either the ``@everyone`` or the ``@here`` text is in the message **and** it did end up mentioning. mentions: List[:class:`abc.User`] A list of :class:`Member` that were mentioned. If the message is in a private message then the list will be of :class:`User` instead. For messages that are not of type :attr:`MessageType.default`\, this array can be used to aid in system messages. For more information, see :attr:`system_content`. .. warning:: The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library. channel_mentions: List[:class:`abc.GuildChannel`] A list of :class:`abc.GuildChannel` that were mentioned. If the message is in a private message then the list is always empty. role_mentions: List[:class:`Role`] A list of :class:`Role` that were mentioned. If the message is in a private message then the list is always empty. id: :class:`int` The message ID. webhook_id: Optional[:class:`int`] If this message was sent by a webhook, then this is the webhook ID's that sent this message. attachments: List[:class:`Attachment`] A list of attachments given to a message. pinned: :class:`bool` Specifies if the message is currently pinned. flags: :class:`MessageFlags` Extra features of the message. .. versionadded:: 1.3 reactions : List[:class:`Reaction`] Reactions to a message. Reactions can be either custom emoji or standard unicode emoji. activity: Optional[:class:`dict`] The activity associated with this message. Sent with Rich-Presence related messages that for example, request joining, spectating, or listening to or with another member. It is a dictionary with the following optional keys: - ``type``: An integer denoting the type of message activity being requested. - ``party_id``: The party ID associated with the party. application: Optional[:class:`dict`] The rich presence enabled application associated with this message. It is a dictionary with the following keys: - ``id``: A string representing the application's ID. - ``name``: A string representing the application's name. - ``description``: A string representing the application's description. - ``icon``: A string representing the icon ID of the application. - ``cover_image``: A string representing the embed's image asset ID. stickers: List[:class:`Sticker`] A list of stickers given to the message. .. versionadded:: 1.6 """ __slots__ = ('_edited_timestamp', 'tts', 'content', 'channel', 'webhook_id', 'mention_everyone', 'embeds', 'id', 'mentions', 'author', '_cs_channel_mentions', '_cs_raw_mentions', 'attachments', '_cs_clean_content', '_cs_raw_channel_mentions', 'nonce', 'pinned', 'role_mentions', '_cs_raw_role_mentions', 'type', 'call', 'flags', '_cs_system_content', '_cs_guild', '_state', 'reactions', 'reference', 'application', 'activity', 'stickers') def __init__(self, *, state, channel, data): self._state = state self.id = int(data['id']) self.webhook_id = utils._get_as_snowflake(data, 'webhook_id') self.reactions = [Reaction(message=self, data=d) for d in data.get('reactions', [])] self.attachments = [Attachment(data=a, state=self._state) for a in data['attachments']] self.embeds = [Embed.from_dict(a) for a in data['embeds']] self.application = data.get('application') self.activity = data.get('activity') self.channel = channel self.call = None self._edited_timestamp = utils.parse_time(data['edited_timestamp']) self.type = try_enum(MessageType, data['type']) self.pinned = data['pinned'] self.flags = MessageFlags._from_value(data.get('flags', 0)) self.mention_everyone = data['mention_everyone'] self.tts = data['tts'] self.content = data['content'] self.nonce = data.get('nonce') self.stickers = [Sticker(data=data, state=state) for data in data.get('stickers', [])] try: ref = data['message_reference'] except KeyError: self.reference = None else: self.reference = ref = MessageReference.with_state(state, ref) try: resolved = data['referenced_message'] except KeyError: pass else: if resolved is None: ref.resolved = DeletedReferencedMessage(ref) else: # Right now the channel IDs match but maybe in the future they won't. if ref.channel_id == channel.id: chan = channel else: chan, _ = state._get_guild_channel(resolved) ref.resolved = self.__class__(channel=chan, data=resolved, state=state) for handler in ('author', 'member', 'mentions', 'mention_roles', 'call', 'flags'): try: getattr(self, '_handle_%s' % handler)(data[handler]) except KeyError: continue def __repr__(self): return '<Message id={0.id} channel={0.channel!r} type={0.type!r} author={0.author!r} flags={0.flags!r}>'.format(self) def _try_patch(self, data, key, transform=None): try: value = data[key] except KeyError: pass else: if transform is None: setattr(self, key, value) else: setattr(self, key, transform(value)) def _add_reaction(self, data, emoji, user_id): reaction = utils.find(lambda r: r.emoji == emoji, self.reactions) is_me = data['me'] = user_id == self._state.self_id if reaction is None: reaction = Reaction(message=self, data=data, emoji=emoji) self.reactions.append(reaction) else: reaction.count += 1 if is_me: reaction.me = is_me return reaction def _remove_reaction(self, data, emoji, user_id): reaction = utils.find(lambda r: r.emoji == emoji, self.reactions) if reaction is None: # already removed? raise ValueError('Emoji already removed?') # if reaction isn't in the list, we crash. This means discord # sent bad data, or we stored improperly reaction.count -= 1 if user_id == self._state.self_id: reaction.me = False if reaction.count == 0: # this raises ValueError if something went wrong as well. self.reactions.remove(reaction) return reaction def _clear_emoji(self, emoji): to_check = str(emoji) for index, reaction in enumerate(self.reactions): if str(reaction.emoji) == to_check: break else: # didn't find anything so just return return del self.reactions[index] return reaction def _update(self, data): # In an update scheme, 'author' key has to be handled before 'member' # otherwise they overwrite each other which is undesirable. # Since there's no good way to do this we have to iterate over every # handler rather than iterating over the keys which is a little slower for key, handler in self._HANDLERS: try: value = data[key] except KeyError: continue else: handler(self, value) # clear the cached properties for attr in self._CACHED_SLOTS: try: delattr(self, attr) except AttributeError: pass def _handle_edited_timestamp(self, value): self._edited_timestamp = utils.parse_time(value) def _handle_pinned(self, value): self.pinned = value def _handle_flags(self, value): self.flags = MessageFlags._from_value(value) def _handle_application(self, value): self.application = value def _handle_activity(self, value): self.activity = value def _handle_mention_everyone(self, value): self.mention_everyone = value def _handle_tts(self, value): self.tts = value def _handle_type(self, value): self.type = try_enum(MessageType, value) def _handle_content(self, value): self.content = value def _handle_attachments(self, value): self.attachments = [Attachment(data=a, state=self._state) for a in value] def _handle_embeds(self, value): self.embeds = [Embed.from_dict(data) for data in value] def _handle_nonce(self, value): self.nonce = value def _handle_author(self, author): self.author = self._state.store_user(author) if isinstance(self.guild, Guild): found = self.guild.get_member(self.author.id) if found is not None: self.author = found def _handle_member(self, member): # The gateway now gives us full Member objects sometimes with the following keys # deaf, mute, joined_at, roles # For the sake of performance I'm going to assume that the only # field that needs *updating* would be the joined_at field. # If there is no Member object (for some strange reason), then we can upgrade # ourselves to a more "partial" member object. author = self.author try: # Update member reference author._update_from_message(member) except AttributeError: # It's a user here # TODO: consider adding to cache here self.author = Member._from_message(message=self, data=member) def _handle_mentions(self, mentions): self.mentions = r = [] guild = self.guild state = self._state if not isinstance(guild, Guild): self.mentions = [state.store_user(m) for m in mentions] return for mention in filter(None, mentions): id_search = int(mention['id']) member = guild.get_member(id_search) if member is not None: r.append(member) else: r.append(Member._try_upgrade(data=mention, guild=guild, state=state)) def _handle_mention_roles(self, role_mentions): self.role_mentions = [] if isinstance(self.guild, Guild): for role_id in map(int, role_mentions): role = self.guild.get_role(role_id) if role is not None: self.role_mentions.append(role) def _handle_call(self, call): if call is None or self.type is not MessageType.call: self.call = None return # we get the participant source from the mentions array or # the author participants = [] for uid in map(int, call.get('participants', [])): if uid == self.author.id: participants.append(self.author) else: user = utils.find(lambda u: u.id == uid, self.mentions) if user is not None: participants.append(user) call['participants'] = participants self.call = CallMessage(message=self, **call) def _rebind_channel_reference(self, new_channel): self.channel = new_channel try: del self._cs_guild except AttributeError: pass @utils.cached_slot_property('_cs_guild') def guild(self): """Optional[:class:`Guild`]: The guild that the message belongs to, if applicable.""" return getattr(self.channel, 'guild', None) @utils.cached_slot_property('_cs_raw_mentions') def raw_mentions(self): """List[:class:`int`]: A property that returns an array of user IDs matched with the syntax of ``<@user_id>`` in the message content. This allows you to receive the user IDs of mentioned users even in a private message context. """ return [int(x) for x in re.findall(r'<@!?([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_raw_channel_mentions') def raw_channel_mentions(self): """List[:class:`int`]: A property that returns an array of channel IDs matched with the syntax of ``<#channel_id>`` in the message content. """ return [int(x) for x in re.findall(r'<#([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_raw_role_mentions') def raw_role_mentions(self): """List[:class:`int`]: A property that returns an array of role IDs matched with the syntax of ``<@&role_id>`` in the message content. """ return [int(x) for x in re.findall(r'<@&([0-9]+)>', self.content)] @utils.cached_slot_property('_cs_channel_mentions') def channel_mentions(self): if self.guild is None: return [] it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions)) return utils._unique(it) @utils.cached_slot_property('_cs_clean_content') def clean_content(self): """:class:`str`: A property that returns the content in a "cleaned up" manner. This basically means that mentions are transformed into the way the client shows it. e.g. ``<#id>`` will transform into ``#name``. This will also transform @everyone and @here mentions into non-mentions. .. note:: This *does not* affect markdown. If you want to escape or remove markdown then use :func:`utils.escape_markdown` or :func:`utils.remove_markdown` respectively, along with this function. """ transformations = { re.escape('<#%s>' % channel.id): '#' + channel.name for channel in self.channel_mentions } mention_transforms = { re.escape('<@%s>' % member.id): '@' + member.display_name for member in self.mentions } # add the <@!user_id> cases as well.. second_mention_transforms = { re.escape('<@!%s>' % member.id): '@' + member.display_name for member in self.mentions } transformations.update(mention_transforms) transformations.update(second_mention_transforms) if self.guild is not None: role_transforms = { re.escape('<@&%s>' % role.id): '@' + role.name for role in self.role_mentions } transformations.update(role_transforms) def repl(obj): return transformations.get(re.escape(obj.group(0)), '') pattern = re.compile('|'.join(transformations.keys())) result = pattern.sub(repl, self.content) return escape_mentions(result) @property def created_at(self): """:class:`datetime.datetime`: The message's creation time in UTC.""" return utils.snowflake_time(self.id) @property def edited_at(self): """Optional[:class:`datetime.datetime`]: A naive UTC datetime object containing the edited time of the message.""" return self._edited_timestamp @property def jump_url(self): """:class:`str`: Returns a URL that allows the client to jump to this message.""" guild_id = getattr(self.guild, 'id', '@me') return 'https://discord.com/channels/{0}/{1.channel.id}/{1.id}'.format(guild_id, self) def is_system(self): """:class:`bool`: Whether the message is a system message. .. versionadded:: 1.3 """ return self.type is not MessageType.default @utils.cached_slot_property('_cs_system_content') def system_content(self): r""":class:`str`: A property that returns the content that is rendered regardless of the :attr:`Message.type`. In the case of :attr:`MessageType.default`\, this just returns the regular :attr:`Message.content`. Otherwise this returns an English message denoting the contents of the system message. """ if self.type is MessageType.default: return self.content if self.type is MessageType.pins_add: return '{0.name} pinned a message to this channel.'.format(self.author) if self.type is MessageType.recipient_add: return '{0.name} added {1.name} to the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.recipient_remove: return '{0.name} removed {1.name} from the group.'.format(self.author, self.mentions[0]) if self.type is MessageType.channel_name_change: return '{0.author.name} changed the channel name: {0.content}'.format(self) if self.type is MessageType.channel_icon_change: return '{0.author.name} changed the channel icon.'.format(self) if self.type is MessageType.new_member: formats = [ "{0} joined the party.", "{0} is here.", "Welcome, {0}. We hope you brought pizza.", "A wild {0} appeared.", "{0} just landed.", "{0} just slid into the server.", "{0} just showed up!", "Welcome {0}. Say hi!", "{0} hopped into the server.", "Everyone welcome {0}!", "Glad you're here, {0}.", "Good to see you, {0}.", "Yay you made it, {0}!", ] # manually reconstruct the epoch with millisecond precision, because # datetime.datetime.timestamp() doesn't return the exact posix # timestamp with the precision that we need created_at_ms = int((self.created_at - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) return formats[created_at_ms % len(formats)].format(self.author.name) if self.type is MessageType.call: # we're at the call message type now, which is a bit more complicated. # we can make the assumption that Message.channel is a PrivateChannel # with the type ChannelType.group or ChannelType.private call_ended = self.call.ended_timestamp is not None if self.channel.me in self.call.participants: return '{0.author.name} started a call.'.format(self) elif call_ended: return 'You missed a call from {0.author.name}'.format(self) else: return '{0.author.name} started a call \N{EM DASH} Join the call.'.format(self) if self.type is MessageType.premium_guild_subscription: return '{0.author.name} just boosted the server!'.format(self) if self.type is MessageType.premium_guild_tier_1: return '{0.author.name} just boosted the server! {0.guild} has achieved **Level 1!**'.format(self) if self.type is MessageType.premium_guild_tier_2: return '{0.author.name} just boosted the server! {0.guild} has achieved **Level 2!**'.format(self) if self.type is MessageType.premium_guild_tier_3: return '{0.author.name} just boosted the server! {0.guild} has achieved **Level 3!**'.format(self) if self.type is MessageType.channel_follow_add: return '{0.author.name} has added {0.content} to this channel'.format(self) if self.type is MessageType.guild_stream: return '{0.author.name} is live! Now streaming {0.author.activity.name}'.format(self) if self.type is MessageType.guild_discovery_disqualified: return 'This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details.' if self.type is MessageType.guild_discovery_requalified: return 'This server is eligible for Server Discovery again and has been automatically relisted!' if self.type is MessageType.guild_discovery_grace_period_initial_warning: return 'This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery.' if self.type is MessageType.guild_discovery_grace_period_final_warning: return 'This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery.' async def delete(self, *, delay=None): """|coro| Deletes the message. Your own messages could be deleted without any proper permissions. However to delete other people's messages, you need the :attr:`~Permissions.manage_messages` permission. .. versionchanged:: 1.1 Added the new ``delay`` keyword-only parameter. Parameters ----------- delay: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message. If the deletion fails then it is silently ignored. Raises ------ Forbidden You do not have proper permissions to delete the message. NotFound The message was deleted already HTTPException Deleting the message failed. """ if delay is not None: async def delete(): await asyncio.sleep(delay) try: await self._state.http.delete_message(self.channel.id, self.id) except HTTPException: pass asyncio.ensure_future(delete(), loop=self._state.loop) else: await self._state.http.delete_message(self.channel.id, self.id) async def edit(self, **fields): """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. .. versionchanged:: 1.3 The ``suppress`` keyword-only parameter was added. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. embed: Optional[:class:`Embed`] The new embed to replace the original with. Could be ``None`` to remove the embed. suppress: :class:`bool` Whether to suppress embeds for the message. This removes all the embeds if set to ``True``. If set to ``False`` this brings the embeds back if they were suppressed. Using this parameter requires :attr:`~.Permissions.manage_messages`. delete_after: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored. allowed_mentions: Optional[:class:`~discord.AllowedMentions`] Controls the mentions being processed in this message. If this is passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`. If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` are used instead. .. versionadded:: 1.4 Raises ------- HTTPException Editing the message failed. Forbidden Tried to suppress a message without permissions or edited a message's content or embed that isn't yours. """ try: content = fields['content'] except KeyError: pass else: if content is not None: fields['content'] = str(content) try: embed = fields['embed'] except KeyError: pass else: if embed is not None: fields['embed'] = embed.to_dict() try: suppress = fields.pop('suppress') except KeyError: pass else: flags = MessageFlags._from_value(self.flags.value) flags.suppress_embeds = suppress fields['flags'] = flags.value delete_after = fields.pop('delete_after', None) try: allowed_mentions = fields.pop('allowed_mentions') except KeyError: pass else: if allowed_mentions is not None: if self._state.allowed_mentions is not None: allowed_mentions = self._state.allowed_mentions.merge(allowed_mentions).to_dict() else: allowed_mentions = allowed_mentions.to_dict() fields['allowed_mentions'] = allowed_mentions if fields: data = await self._state.http.edit_message(self.channel.id, self.id, **fields) self._update(data) if delete_after is not None: await self.delete(delay=delete_after) async def publish(self): """|coro| Publishes this message to your announcement channel. You must have the :attr:`~Permissions.send_messages` permission to do this. If the message is not your own then the :attr:`~Permissions.manage_messages` permission is also needed. Raises ------- Forbidden You do not have the proper permissions to publish this message. HTTPException Publishing the message failed. """ await self._state.http.publish_message(self.channel.id, self.id) async def pin(self, *, reason=None): """|coro| Pins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Parameters ----------- reason: Optional[:class:`str`] The reason for pinning the message. Shows up on the audit log. .. versionadded:: 1.4 Raises ------- Forbidden You do not have permissions to pin the message. NotFound The message or channel was not found or deleted. HTTPException Pinning the message failed, probably due to the channel having more than 50 pinned messages. """ await self._state.http.pin_message(self.channel.id, self.id, reason=reason) self.pinned = True async def unpin(self, *, reason=None): """|coro| Unpins the message. You must have the :attr:`~Permissions.manage_messages` permission to do this in a non-private channel context. Parameters ----------- reason: Optional[:class:`str`] The reason for unpinning the message. Shows up on the audit log. .. versionadded:: 1.4 Raises ------- Forbidden You do not have permissions to unpin the message. NotFound The message or channel was not found or deleted. HTTPException Unpinning the message failed. """ await self._state.http.unpin_message(self.channel.id, self.id, reason=reason) self.pinned = False async def add_reaction(self, emoji): """|coro| Add a reaction to the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. You must have the :attr:`~Permissions.read_message_history` permission to use this. If nobody else has reacted to the message using this emoji, the :attr:`~Permissions.add_reactions` permission is required. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to react with. Raises -------- HTTPException Adding the reaction failed. Forbidden You do not have the proper permissions to react to the message. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = convert_emoji_reaction(emoji) await self._state.http.add_reaction(self.channel.id, self.id, emoji) async def remove_reaction(self, emoji, member): """|coro| Remove a reaction by the member from the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. If the reaction is not your own (i.e. ``member`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``member`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Parameters ------------ emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to remove. member: :class:`abc.Snowflake` The member for which to remove the reaction. Raises -------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The member or emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = convert_emoji_reaction(emoji) if member.id == self._state.self_id: await self._state.http.remove_own_reaction(self.channel.id, self.id, emoji) else: await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id) async def clear_reaction(self, emoji): """|coro| Clears a specific reaction from the message. The emoji may be a unicode emoji or a custom guild :class:`Emoji`. You need the :attr:`~Permissions.manage_messages` permission to use this. .. versionadded:: 1.3 Parameters ----------- emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] The emoji to clear. Raises -------- HTTPException Clearing the reaction failed. Forbidden You do not have the proper permissions to clear the reaction. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ emoji = convert_emoji_reaction(emoji) await self._state.http.clear_single_reaction(self.channel.id, self.id, emoji) async def clear_reactions(self): """|coro| Removes all the reactions from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. Raises -------- HTTPException Removing the reactions failed. Forbidden You do not have the proper permissions to remove all the reactions. """ await self._state.http.clear_reactions(self.channel.id, self.id) @utils.deprecated() async def ack(self): """|coro| Marks this message as read. The user must not be a bot user. .. deprecated:: 1.7 Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state.is_bot: raise ClientException('Must not be a bot account to ack messages.') return await state.http.ack_message(self.channel.id, self.id) async def reply(self, content=None, **kwargs): """|coro| A shortcut method to :meth:`.abc.Messageable.send` to reply to the :class:`.Message`. .. versionadded:: 1.6 Raises -------- ~discord.HTTPException Sending the message failed. ~discord.Forbidden You do not have the proper permissions to send the message. ~discord.InvalidArgument The ``files`` list is not of the appropriate size or you specified both ``file`` and ``files``. Returns --------- :class:`.Message` The message that was sent. """ return await self.channel.send(content, reference=self, **kwargs) def to_reference(self, *, fail_if_not_exists=True): """Creates a :class:`~discord.MessageReference` from the current message. .. versionadded:: 1.6 Parameters ---------- fail_if_not_exists: :class:`bool` Whether replying using the message reference should raise :class:`HTTPException` if the message no longer exists or Discord could not fetch the message. .. versionadded:: 1.7 Returns --------- :class:`~discord.MessageReference` The reference to this message. """ return MessageReference.from_message(self, fail_if_not_exists=fail_if_not_exists) def to_message_reference_dict(self): data = { 'message_id': self.id, 'channel_id': self.channel.id, } if self.guild is not None: data['guild_id'] = self.guild.id return data def implement_partial_methods(cls): msg = Message for name in cls._exported_names: func = getattr(msg, name) setattr(cls, name, func) return cls @implement_partial_methods class PartialMessage(Hashable): """Represents a partial message to aid with working messages when only a message and channel ID are present. There are two ways to construct this class. The first one is through the constructor itself, and the second is via :meth:`TextChannel.get_partial_message` or :meth:`DMChannel.get_partial_message`. Note that this class is trimmed down and has no rich attributes. .. versionadded:: 1.6 .. container:: operations .. describe:: x == y Checks if two partial messages are equal. .. describe:: x != y Checks if two partial messages are not equal. .. describe:: hash(x) Returns the partial message's hash. Attributes ----------- channel: Union[:class:`TextChannel`, :class:`DMChannel`] The channel associated with this partial message. id: :class:`int` The message ID. """ __slots__ = ('channel', 'id', '_cs_guild', '_state') _exported_names = ( 'jump_url', 'delete', 'publish', 'pin', 'unpin', 'add_reaction', 'remove_reaction', 'clear_reaction', 'clear_reactions', 'reply', 'to_reference', 'to_message_reference_dict', ) def __init__(self, *, channel, id): if channel.type not in (ChannelType.text, ChannelType.news, ChannelType.private): raise TypeError('Expected TextChannel or DMChannel not %r' % type(channel)) self.channel = channel self._state = channel._state self.id = id def _update(self, data): # This is used for duck typing purposes. # Just do nothing with the data. pass # Also needed for duck typing purposes # n.b. not exposed pinned = property(None, lambda x, y: ...) def __repr__(self): return '<PartialMessage id={0.id} channel={0.channel!r}>'.format(self) @property def created_at(self): """:class:`datetime.datetime`: The partial message's creation time in UTC.""" return utils.snowflake_time(self.id) @utils.cached_slot_property('_cs_guild') def guild(self): """Optional[:class:`Guild`]: The guild that the partial message belongs to, if applicable.""" return getattr(self.channel, 'guild', None) async def fetch(self): """|coro| Fetches the partial message to a full :class:`Message`. Raises -------- NotFound The message was not found. Forbidden You do not have the permissions required to get a message. HTTPException Retrieving the message failed. Returns -------- :class:`Message` The full message. """ data = await self._state.http.get_message(self.channel.id, self.id) return self._state.create_message(channel=self.channel, data=data) async def edit(self, **fields): """|coro| Edits the message. The content must be able to be transformed into a string via ``str(content)``. .. versionchanged:: 1.7 :class:`discord.Message` is returned instead of ``None`` if an edit took place. Parameters ----------- content: Optional[:class:`str`] The new content to replace the message with. Could be ``None`` to remove the content. embed: Optional[:class:`Embed`] The new embed to replace the original with. Could be ``None`` to remove the embed. suppress: :class:`bool` Whether to suppress embeds for the message. This removes all the embeds if set to ``True``. If set to ``False`` this brings the embeds back if they were suppressed. Using this parameter requires :attr:`~.Permissions.manage_messages`. delete_after: Optional[:class:`float`] If provided, the number of seconds to wait in the background before deleting the message we just edited. If the deletion fails, then it is silently ignored. allowed_mentions: Optional[:class:`~discord.AllowedMentions`] Controls the mentions being processed in this message. If this is passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`. If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` are used instead. Raises ------- NotFound The message was not found. HTTPException Editing the message failed. Forbidden Tried to suppress a message without permissions or edited a message's content or embed that isn't yours. Returns --------- Optional[:class:`Message`] The message that was edited. """ try: content = fields['content'] except KeyError: pass else: if content is not None: fields['content'] = str(content) try: embed = fields['embed'] except KeyError: pass else: if embed is not None: fields['embed'] = embed.to_dict() try: suppress = fields.pop('suppress') except KeyError: pass else: flags = MessageFlags._from_value(0) flags.suppress_embeds = suppress fields['flags'] = flags.value delete_after = fields.pop('delete_after', None) try: allowed_mentions = fields.pop('allowed_mentions') except KeyError: pass else: if allowed_mentions is not None: if self._state.allowed_mentions is not None: allowed_mentions = self._state.allowed_mentions.merge(allowed_mentions).to_dict() else: allowed_mentions = allowed_mentions.to_dict() fields['allowed_mentions'] = allowed_mentions if fields: data = await self._state.http.edit_message(self.channel.id, self.id, **fields) if delete_after is not None: await self.delete(delay=delete_after) if fields: return self._state.create_message(channel=self.channel, data=data)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/message.py
message.py
import time import random class ExponentialBackoff: """An implementation of the exponential backoff algorithm Provides a convenient interface to implement an exponential backoff for reconnecting or retrying transmissions in a distributed network. Once instantiated, the delay method will return the next interval to wait for when retrying a connection or transmission. The maximum delay increases exponentially with each retry up to a maximum of 2^10 * base, and is reset if no more attempts are needed in a period of 2^11 * base seconds. Parameters ---------- base: :class:`int` The base delay in seconds. The first retry-delay will be up to this many seconds. integral: :class:`bool` Set to ``True`` if whole periods of base is desirable, otherwise any number in between may be returned. """ def __init__(self, base=1, *, integral=False): self._base = base self._exp = 0 self._max = 10 self._reset_time = base * 2 ** 11 self._last_invocation = time.monotonic() # Use our own random instance to avoid messing with global one rand = random.Random() rand.seed() self._randfunc = rand.randrange if integral else rand.uniform def delay(self): """Compute the next delay Returns the next delay to wait according to the exponential backoff algorithm. This is a value between 0 and base * 2^exp where exponent starts off at 1 and is incremented at every invocation of this method up to a maximum of 10. If a period of more than base * 2^11 has passed since the last retry, the exponent is reset to 1. """ invocation = time.monotonic() interval = invocation - self._last_invocation self._last_invocation = invocation if interval > self._reset_time: self._exp = 0 self._exp = min(self._exp + 1, self._max) return self._randfunc(0, self._base * 2 ** self._exp)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/backoff.py
backoff.py
import datetime from . import utils from .colour import Colour class _EmptyEmbed: def __bool__(self): return False def __repr__(self): return 'Embed.Empty' def __len__(self): return 0 EmptyEmbed = _EmptyEmbed() class EmbedProxy: def __init__(self, layer): self.__dict__.update(layer) def __len__(self): return len(self.__dict__) def __repr__(self): return 'EmbedProxy(%s)' % ', '.join(('%s=%r' % (k, v) for k, v in self.__dict__.items() if not k.startswith('_'))) def __getattr__(self, attr): return EmptyEmbed class Embed: """Represents a Discord embed. .. container:: operations .. describe:: len(x) Returns the total size of the embed. Useful for checking if it's within the 6000 character limit. Certain properties return an ``EmbedProxy``, a type that acts similar to a regular :class:`dict` except using dotted access, e.g. ``embed.author.icon_url``. If the attribute is invalid or empty, then a special sentinel value is returned, :attr:`Embed.Empty`. For ease of use, all parameters that expect a :class:`str` are implicitly casted to :class:`str` for you. Attributes ----------- title: :class:`str` The title of the embed. This can be set during initialisation. type: :class:`str` The type of embed. Usually "rich". This can be set during initialisation. Possible strings for embed types can be found on discord's `api docs <https://discord.com/developers/docs/resources/channel#embed-object-embed-types>`_ description: :class:`str` The description of the embed. This can be set during initialisation. url: :class:`str` The URL of the embed. This can be set during initialisation. timestamp: :class:`datetime.datetime` The timestamp of the embed content. This could be a naive or aware datetime. colour: Union[:class:`Colour`, :class:`int`] The colour code of the embed. Aliased to ``color`` as well. This can be set during initialisation. Empty A special sentinel value used by ``EmbedProxy`` and this class to denote that the value or attribute is empty. """ __slots__ = ('title', 'url', 'type', '_timestamp', '_colour', '_footer', '_image', '_thumbnail', '_video', '_provider', '_author', '_fields', 'description') Empty = EmptyEmbed def __init__(self, **kwargs): # swap the colour/color aliases try: colour = kwargs['colour'] except KeyError: colour = kwargs.get('color', EmptyEmbed) self.colour = colour self.title = kwargs.get('title', EmptyEmbed) self.type = kwargs.get('type', 'rich') self.url = kwargs.get('url', EmptyEmbed) self.description = kwargs.get('description', EmptyEmbed) if self.title is not EmptyEmbed: self.title = str(self.title) if self.description is not EmptyEmbed: self.description = str(self.description) if self.url is not EmptyEmbed: self.url = str(self.url) try: timestamp = kwargs['timestamp'] except KeyError: pass else: self.timestamp = timestamp @classmethod def from_dict(cls, data): """Converts a :class:`dict` to a :class:`Embed` provided it is in the format that Discord expects it to be in. You can find out about this format in the `official Discord documentation`__. .. _DiscordDocs: https://discord.com/developers/docs/resources/channel#embed-object __ DiscordDocs_ Parameters ----------- data: :class:`dict` The dictionary to convert into an embed. """ # we are bypassing __init__ here since it doesn't apply here self = cls.__new__(cls) # fill in the basic fields self.title = data.get('title', EmptyEmbed) self.type = data.get('type', EmptyEmbed) self.description = data.get('description', EmptyEmbed) self.url = data.get('url', EmptyEmbed) if self.title is not EmptyEmbed: self.title = str(self.title) if self.description is not EmptyEmbed: self.description = str(self.description) if self.url is not EmptyEmbed: self.url = str(self.url) # try to fill in the more rich fields try: self._colour = Colour(value=data['color']) except KeyError: pass try: self._timestamp = utils.parse_time(data['timestamp']) except KeyError: pass for attr in ('thumbnail', 'video', 'provider', 'author', 'fields', 'image', 'footer'): try: value = data[attr] except KeyError: continue else: setattr(self, '_' + attr, value) return self def copy(self): """Returns a shallow copy of the embed.""" return Embed.from_dict(self.to_dict()) def __len__(self): total = len(self.title) + len(self.description) for field in getattr(self, '_fields', []): total += len(field['name']) + len(field['value']) try: footer = self._footer except AttributeError: pass else: total += len(footer['text']) try: author = self._author except AttributeError: pass else: total += len(author['name']) return total @property def colour(self): return getattr(self, '_colour', EmptyEmbed) @colour.setter def colour(self, value): if isinstance(value, (Colour, _EmptyEmbed)): self._colour = value elif isinstance(value, int): self._colour = Colour(value=value) else: raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__) color = colour @property def timestamp(self): return getattr(self, '_timestamp', EmptyEmbed) @timestamp.setter def timestamp(self, value): if isinstance(value, (datetime.datetime, _EmptyEmbed)): self._timestamp = value else: raise TypeError("Expected datetime.datetime or Embed.Empty received %s instead" % value.__class__.__name__) @property def footer(self): """Union[:class:`EmbedProxy`, :attr:`Empty`]: Returns an ``EmbedProxy`` denoting the footer contents. See :meth:`set_footer` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_footer', {})) def set_footer(self, *, text=EmptyEmbed, icon_url=EmptyEmbed): """Sets the footer for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- text: :class:`str` The footer text. icon_url: :class:`str` The URL of the footer icon. Only HTTP(S) is supported. """ self._footer = {} if text is not EmptyEmbed: self._footer['text'] = str(text) if icon_url is not EmptyEmbed: self._footer['icon_url'] = str(icon_url) return self @property def image(self): """Union[:class:`EmbedProxy`, :attr:`Empty`]: Returns an ``EmbedProxy`` denoting the image contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_image', {})) def set_image(self, *, url): """Sets the image for the embed content. This function returns the class instance to allow for fluent-style chaining. .. versionchanged:: 1.4 Passing :attr:`Empty` removes the image. Parameters ----------- url: :class:`str` The source URL for the image. Only HTTP(S) is supported. """ if url is EmptyEmbed: try: del self._image except AttributeError: pass else: self._image = { 'url': str(url) } return self @property def thumbnail(self): """Union[:class:`EmbedProxy`, :attr:`Empty`]: Returns an ``EmbedProxy`` denoting the thumbnail contents. Possible attributes you can access are: - ``url`` - ``proxy_url`` - ``width`` - ``height`` If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_thumbnail', {})) def set_thumbnail(self, *, url): """Sets the thumbnail for the embed content. This function returns the class instance to allow for fluent-style chaining. .. versionchanged:: 1.4 Passing :attr:`Empty` removes the thumbnail. Parameters ----------- url: :class:`str` The source URL for the thumbnail. Only HTTP(S) is supported. """ if url is EmptyEmbed: try: del self._thumbnail except AttributeError: pass else: self._thumbnail = { 'url': str(url) } return self @property def video(self): """Union[:class:`EmbedProxy`, :attr:`Empty`]: Returns an ``EmbedProxy`` denoting the video contents. Possible attributes include: - ``url`` for the video URL. - ``height`` for the video height. - ``width`` for the video width. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_video', {})) @property def provider(self): """Union[:class:`EmbedProxy`, :attr:`Empty`]: Returns an ``EmbedProxy`` denoting the provider contents. The only attributes that might be accessed are ``name`` and ``url``. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_provider', {})) @property def author(self): """Union[:class:`EmbedProxy`, :attr:`Empty`]: Returns an ``EmbedProxy`` denoting the author contents. See :meth:`set_author` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return EmbedProxy(getattr(self, '_author', {})) def set_author(self, *, name, url=EmptyEmbed, icon_url=EmptyEmbed): """Sets the author for the embed content. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the author. url: :class:`str` The URL for the author. icon_url: :class:`str` The URL of the author icon. Only HTTP(S) is supported. """ self._author = { 'name': str(name) } if url is not EmptyEmbed: self._author['url'] = str(url) if icon_url is not EmptyEmbed: self._author['icon_url'] = str(icon_url) return self def remove_author(self): """Clears embed's author information. This function returns the class instance to allow for fluent-style chaining. .. versionadded:: 1.4 """ try: del self._author except AttributeError: pass return self @property def fields(self): """List[Union[``EmbedProxy``, :attr:`Empty`]]: Returns a :class:`list` of ``EmbedProxy`` denoting the field contents. See :meth:`add_field` for possible values you can access. If the attribute has no value then :attr:`Empty` is returned. """ return [EmbedProxy(d) for d in getattr(self, '_fields', [])] def add_field(self, *, name, value, inline=True): """Adds a field to the embed object. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value) } try: self._fields.append(field) except AttributeError: self._fields = [field] return self def insert_field_at(self, index, *, name, value, inline=True): """Inserts a field before a specified index to the embed. This function returns the class instance to allow for fluent-style chaining. .. versionadded:: 1.2 Parameters ----------- index: :class:`int` The index of where to insert the field. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. """ field = { 'inline': inline, 'name': str(name), 'value': str(value) } try: self._fields.insert(index, field) except AttributeError: self._fields = [field] return self def clear_fields(self): """Removes all fields from this embed.""" try: self._fields.clear() except AttributeError: self._fields = [] def remove_field(self, index): """Removes a field at a specified index. If the index is invalid or out of bounds then the error is silently swallowed. .. note:: When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list. Parameters ----------- index: :class:`int` The index of the field to remove. """ try: del self._fields[index] except (AttributeError, IndexError): pass def set_field_at(self, index, *, name, value, inline=True): """Modifies a field to the embed object. The index must point to a valid pre-existing field. This function returns the class instance to allow for fluent-style chaining. Parameters ----------- index: :class:`int` The index of the field to modify. name: :class:`str` The name of the field. value: :class:`str` The value of the field. inline: :class:`bool` Whether the field should be displayed inline. Raises ------- IndexError An invalid index was provided. """ try: field = self._fields[index] except (TypeError, IndexError, AttributeError): raise IndexError('field index out of range') field['name'] = str(name) field['value'] = str(value) field['inline'] = inline return self def to_dict(self): """Converts this embed object into a dict.""" # add in the raw data into the dict result = { key[1:]: getattr(self, key) for key in self.__slots__ if key[0] == '_' and hasattr(self, key) } # deal with basic convenience wrappers try: colour = result.pop('colour') except KeyError: pass else: if colour: result['color'] = colour.value try: timestamp = result.pop('timestamp') except KeyError: pass else: if timestamp: if timestamp.tzinfo: result['timestamp'] = timestamp.astimezone(tz=datetime.timezone.utc).isoformat() else: result['timestamp'] = timestamp.replace(tzinfo=datetime.timezone.utc).isoformat() # add in the non raw attribute ones if self.type: result['type'] = self.type if self.description: result['description'] = self.description if self.url: result['url'] = self.url if self.title: result['title'] = self.title return result
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/embeds.py
embeds.py
from . import utils, enums from .object import Object from .permissions import PermissionOverwrite, Permissions from .colour import Colour from .invite import Invite from .mixins import Hashable def _transform_verification_level(entry, data): return enums.try_enum(enums.VerificationLevel, data) def _transform_default_notifications(entry, data): return enums.try_enum(enums.NotificationLevel, data) def _transform_explicit_content_filter(entry, data): return enums.try_enum(enums.ContentFilter, data) def _transform_permissions(entry, data): return Permissions(data) def _transform_color(entry, data): return Colour(data) def _transform_snowflake(entry, data): return int(data) def _transform_channel(entry, data): if data is None: return None return entry.guild.get_channel(int(data)) or Object(id=data) def _transform_owner_id(entry, data): if data is None: return None return entry._get_member(int(data)) def _transform_inviter_id(entry, data): if data is None: return None return entry._get_member(int(data)) def _transform_overwrites(entry, data): overwrites = [] for elem in data: allow = Permissions(elem['allow']) deny = Permissions(elem['deny']) ow = PermissionOverwrite.from_pair(allow, deny) ow_type = elem['type'] ow_id = int(elem['id']) if ow_type == 'role': target = entry.guild.get_role(ow_id) else: target = entry._get_member(ow_id) if target is None: target = Object(id=ow_id) overwrites.append((target, ow)) return overwrites class AuditLogDiff: def __len__(self): return len(self.__dict__) def __iter__(self): return iter(self.__dict__.items()) def __repr__(self): values = ' '.join('%s=%r' % item for item in self.__dict__.items()) return '<AuditLogDiff %s>' % values class AuditLogChanges: TRANSFORMERS = { 'verification_level': (None, _transform_verification_level), 'explicit_content_filter': (None, _transform_explicit_content_filter), 'allow': (None, _transform_permissions), 'deny': (None, _transform_permissions), 'permissions': (None, _transform_permissions), 'id': (None, _transform_snowflake), 'color': ('colour', _transform_color), 'owner_id': ('owner', _transform_owner_id), 'inviter_id': ('inviter', _transform_inviter_id), 'channel_id': ('channel', _transform_channel), 'afk_channel_id': ('afk_channel', _transform_channel), 'system_channel_id': ('system_channel', _transform_channel), 'widget_channel_id': ('widget_channel', _transform_channel), 'permission_overwrites': ('overwrites', _transform_overwrites), 'splash_hash': ('splash', None), 'icon_hash': ('icon', None), 'avatar_hash': ('avatar', None), 'rate_limit_per_user': ('slowmode_delay', None), 'default_message_notifications': ('default_notifications', _transform_default_notifications), } def __init__(self, entry, data): self.before = AuditLogDiff() self.after = AuditLogDiff() for elem in data: attr = elem['key'] # special cases for role add/remove if attr == '$add': self._handle_role(self.before, self.after, entry, elem['new_value']) continue elif attr == '$remove': self._handle_role(self.after, self.before, entry, elem['new_value']) continue transformer = self.TRANSFORMERS.get(attr) if transformer: key, transformer = transformer if key: attr = key try: before = elem['old_value'] except KeyError: before = None else: if transformer: before = transformer(entry, before) setattr(self.before, attr, before) try: after = elem['new_value'] except KeyError: after = None else: if transformer: after = transformer(entry, after) setattr(self.after, attr, after) # add an alias if hasattr(self.after, 'colour'): self.after.color = self.after.colour self.before.color = self.before.colour def __repr__(self): return '<AuditLogChanges before=%r after=%r>' % (self.before, self.after) def _handle_role(self, first, second, entry, elem): if not hasattr(first, 'roles'): setattr(first, 'roles', []) data = [] g = entry.guild for e in elem: role_id = int(e['id']) role = g.get_role(role_id) if role is None: role = Object(id=role_id) role.name = e['name'] data.append(role) setattr(second, 'roles', data) class AuditLogEntry(Hashable): r"""Represents an Audit Log entry. You retrieve these via :meth:`Guild.audit_logs`. .. container:: operations .. describe:: x == y Checks if two entries are equal. .. describe:: x != y Checks if two entries are not equal. .. describe:: hash(x) Returns the entry's hash. .. versionchanged:: 1.7 Audit log entries are now comparable and hashable. Attributes ----------- action: :class:`AuditLogAction` The action that was done. user: :class:`abc.User` The user who initiated this action. Usually a :class:`Member`\, unless gone then it's a :class:`User`. id: :class:`int` The entry ID. target: Any The target that got changed. The exact type of this depends on the action being done. reason: Optional[:class:`str`] The reason this action was done. extra: Any Extra information that this entry has that might be useful. For most actions, this is ``None``. However in some cases it contains extra information. See :class:`AuditLogAction` for which actions have this field filled out. """ def __init__(self, *, users, data, guild): self._state = guild._state self.guild = guild self._users = users self._from_data(data) def _from_data(self, data): self.action = enums.try_enum(enums.AuditLogAction, data['action_type']) self.id = int(data['id']) # this key is technically not usually present self.reason = data.get('reason') self.extra = data.get('options') if isinstance(self.action, enums.AuditLogAction) and self.extra: if self.action is enums.AuditLogAction.member_prune: # member prune has two keys with useful information self.extra = type('_AuditLogProxy', (), {k: int(v) for k, v in self.extra.items()})() elif self.action is enums.AuditLogAction.member_move or self.action is enums.AuditLogAction.message_delete: channel_id = int(self.extra['channel_id']) elems = { 'count': int(self.extra['count']), 'channel': self.guild.get_channel(channel_id) or Object(id=channel_id) } self.extra = type('_AuditLogProxy', (), elems)() elif self.action is enums.AuditLogAction.member_disconnect: # The member disconnect action has a dict with some information elems = { 'count': int(self.extra['count']), } self.extra = type('_AuditLogProxy', (), elems)() elif self.action.name.endswith('pin'): # the pin actions have a dict with some information channel_id = int(self.extra['channel_id']) message_id = int(self.extra['message_id']) elems = { 'channel': self.guild.get_channel(channel_id) or Object(id=channel_id), 'message_id': message_id } self.extra = type('_AuditLogProxy', (), elems)() elif self.action.name.startswith('overwrite_'): # the overwrite_ actions have a dict with some information instance_id = int(self.extra['id']) the_type = self.extra.get('type') if the_type == 'member': self.extra = self._get_member(instance_id) else: role = self.guild.get_role(instance_id) if role is None: role = Object(id=instance_id) role.name = self.extra.get('role_name') self.extra = role # this key is not present when the above is present, typically. # It's a list of { new_value: a, old_value: b, key: c } # where new_value and old_value are not guaranteed to be there depending # on the action type, so let's just fetch it for now and only turn it # into meaningful data when requested self._changes = data.get('changes', []) self.user = self._get_member(utils._get_as_snowflake(data, 'user_id')) self._target_id = utils._get_as_snowflake(data, 'target_id') def _get_member(self, user_id): return self.guild.get_member(user_id) or self._users.get(user_id) def __repr__(self): return '<AuditLogEntry id={0.id} action={0.action} user={0.user!r}>'.format(self) @utils.cached_property def created_at(self): """:class:`datetime.datetime`: Returns the entry's creation time in UTC.""" return utils.snowflake_time(self.id) @utils.cached_property def target(self): try: converter = getattr(self, '_convert_target_' + self.action.target_type) except AttributeError: return Object(id=self._target_id) else: return converter(self._target_id) @utils.cached_property def category(self): """Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable.""" return self.action.category @utils.cached_property def changes(self): """:class:`AuditLogChanges`: The list of changes this entry has.""" obj = AuditLogChanges(self, self._changes) del self._changes return obj @utils.cached_property def before(self): """:class:`AuditLogDiff`: The target's prior state.""" return self.changes.before @utils.cached_property def after(self): """:class:`AuditLogDiff`: The target's subsequent state.""" return self.changes.after def _convert_target_guild(self, target_id): return self.guild def _convert_target_channel(self, target_id): ch = self.guild.get_channel(target_id) if ch is None: return Object(id=target_id) return ch def _convert_target_user(self, target_id): return self._get_member(target_id) def _convert_target_role(self, target_id): role = self.guild.get_role(target_id) if role is None: return Object(id=target_id) return role def _convert_target_invite(self, target_id): # invites have target_id set to null # so figure out which change has the full invite data changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after fake_payload = { 'max_age': changeset.max_age, 'max_uses': changeset.max_uses, 'code': changeset.code, 'temporary': changeset.temporary, 'channel': changeset.channel, 'uses': changeset.uses, 'guild': self.guild, } obj = Invite(state=self._state, data=fake_payload) try: obj.inviter = changeset.inviter except AttributeError: pass return obj def _convert_target_emoji(self, target_id): return self._state.get_emoji(target_id) or Object(id=target_id) def _convert_target_message(self, target_id): return self._get_member(target_id)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/audit_logs.py
audit_logs.py
import os.path import io class File: r"""A parameter object used for :meth:`abc.Messageable.send` for sending file objects. .. note:: File objects are single use and are not meant to be reused in multiple :meth:`abc.Messageable.send`\s. Attributes ----------- fp: Union[:class:`str`, :class:`io.BufferedIOBase`] A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open. .. note:: If the file-like object passed is opened via ``open`` then the modes 'rb' should be used. To pass binary data, consider usage of ``io.BytesIO``. filename: Optional[:class:`str`] The filename to display when uploading to Discord. If this is not given then it defaults to ``fp.name`` or if ``fp`` is a string then the ``filename`` will default to the string given. spoiler: :class:`bool` Whether the attachment is a spoiler. """ __slots__ = ('fp', 'filename', 'spoiler', '_original_pos', '_owner', '_closer') def __init__(self, fp, filename=None, *, spoiler=False): self.fp = fp if isinstance(fp, io.IOBase): if not (fp.seekable() and fp.readable()): raise ValueError('File buffer {!r} must be seekable and readable'.format(fp)) self.fp = fp self._original_pos = fp.tell() self._owner = False else: self.fp = open(fp, 'rb') self._original_pos = 0 self._owner = True # aiohttp only uses two methods from IOBase # read and close, since I want to control when the files # close, I need to stub it so it doesn't close unless # I tell it to self._closer = self.fp.close self.fp.close = lambda: None if filename is None: if isinstance(fp, str): _, self.filename = os.path.split(fp) else: self.filename = getattr(fp, 'name', None) else: self.filename = filename if spoiler and self.filename is not None and not self.filename.startswith('SPOILER_'): self.filename = 'SPOILER_' + self.filename self.spoiler = spoiler or (self.filename is not None and self.filename.startswith('SPOILER_')) def reset(self, *, seek=True): # The `seek` parameter is needed because # the retry-loop is iterated over multiple times # starting from 0, as an implementation quirk # the resetting must be done at the beginning # before a request is done, since the first index # is 0, and thus false, then this prevents an # unnecessary seek since it's the first request # done. if seek: self.fp.seek(self._original_pos) def close(self): self.fp.close = self._closer if self._owner: self._closer()
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/file.py
file.py
from .asset import Asset from .utils import parse_time, snowflake_time, _get_as_snowflake from .object import Object from .mixins import Hashable from .enums import ChannelType, VerificationLevel, try_enum class PartialInviteChannel: """Represents a "partial" invite channel. This model will be given when the user is not part of the guild the :class:`Invite` resolves to. .. container:: operations .. describe:: x == y Checks if two partial channels are the same. .. describe:: x != y Checks if two partial channels are not the same. .. describe:: hash(x) Return the partial channel's hash. .. describe:: str(x) Returns the partial channel's name. Attributes ----------- name: :class:`str` The partial channel's name. id: :class:`int` The partial channel's ID. type: :class:`ChannelType` The partial channel's type. """ __slots__ = ('id', 'name', 'type') def __init__(self, **kwargs): self.id = kwargs.pop('id') self.name = kwargs.pop('name') self.type = kwargs.pop('type') def __str__(self): return self.name def __repr__(self): return '<PartialInviteChannel id={0.id} name={0.name} type={0.type!r}>'.format(self) @property def mention(self): """:class:`str`: The string that allows you to mention the channel.""" return '<#%s>' % self.id @property def created_at(self): """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return snowflake_time(self.id) class PartialInviteGuild: """Represents a "partial" invite guild. This model will be given when the user is not part of the guild the :class:`Invite` resolves to. .. container:: operations .. describe:: x == y Checks if two partial guilds are the same. .. describe:: x != y Checks if two partial guilds are not the same. .. describe:: hash(x) Return the partial guild's hash. .. describe:: str(x) Returns the partial guild's name. Attributes ----------- name: :class:`str` The partial guild's name. id: :class:`int` The partial guild's ID. verification_level: :class:`VerificationLevel` The partial guild's verification level. features: List[:class:`str`] A list of features the guild has. See :attr:`Guild.features` for more information. icon: Optional[:class:`str`] The partial guild's icon. banner: Optional[:class:`str`] The partial guild's banner. splash: Optional[:class:`str`] The partial guild's invite splash. description: Optional[:class:`str`] The partial guild's description. """ __slots__ = ('_state', 'features', 'icon', 'banner', 'id', 'name', 'splash', 'verification_level', 'description') def __init__(self, state, data, id): self._state = state self.id = id self.name = data['name'] self.features = data.get('features', []) self.icon = data.get('icon') self.banner = data.get('banner') self.splash = data.get('splash') self.verification_level = try_enum(VerificationLevel, data.get('verification_level')) self.description = data.get('description') def __str__(self): return self.name def __repr__(self): return '<{0.__class__.__name__} id={0.id} name={0.name!r} features={0.features} ' \ 'description={0.description!r}>'.format(self) @property def created_at(self): """:class:`datetime.datetime`: Returns the guild's creation time in UTC.""" return snowflake_time(self.id) @property def icon_url(self): """:class:`Asset`: Returns the guild's icon asset.""" return self.icon_url_as() def is_icon_animated(self): """:class:`bool`: Returns ``True`` if the guild has an animated icon. .. versionadded:: 1.4 """ return bool(self.icon and self.icon.startswith('a_')) def icon_url_as(self, *, format=None, static_format='webp', size=1024): """The same operation as :meth:`Guild.icon_url_as`. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_icon(self._state, self, format=format, static_format=static_format, size=size) @property def banner_url(self): """:class:`Asset`: Returns the guild's banner asset.""" return self.banner_url_as() def banner_url_as(self, *, format='webp', size=2048): """The same operation as :meth:`Guild.banner_url_as`. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size) @property def splash_url(self): """:class:`Asset`: Returns the guild's invite splash asset.""" return self.splash_url_as() def splash_url_as(self, *, format='webp', size=2048): """The same operation as :meth:`Guild.splash_url_as`. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size) class Invite(Hashable): r"""Represents a Discord :class:`Guild` or :class:`abc.GuildChannel` invite. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two invites are equal. .. describe:: x != y Checks if two invites are not equal. .. describe:: hash(x) Returns the invite hash. .. describe:: str(x) Returns the invite URL. The following table illustrates what methods will obtain the attributes: +------------------------------------+----------------------------------------------------------+ | Attribute | Method | +====================================+==========================================================+ | :attr:`max_age` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+----------------------------------------------------------+ | :attr:`max_uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+----------------------------------------------------------+ | :attr:`created_at` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+----------------------------------------------------------+ | :attr:`temporary` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+----------------------------------------------------------+ | :attr:`uses` | :meth:`abc.GuildChannel.invites`\, :meth:`Guild.invites` | +------------------------------------+----------------------------------------------------------+ | :attr:`approximate_member_count` | :meth:`Client.fetch_invite` | +------------------------------------+----------------------------------------------------------+ | :attr:`approximate_presence_count` | :meth:`Client.fetch_invite` | +------------------------------------+----------------------------------------------------------+ If it's not in the table above then it is available by all methods. Attributes ----------- max_age: :class:`int` How long the before the invite expires in seconds. A value of ``0`` indicates that it doesn't expire. code: :class:`str` The URL fragment used for the invite. guild: Optional[Union[:class:`Guild`, :class:`Object`, :class:`PartialInviteGuild`]] The guild the invite is for. Can be ``None`` if it's from a group direct message. revoked: :class:`bool` Indicates if the invite has been revoked. created_at: :class:`datetime.datetime` A datetime object denoting the time the invite was created. temporary: :class:`bool` Indicates that the invite grants temporary membership. If ``True``, members who joined via this invite will be kicked upon disconnect. uses: :class:`int` How many times the invite has been used. max_uses: :class:`int` How many times the invite can be used. A value of ``0`` indicates that it has unlimited uses. inviter: :class:`User` The user who created the invite. approximate_member_count: Optional[:class:`int`] The approximate number of members in the guild. approximate_presence_count: Optional[:class:`int`] The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded. channel: Union[:class:`abc.GuildChannel`, :class:`Object`, :class:`PartialInviteChannel`] The channel the invite is for. """ __slots__ = ('max_age', 'code', 'guild', 'revoked', 'created_at', 'uses', 'temporary', 'max_uses', 'inviter', 'channel', '_state', 'approximate_member_count', 'approximate_presence_count' ) BASE = 'https://discord.gg' def __init__(self, *, state, data): self._state = state self.max_age = data.get('max_age') self.code = data.get('code') self.guild = data.get('guild') self.revoked = data.get('revoked') self.created_at = parse_time(data.get('created_at')) self.temporary = data.get('temporary') self.uses = data.get('uses') self.max_uses = data.get('max_uses') self.approximate_presence_count = data.get('approximate_presence_count') self.approximate_member_count = data.get('approximate_member_count') inviter_data = data.get('inviter') self.inviter = None if inviter_data is None else self._state.store_user(inviter_data) self.channel = data.get('channel') @classmethod def from_incomplete(cls, *, state, data): try: guild_id = int(data['guild']['id']) except KeyError: # If we're here, then this is a group DM guild = None else: guild = state._get_guild(guild_id) if guild is None: # If it's not cached, then it has to be a partial guild guild_data = data['guild'] guild = PartialInviteGuild(state, guild_data, guild_id) # As far as I know, invites always need a channel # So this should never raise. channel_data = data['channel'] channel_id = int(channel_data['id']) channel_type = try_enum(ChannelType, channel_data['type']) channel = PartialInviteChannel(id=channel_id, name=channel_data['name'], type=channel_type) if guild is not None and not isinstance(guild, PartialInviteGuild): # Upgrade the partial data if applicable channel = guild.get_channel(channel_id) or channel data['guild'] = guild data['channel'] = channel return cls(state=state, data=data) @classmethod def from_gateway(cls, *, state, data): guild_id = _get_as_snowflake(data, 'guild_id') guild = state._get_guild(guild_id) channel_id = _get_as_snowflake(data, 'channel_id') if guild is not None: channel = guild.get_channel(channel_id) or Object(id=channel_id) else: guild = Object(id=guild_id) channel = Object(id=channel_id) data['guild'] = guild data['channel'] = channel return cls(state=state, data=data) def __str__(self): return self.url def __repr__(self): return '<Invite code={0.code!r} guild={0.guild!r} ' \ 'online={0.approximate_presence_count} ' \ 'members={0.approximate_member_count}>'.format(self) def __hash__(self): return hash(self.code) @property def id(self): """:class:`str`: Returns the proper code portion of the invite.""" return self.code @property def url(self): """:class:`str`: A property that retrieves the invite URL.""" return self.BASE + '/' + self.code async def delete(self, *, reason=None): """|coro| Revokes the instant invite. You must have the :attr:`~Permissions.manage_channels` permission to do this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this invite. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to revoke invites. NotFound The invite is invalid or expired. HTTPException Revoking the invite failed. """ await self._state.http.delete_invite(self.code, reason=reason)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/invite.py
invite.py
import time import asyncio import discord.abc from .permissions import Permissions from .enums import ChannelType, try_enum, VoiceRegion from .mixins import Hashable from . import utils from .asset import Asset from .errors import ClientException, NoMoreItems, InvalidArgument __all__ = ( 'TextChannel', 'VoiceChannel', 'StageChannel', 'DMChannel', 'CategoryChannel', 'StoreChannel', 'GroupChannel', '_channel_factory', ) async def _single_delete_strategy(messages): for m in messages: await m.delete() class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable): """Represents a Discord guild text channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. topic: Optional[:class:`str`] The channel's topic. ``None`` if it doesn't exist. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. last_message_id: Optional[:class:`int`] The last message ID of the message sent to this channel. It may *not* point to an existing or valid message. slowmode_delay: :class:`int` The number of seconds a member must wait between sending messages in this channel. A value of `0` denotes that it is disabled. Bots and users with :attr:`~Permissions.manage_channels` or :attr:`~Permissions.manage_messages` bypass slowmode. """ __slots__ = ('name', 'id', 'guild', 'topic', '_state', 'nsfw', 'category_id', 'position', 'slowmode_delay', '_overwrites', '_type', 'last_message_id') def __init__(self, *, state, guild, data): self._state = state self.id = int(data['id']) self._type = data['type'] self._update(guild, data) def __repr__(self): attrs = [ ('id', self.id), ('name', self.name), ('position', self.position), ('nsfw', self.nsfw), ('news', self.is_news()), ('category_id', self.category_id) ] return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs)) def _update(self, guild, data): self.guild = guild self.name = data['name'] self.category_id = utils._get_as_snowflake(data, 'parent_id') self.topic = data.get('topic') self.position = data['position'] self.nsfw = data.get('nsfw', False) # Does this need coercion into `int`? No idea yet. self.slowmode_delay = data.get('rate_limit_per_user', 0) self._type = data.get('type', self._type) self.last_message_id = utils._get_as_snowflake(data, 'last_message_id') self._fill_overwrites(data) async def _get_channel(self): return self @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return try_enum(ChannelType, self._type) @property def _sorting_bucket(self): return ChannelType.text.value @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, member): base = super().permissions_for(member) # text channels do not have voice related permissions denied = Permissions.voice() base.value &= ~denied.value return base @property def members(self): """List[:class:`Member`]: Returns all members that can see this channel.""" return [m for m in self.guild.members if self.permissions_for(m).read_messages] def is_nsfw(self): """:class:`bool`: Checks if the channel is NSFW.""" return self.nsfw def is_news(self): """:class:`bool`: Checks if the channel is a news channel.""" return self._type == ChannelType.news.value @property def last_message(self): """Fetches the last message from this channel in cache. The message might not be valid or point to an existing message. .. admonition:: Reliable Fetching :class: helpful For a slightly more reliable method of fetching the last message, consider using either :meth:`history` or :meth:`fetch_message` with the :attr:`last_message_id` attribute. Returns --------- Optional[:class:`Message`] The last message in this channel or ``None`` if not found. """ return self._state._get_message(self.last_message_id) if self.last_message_id else None async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. .. versionchanged:: 1.4 The ``type`` keyword-only parameter was added. Parameters ---------- name: :class:`str` The new channel name. topic: :class:`str` The new channel's topic. position: :class:`int` The new channel's position. nsfw: :class:`bool` To mark the channel as NSFW or not. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel, in seconds. A value of `0` disables slowmode. The maximum value possible is `21600`. type: :class:`ChannelType` Change the type of this text channel. Currently, only conversion between :attr:`ChannelType.text` and :attr:`ChannelType.news` is supported. This is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`dict` A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. Raises ------ InvalidArgument If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. """ await self._edit(options, reason=reason) @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name=None, reason=None): return await self._clone_impl({ 'topic': self.topic, 'nsfw': self.nsfw, 'rate_limit_per_user': self.slowmode_delay }, name=name, reason=reason) async def delete_messages(self, messages): """|coro| Deletes a list of messages. This is similar to :meth:`Message.delete` except it bulk deletes multiple messages. As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it's more than two, then bulk delete is used. You cannot bulk delete more than 100 messages or messages that are older than 14 days old. You must have the :attr:`~Permissions.manage_messages` permission to use this. Usable only by bot accounts. Parameters ----------- messages: Iterable[:class:`abc.Snowflake`] An iterable of messages denoting which ones to bulk delete. Raises ------ ClientException The number of messages to delete was more than 100. Forbidden You do not have proper permissions to delete the messages or you're not using a bot account. NotFound If single delete, then the message was already deleted. HTTPException Deleting the messages failed. """ if not isinstance(messages, (list, tuple)): messages = list(messages) if len(messages) == 0: return # do nothing if len(messages) == 1: message_id = messages[0].id await self._state.http.delete_message(self.id, message_id) return if len(messages) > 100: raise ClientException('Can only bulk delete messages up to 100 messages') message_ids = [m.id for m in messages] await self._state.http.delete_messages(self.id, message_ids) async def purge(self, *, limit=100, check=None, before=None, after=None, around=None, oldest_first=False, bulk=True): """|coro| Purges a list of messages that meet the criteria given by the predicate ``check``. If a ``check`` is not provided then all messages are deleted without discrimination. You must have the :attr:`~Permissions.manage_messages` permission to delete messages even if they are your own (unless you are a user account). The :attr:`~Permissions.read_message_history` permission is also needed to retrieve message history. Internally, this employs a different number of strategies depending on the conditions met such as if a bulk delete is possible or if the account is a user bot or not. Examples --------- Deleting bot's messages :: def is_me(m): return m.author == client.user deleted = await channel.purge(limit=100, check=is_me) await channel.send('Deleted {} message(s)'.format(len(deleted))) Parameters ----------- limit: Optional[:class:`int`] The number of messages to search through. This is not the number of messages that will be deleted, though it can be. check: Callable[[:class:`Message`], :class:`bool`] The function used to check if a message should be deleted. It must take a :class:`Message` as its sole parameter. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Same as ``before`` in :meth:`history`. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Same as ``after`` in :meth:`history`. around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Same as ``around`` in :meth:`history`. oldest_first: Optional[:class:`bool`] Same as ``oldest_first`` in :meth:`history`. bulk: :class:`bool` If ``True``, use bulk delete. Setting this to ``False`` is useful for mass-deleting a bot's own messages without :attr:`Permissions.manage_messages`. When ``True``, will fall back to single delete if current account is a user bot (now deprecated), or if messages are older than two weeks. Raises ------- Forbidden You do not have proper permissions to do the actions required. HTTPException Purging the messages failed. Returns -------- List[:class:`.Message`] The list of messages that were deleted. """ if check is None: check = lambda m: True iterator = self.history(limit=limit, before=before, after=after, oldest_first=oldest_first, around=around) ret = [] count = 0 minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22 strategy = self.delete_messages if self._state.is_bot and bulk else _single_delete_strategy while True: try: msg = await iterator.next() except NoMoreItems: # no more messages to poll if count >= 2: # more than 2 messages -> bulk delete to_delete = ret[-count:] await strategy(to_delete) elif count == 1: # delete a single message await ret[-1].delete() return ret else: if count == 100: # we've reached a full 'queue' to_delete = ret[-100:] await strategy(to_delete) count = 0 await asyncio.sleep(1) if check(msg): if msg.id < minimum_time: # older than 14 days old if count == 1: await ret[-1].delete() elif count >= 2: to_delete = ret[-count:] await strategy(to_delete) count = 0 strategy = _single_delete_strategy count += 1 ret.append(msg) async def webhooks(self): """|coro| Gets the list of webhooks from this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. Raises ------- Forbidden You don't have permissions to get the webhooks. Returns -------- List[:class:`Webhook`] The webhooks for this channel. """ from .webhook import Webhook data = await self._state.http.channel_webhooks(self.id) return [Webhook.from_state(d, state=self._state) for d in data] async def create_webhook(self, *, name, avatar=None, reason=None): """|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1 Added the ``reason`` keyword-only parameter. Parameters ------------- name: :class:`str` The webhook's name. avatar: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the webhook's default avatar. This operates similarly to :meth:`~ClientUser.edit`. reason: Optional[:class:`str`] The reason for creating this webhook. Shows up in the audit logs. Raises ------- HTTPException Creating the webhook failed. Forbidden You do not have permissions to create a webhook. Returns -------- :class:`Webhook` The created webhook. """ from .webhook import Webhook if avatar is not None: avatar = utils._bytes_to_base64_data(avatar) data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) return Webhook.from_state(data, state=self._state) async def follow(self, *, destination, reason=None): """ Follows a channel using a webhook. Only news channels can be followed. .. note:: The webhook returned will not provide a token to do webhook actions, as Discord does not provide it. .. versionadded:: 1.3 Parameters ----------- destination: :class:`TextChannel` The channel you would like to follow from. reason: Optional[:class:`str`] The reason for following the channel. Shows up on the destination guild's audit log. .. versionadded:: 1.4 Raises ------- HTTPException Following the channel failed. Forbidden You do not have the permissions to create a webhook. Returns -------- :class:`Webhook` The created webhook. """ if not self.is_news(): raise ClientException('The channel must be a news channel.') if not isinstance(destination, TextChannel): raise InvalidArgument('Expected TextChannel received {0.__name__}'.format(type(destination))) from .webhook import Webhook data = await self._state.http.follow_webhook(self.id, webhook_channel_id=destination.id, reason=reason) return Webhook._as_follower(data, channel=destination, user=self._state.user) def get_partial_message(self, message_id): """Creates a :class:`PartialMessage` from the message ID. This is useful if you want to work with a message and only have its ID without doing an unnecessary API call. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to create a partial message for. Returns --------- :class:`PartialMessage` The partial message. """ from .message import PartialMessage return PartialMessage(channel=self, id=message_id) class VocalGuildChannel(discord.abc.Connectable, discord.abc.GuildChannel, Hashable): __slots__ = ('name', 'id', 'guild', 'bitrate', 'user_limit', '_state', 'position', '_overwrites', 'category_id', 'rtc_region') def __init__(self, *, state, guild, data): self._state = state self.id = int(data['id']) self._update(guild, data) def _get_voice_client_key(self): return self.guild.id, 'guild_id' def _get_voice_state_pair(self): return self.guild.id, self.id def _update(self, guild, data): self.guild = guild self.name = data['name'] self.rtc_region = data.get('rtc_region') if self.rtc_region: self.rtc_region = try_enum(VoiceRegion, self.rtc_region) self.category_id = utils._get_as_snowflake(data, 'parent_id') self.position = data['position'] self.bitrate = data.get('bitrate') self.user_limit = data.get('user_limit') self._fill_overwrites(data) @property def _sorting_bucket(self): return ChannelType.voice.value @property def members(self): """List[:class:`Member`]: Returns all members that are currently inside this voice channel.""" ret = [] for user_id, state in self.guild._voice_states.items(): if state.channel and state.channel.id == self.id: member = self.guild.get_member(user_id) if member is not None: ret.append(member) return ret @property def voice_states(self): """Returns a mapping of member IDs who have voice states in this channel. .. versionadded:: 1.3 .. note:: This function is intentionally low level to replace :attr:`members` when the member cache is unavailable. Returns -------- Mapping[:class:`int`, :class:`VoiceState`] The mapping of member ID to a voice state. """ return {key: value for key, value in self.guild._voice_states.items() if value.channel.id == self.id} @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, member): base = super().permissions_for(member) # voice channels cannot be edited by people who can't connect to them # It also implicitly denies all other voice perms if not base.connect: denied = Permissions.voice() denied.update(manage_channels=True, manage_roles=True) base.value &= ~denied.value return base class VoiceChannel(VocalGuildChannel): """Represents a Discord guild voice channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. bitrate: :class:`int` The channel's preferred audio bitrate in bits per second. user_limit: :class:`int` The channel's limit for number of members that can be in a voice channel. rtc_region: Optional[:class:`VoiceRegion`] The region for the voice channel's voice communication. A value of ``None`` indicates automatic voice region detection. .. versionadded:: 1.7 """ __slots__ = () def __repr__(self): attrs = [ ('id', self.id), ('name', self.name), ('rtc_region', self.rtc_region), ('position', self.position), ('bitrate', self.bitrate), ('user_limit', self.user_limit), ('category_id', self.category_id) ] return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs)) @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.voice @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name=None, reason=None): return await self._clone_impl({ 'bitrate': self.bitrate, 'user_limit': self.user_limit }, name=name, reason=reason) async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. Parameters ---------- name: :class:`str` The new channel's name. bitrate: :class:`int` The new channel's bitrate. user_limit: :class:`int` The new channel's user limit. position: :class:`int` The new channel's position. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`dict` A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. rtc_region: Optional[:class:`VoiceRegion`] The new region for the voice channel's voice communication. A value of ``None`` indicates automatic voice region detection. .. versionadded:: 1.7 Raises ------ InvalidArgument If the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. """ await self._edit(options, reason=reason) class StageChannel(VocalGuildChannel): """Represents a Discord guild stage channel. .. versionadded:: 1.7 .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. topic: Optional[:class:`str`] The channel's topic. ``None`` if it isn't set. category_id: Optional[:class:`int`] The category channel ID this channel belongs to, if applicable. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. bitrate: :class:`int` The channel's preferred audio bitrate in bits per second. user_limit: :class:`int` The channel's limit for number of members that can be in a stage channel. rtc_region: Optional[:class:`VoiceRegion`] The region for the stage channel's voice communication. A value of ``None`` indicates automatic voice region detection. """ __slots__ = ('topic',) def __repr__(self): attrs = [ ('id', self.id), ('name', self.name), ('topic', self.topic), ('rtc_region', self.rtc_region), ('position', self.position), ('bitrate', self.bitrate), ('user_limit', self.user_limit), ('category_id', self.category_id) ] return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs)) def _update(self, guild, data): super()._update(guild, data) self.topic = data.get('topic') @property def requesting_to_speak(self): """List[:class:`Member`]: A list of members who are requesting to speak in the stage channel.""" return [member for member in self.members if member.voice.requested_to_speak_at is not None] @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.stage_voice @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name=None, reason=None): return await self._clone_impl({ 'topic': self.topic, }, name=name, reason=reason) async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. Parameters ---------- name: :class:`str` The new channel's name. topic: :class:`str` The new channel's topic. position: :class:`int` The new channel's position. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`dict` A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. rtc_region: Optional[:class:`VoiceRegion`] The new region for the stage channel's voice communication. A value of ``None`` indicates automatic voice region detection. Raises ------ InvalidArgument If the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. """ await self._edit(options, reason=reason) class CategoryChannel(discord.abc.GuildChannel, Hashable): """Represents a Discord channel category. These are useful to group channels to logical compartments. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the category's hash. .. describe:: str(x) Returns the category's name. Attributes ----------- name: :class:`str` The category name. guild: :class:`Guild` The guild the category belongs to. id: :class:`int` The category channel ID. position: :class:`int` The position in the category list. This is a number that starts at 0. e.g. the top category is position 0. """ __slots__ = ('name', 'id', 'guild', 'nsfw', '_state', 'position', '_overwrites', 'category_id') def __init__(self, *, state, guild, data): self._state = state self.id = int(data['id']) self._update(guild, data) def __repr__(self): return '<CategoryChannel id={0.id} name={0.name!r} position={0.position} nsfw={0.nsfw}>'.format(self) def _update(self, guild, data): self.guild = guild self.name = data['name'] self.category_id = utils._get_as_snowflake(data, 'parent_id') self.nsfw = data.get('nsfw', False) self.position = data['position'] self._fill_overwrites(data) @property def _sorting_bucket(self): return ChannelType.category.value @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.category def is_nsfw(self): """:class:`bool`: Checks if the category is NSFW.""" return self.nsfw @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name=None, reason=None): return await self._clone_impl({ 'nsfw': self.nsfw }, name=name, reason=reason) async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. .. versionchanged:: 1.3 The ``overwrites`` keyword-only parameter was added. Parameters ---------- name: :class:`str` The new category's name. position: :class:`int` The new category's position. nsfw: :class:`bool` To mark the category as NSFW or not. reason: Optional[:class:`str`] The reason for editing this category. Shows up on the audit log. overwrites: :class:`dict` A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. Raises ------ InvalidArgument If position is less than 0 or greater than the number of categories. Forbidden You do not have permissions to edit the category. HTTPException Editing the category failed. """ await self._edit(options=options, reason=reason) @utils.copy_doc(discord.abc.GuildChannel.move) async def move(self, **kwargs): kwargs.pop('category', None) await super().move(**kwargs) @property def channels(self): """List[:class:`abc.GuildChannel`]: Returns the channels that are under this category. These are sorted by the official Discord UI, which places voice channels below the text channels. """ def comparator(channel): return (not isinstance(channel, TextChannel), channel.position) ret = [c for c in self.guild.channels if c.category_id == self.id] ret.sort(key=comparator) return ret @property def text_channels(self): """List[:class:`TextChannel`]: Returns the text channels that are under this category.""" ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, TextChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret @property def voice_channels(self): """List[:class:`VoiceChannel`]: Returns the voice channels that are under this category.""" ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, VoiceChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret @property def stage_channels(self): """List[:class:`StageChannel`]: Returns the voice channels that are under this category. .. versionadded:: 1.7 """ ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, StageChannel)] ret.sort(key=lambda c: (c.position, c.id)) return ret async def create_text_channel(self, name, *, overwrites=None, reason=None, **options): """|coro| A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category. Returns ------- :class:`TextChannel` The channel that was just created. """ return await self.guild.create_text_channel(name, overwrites=overwrites, category=self, reason=reason, **options) async def create_voice_channel(self, name, *, overwrites=None, reason=None, **options): """|coro| A shortcut method to :meth:`Guild.create_voice_channel` to create a :class:`VoiceChannel` in the category. Returns ------- :class:`VoiceChannel` The channel that was just created. """ return await self.guild.create_voice_channel(name, overwrites=overwrites, category=self, reason=reason, **options) async def create_stage_channel(self, name, *, overwrites=None, reason=None, **options): """|coro| A shortcut method to :meth:`Guild.create_stage_channel` to create a :class:`StageChannel` in the category. .. versionadded:: 1.7 Returns ------- :class:`StageChannel` The channel that was just created. """ return await self.guild.create_stage_channel(name, overwrites=overwrites, category=self, reason=reason, **options) class StoreChannel(discord.abc.GuildChannel, Hashable): """Represents a Discord guild store channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns the channel's name. Attributes ----------- name: :class:`str` The channel name. guild: :class:`Guild` The guild the channel belongs to. id: :class:`int` The channel ID. category_id: :class:`int` The category channel ID this channel belongs to. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. """ __slots__ = ('name', 'id', 'guild', '_state', 'nsfw', 'category_id', 'position', '_overwrites',) def __init__(self, *, state, guild, data): self._state = state self.id = int(data['id']) self._update(guild, data) def __repr__(self): return '<StoreChannel id={0.id} name={0.name!r} position={0.position} nsfw={0.nsfw}>'.format(self) def _update(self, guild, data): self.guild = guild self.name = data['name'] self.category_id = utils._get_as_snowflake(data, 'parent_id') self.position = data['position'] self.nsfw = data.get('nsfw', False) self._fill_overwrites(data) @property def _sorting_bucket(self): return ChannelType.text.value @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.store @utils.copy_doc(discord.abc.GuildChannel.permissions_for) def permissions_for(self, member): base = super().permissions_for(member) # store channels do not have voice related permissions denied = Permissions.voice() base.value &= ~denied.value return base def is_nsfw(self): """:class:`bool`: Checks if the channel is NSFW.""" return self.nsfw @utils.copy_doc(discord.abc.GuildChannel.clone) async def clone(self, *, name=None, reason=None): return await self._clone_impl({ 'nsfw': self.nsfw }, name=name, reason=reason) async def edit(self, *, reason=None, **options): """|coro| Edits the channel. You must have the :attr:`~Permissions.manage_channels` permission to use this. Parameters ---------- name: :class:`str` The new channel name. position: :class:`int` The new channel's position. nsfw: :class:`bool` To mark the channel as NSFW or not. sync_permissions: :class:`bool` Whether to sync permissions with the channel's new or pre-existing category. Defaults to ``False``. category: Optional[:class:`CategoryChannel`] The new category for this channel. Can be ``None`` to remove the category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. overwrites: :class:`dict` A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply to the channel. .. versionadded:: 1.3 Raises ------ InvalidArgument If position is less than 0 or greater than the number of channels, or if the permission overwrite information is not in proper form. Forbidden You do not have permissions to edit the channel. HTTPException Editing the channel failed. """ await self._edit(options, reason=reason) class DMChannel(discord.abc.Messageable, Hashable): """Represents a Discord direct message channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns a string representation of the channel Attributes ---------- recipient: :class:`User` The user you are participating with in the direct message channel. me: :class:`ClientUser` The user presenting yourself. id: :class:`int` The direct message channel ID. """ __slots__ = ('id', 'recipient', 'me', '_state') def __init__(self, *, me, state, data): self._state = state self.recipient = state.store_user(data['recipients'][0]) self.me = me self.id = int(data['id']) async def _get_channel(self): return self def __str__(self): return 'Direct Message with %s' % self.recipient def __repr__(self): return '<DMChannel id={0.id} recipient={0.recipient!r}>'.format(self) @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.private @property def created_at(self): """:class:`datetime.datetime`: Returns the direct message channel's creation time in UTC.""" return utils.snowflake_time(self.id) def permissions_for(self, user=None): """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to ``True`` except: - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. Parameters ----------- user: :class:`User` The user to check permissions for. This parameter is ignored but kept for compatibility. Returns -------- :class:`Permissions` The resolved permissions. """ base = Permissions.text() base.read_messages = True base.send_tts_messages = False base.manage_messages = False return base def get_partial_message(self, message_id): """Creates a :class:`PartialMessage` from the message ID. This is useful if you want to work with a message and only have its ID without doing an unnecessary API call. .. versionadded:: 1.6 Parameters ------------ message_id: :class:`int` The message ID to create a partial message for. Returns --------- :class:`PartialMessage` The partial message. """ from .message import PartialMessage return PartialMessage(channel=self, id=message_id) class GroupChannel(discord.abc.Messageable, Hashable): """Represents a Discord group channel. .. container:: operations .. describe:: x == y Checks if two channels are equal. .. describe:: x != y Checks if two channels are not equal. .. describe:: hash(x) Returns the channel's hash. .. describe:: str(x) Returns a string representation of the channel Attributes ---------- recipients: List[:class:`User`] The users you are participating with in the group channel. me: :class:`ClientUser` The user presenting yourself. id: :class:`int` The group channel ID. owner: :class:`User` The user that owns the group channel. icon: Optional[:class:`str`] The group channel's icon hash if provided. name: Optional[:class:`str`] The group channel's name if provided. """ __slots__ = ('id', 'recipients', 'owner', 'icon', 'name', 'me', '_state') def __init__(self, *, me, state, data): self._state = state self.id = int(data['id']) self.me = me self._update_group(data) def _update_group(self, data): owner_id = utils._get_as_snowflake(data, 'owner_id') self.icon = data.get('icon') self.name = data.get('name') try: self.recipients = [self._state.store_user(u) for u in data['recipients']] except KeyError: pass if owner_id == self.me.id: self.owner = self.me else: self.owner = utils.find(lambda u: u.id == owner_id, self.recipients) async def _get_channel(self): return self def __str__(self): if self.name: return self.name if len(self.recipients) == 0: return 'Unnamed' return ', '.join(map(lambda x: x.name, self.recipients)) def __repr__(self): return '<GroupChannel id={0.id} name={0.name!r}>'.format(self) @property def type(self): """:class:`ChannelType`: The channel's Discord type.""" return ChannelType.group @property def icon_url(self): """:class:`Asset`: Returns the channel's icon asset if available. This is equivalent to calling :meth:`icon_url_as` with the default parameters ('webp' format and a size of 1024). """ return self.icon_url_as() def icon_url_as(self, *, format='webp', size=1024): """Returns an :class:`Asset` for the icon the channel has. The format must be one of 'webp', 'jpeg', 'jpg' or 'png'. The size must be a power of 2 between 16 and 4096. .. versionadded:: 2.0 Parameters ----------- format: :class:`str` The format to attempt to convert the icon to. Defaults to 'webp'. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_icon(self._state, self, 'channel', format=format, size=size) @property def created_at(self): """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return utils.snowflake_time(self.id) def permissions_for(self, user): """Handles permission resolution for a :class:`User`. This function is there for compatibility with other channel types. Actual direct messages do not really have the concept of permissions. This returns all the Text related permissions set to ``True`` except: - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. This also checks the kick_members permission if the user is the owner. Parameters ----------- user: :class:`User` The user to check permissions for. Returns -------- :class:`Permissions` The resolved permissions for the user. """ base = Permissions.text() base.read_messages = True base.send_tts_messages = False base.manage_messages = False base.mention_everyone = True if user.id == self.owner.id: base.kick_members = True return base @utils.deprecated() async def add_recipients(self, *recipients): r"""|coro| Adds recipients to this group. A group can only have a maximum of 10 members. Attempting to add more ends up in an exception. To add a recipient to the group, you must have a relationship with the user of type :attr:`RelationshipType.friend`. .. deprecated:: 1.7 Parameters ----------- \*recipients: :class:`User` An argument list of users to add to this group. Raises ------- HTTPException Adding a recipient to this group failed. """ # TODO: wait for the corresponding WS event req = self._state.http.add_group_recipient for recipient in recipients: await req(self.id, recipient.id) @utils.deprecated() async def remove_recipients(self, *recipients): r"""|coro| Removes recipients from this group. .. deprecated:: 1.7 Parameters ----------- \*recipients: :class:`User` An argument list of users to remove from this group. Raises ------- HTTPException Removing a recipient from this group failed. """ # TODO: wait for the corresponding WS event req = self._state.http.remove_group_recipient for recipient in recipients: await req(self.id, recipient.id) @utils.deprecated() async def edit(self, **fields): """|coro| Edits the group. .. deprecated:: 1.7 Parameters ----------- name: Optional[:class:`str`] The new name to change the group to. Could be ``None`` to remove the name. icon: Optional[:class:`bytes`] A :term:`py:bytes-like object` representing the new icon. Could be ``None`` to remove the icon. Raises ------- HTTPException Editing the group failed. """ try: icon_bytes = fields['icon'] except KeyError: pass else: if icon_bytes is not None: fields['icon'] = utils._bytes_to_base64_data(icon_bytes) data = await self._state.http.edit_group(self.id, **fields) self._update_group(data) async def leave(self): """|coro| Leave the group. If you are the only one in the group, this deletes it as well. Raises ------- HTTPException Leaving the group failed. """ await self._state.http.leave_group(self.id) def _channel_factory(channel_type): value = try_enum(ChannelType, channel_type) if value is ChannelType.text: return TextChannel, value elif value is ChannelType.voice: return VoiceChannel, value elif value is ChannelType.private: return DMChannel, value elif value is ChannelType.category: return CategoryChannel, value elif value is ChannelType.group: return GroupChannel, value elif value is ChannelType.news: return TextChannel, value elif value is ChannelType.store: return StoreChannel, value elif value is ChannelType.stage_voice: return StageChannel, value else: return None, value
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/channel.py
channel.py
from .utils import snowflake_time, _get_as_snowflake, resolve_invite from .user import BaseUser from .activity import create_activity from .invite import Invite from .enums import Status, try_enum class WidgetChannel: """Represents a "partial" widget channel. .. container:: operations .. describe:: x == y Checks if two partial channels are the same. .. describe:: x != y Checks if two partial channels are not the same. .. describe:: hash(x) Return the partial channel's hash. .. describe:: str(x) Returns the partial channel's name. Attributes ----------- id: :class:`int` The channel's ID. name: :class:`str` The channel's name. position: :class:`int` The channel's position """ __slots__ = ('id', 'name', 'position') def __init__(self, **kwargs): self.id = kwargs.pop('id') self.name = kwargs.pop('name') self.position = kwargs.pop('position') def __str__(self): return self.name def __repr__(self): return '<WidgetChannel id={0.id} name={0.name!r} position={0.position!r}>'.format(self) @property def mention(self): """:class:`str`: The string that allows you to mention the channel.""" return '<#%s>' % self.id @property def created_at(self): """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" return snowflake_time(self.id) class WidgetMember(BaseUser): """Represents a "partial" member of the widget's guild. .. container:: operations .. describe:: x == y Checks if two widget members are the same. .. describe:: x != y Checks if two widget members are not the same. .. describe:: hash(x) Return the widget member's hash. .. describe:: str(x) Returns the widget member's `name#discriminator`. Attributes ----------- id: :class:`int` The member's ID. name: :class:`str` The member's username. discriminator: :class:`str` The member's discriminator. bot: :class:`bool` Whether the member is a bot. status: :class:`Status` The member's status. nick: Optional[:class:`str`] The member's nickname. avatar: Optional[:class:`str`] The member's avatar hash. activity: Optional[Union[:class:`BaseActivity`, :class:`Spotify`]] The member's activity. deafened: Optional[:class:`bool`] Whether the member is currently deafened. muted: Optional[:class:`bool`] Whether the member is currently muted. suppress: Optional[:class:`bool`] Whether the member is currently being suppressed. connected_channel: Optional[:class:`VoiceChannel`] Which channel the member is connected to. """ __slots__ = ('name', 'status', 'nick', 'avatar', 'discriminator', 'id', 'bot', 'activity', 'deafened', 'suppress', 'muted', 'connected_channel') def __init__(self, *, state, data, connected_channel=None): super().__init__(state=state, data=data) self.nick = data.get('nick') self.status = try_enum(Status, data.get('status')) self.deafened = data.get('deaf', False) or data.get('self_deaf', False) self.muted = data.get('mute', False) or data.get('self_mute', False) self.suppress = data.get('suppress', False) try: game = data['game'] except KeyError: self.activity = None else: self.activity = create_activity(game) self.connected_channel = connected_channel @property def display_name(self): """:class:`str`: Returns the member's display name.""" return self.nick or self.name class Widget: """Represents a :class:`Guild` widget. .. container:: operations .. describe:: x == y Checks if two widgets are the same. .. describe:: x != y Checks if two widgets are not the same. .. describe:: str(x) Returns the widget's JSON URL. Attributes ----------- id: :class:`int` The guild's ID. name: :class:`str` The guild's name. channels: Optional[List[:class:`WidgetChannel`]] The accessible voice channels in the guild. members: Optional[List[:class:`Member`]] The online members in the server. Offline members do not appear in the widget. .. note:: Due to a Discord limitation, if this data is available the users will be "anonymized" with linear IDs and discriminator information being incorrect. Likewise, the number of members retrieved is capped. """ __slots__ = ('_state', 'channels', '_invite', 'id', 'members', 'name') def __init__(self, *, state, data): self._state = state self._invite = data['instant_invite'] self.name = data['name'] self.id = int(data['id']) self.channels = [] for channel in data.get('channels', []): _id = int(channel['id']) self.channels.append(WidgetChannel(id=_id, name=channel['name'], position=channel['position'])) self.members = [] channels = {channel.id: channel for channel in self.channels} for member in data.get('members', []): connected_channel = _get_as_snowflake(member, 'channel_id') if connected_channel in channels: connected_channel = channels[connected_channel] elif connected_channel: connected_channel = WidgetChannel(id=connected_channel, name='', position=0) self.members.append(WidgetMember(state=self._state, data=member, connected_channel=connected_channel)) def __str__(self): return self.json_url def __eq__(self, other): return self.id == other.id def __repr__(self): return '<Widget id={0.id} name={0.name!r} invite_url={0.invite_url!r}>'.format(self) @property def created_at(self): """:class:`datetime.datetime`: Returns the member's creation time in UTC.""" return snowflake_time(self.id) @property def json_url(self): """:class:`str`: The JSON URL of the widget.""" return "https://discord.com/api/guilds/{0.id}/widget.json".format(self) @property def invite_url(self): """Optional[:class:`str`]: The invite URL for the guild, if available.""" return self._invite async def fetch_invite(self, *, with_counts=True): """|coro| Retrieves an :class:`Invite` from a invite URL or ID. This is the same as :meth:`Client.fetch_invite`; the invite code is abstracted away. Parameters ----------- with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`Invite.approximate_member_count` and :attr:`Invite.approximate_presence_count` fields. Returns -------- :class:`Invite` The invite from the URL/ID. """ if self._invite: invite_id = resolve_invite(self._invite) data = await self._state.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._state, data=data)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/widget.py
widget.py
import asyncio import logging import signal import sys import traceback import aiohttp from .user import User, Profile from .invite import Invite from .template import Template from .widget import Widget from .guild import Guild from .channel import _channel_factory from .enums import ChannelType from .mentions import AllowedMentions from .errors import * from .enums import Status, VoiceRegion from .gateway import * from .activity import BaseActivity, create_activity from .voice_client import VoiceClient from .http import HTTPClient from .state import ConnectionState from . import utils from .object import Object from .backoff import ExponentialBackoff from .webhook import Webhook from .iterators import GuildIterator from .appinfo import AppInfo log = logging.getLogger(__name__) def _cancel_tasks(loop): try: task_retriever = asyncio.Task.all_tasks except AttributeError: # future proofing for 3.9 I guess task_retriever = asyncio.all_tasks tasks = {t for t in task_retriever(loop=loop) if not t.done()} if not tasks: return log.info('Cleaning up after %d tasks.', len(tasks)) for task in tasks: task.cancel() loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) log.info('All tasks finished cancelling.') for task in tasks: if task.cancelled(): continue if task.exception() is not None: loop.call_exception_handler({ 'message': 'Unhandled exception during Client.run shutdown.', 'exception': task.exception(), 'task': task }) def _cleanup_loop(loop): try: _cancel_tasks(loop) if sys.version_info >= (3, 6): loop.run_until_complete(loop.shutdown_asyncgens()) finally: log.info('Closing the event loop.') loop.close() class _ClientEventTask(asyncio.Task): def __init__(self, original_coro, event_name, coro, *, loop): super().__init__(coro, loop=loop) self.__event_name = event_name self.__original_coro = original_coro def __repr__(self): info = [ ('state', self._state.lower()), ('event', self.__event_name), ('coro', repr(self.__original_coro)), ] if self._exception is not None: info.append(('exception', repr(self._exception))) return '<ClientEventTask {}>'.format(' '.join('%s=%s' % t for t in info)) class Client: r"""Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API. A number of options can be passed to the :class:`Client`. Parameters ----------- max_messages: Optional[:class:`int`] The maximum number of messages to store in the internal message cache. This defaults to ``1000``. Passing in ``None`` disables the message cache. .. versionchanged:: 1.3 Allow disabling the message cache and change the default size to ``1000``. loop: Optional[:class:`asyncio.AbstractEventLoop`] The :class:`asyncio.AbstractEventLoop` to use for asynchronous operations. Defaults to ``None``, in which case the default event loop is used via :func:`asyncio.get_event_loop()`. connector: :class:`aiohttp.BaseConnector` The connector to use for connection pooling. proxy: Optional[:class:`str`] Proxy URL. proxy_auth: Optional[:class:`aiohttp.BasicAuth`] An object that represents proxy HTTP Basic Authorization. shard_id: Optional[:class:`int`] Integer starting at ``0`` and less than :attr:`.shard_count`. shard_count: Optional[:class:`int`] The total number of shards. intents: :class:`Intents` The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent. If not given, defaults to a regularly constructed :class:`Intents` class. .. versionadded:: 1.5 member_cache_flags: :class:`MemberCacheFlags` Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents. .. versionadded:: 1.5 fetch_offline_members: :class:`bool` A deprecated alias of ``chunk_guilds_at_startup``. chunk_guilds_at_startup: :class:`bool` Indicates if :func:`.on_ready` should be delayed to chunk all guilds at start-up if necessary. This operation is incredibly slow for large amounts of guilds. The default is ``True`` if :attr:`Intents.members` is ``True``. .. versionadded:: 1.5 status: Optional[:class:`.Status`] A status to start your presence with upon logging on to Discord. activity: Optional[:class:`.BaseActivity`] An activity to start your presence with upon logging on to Discord. allowed_mentions: Optional[:class:`AllowedMentions`] Control how the client handles mentions by default on every message sent. .. versionadded:: 1.4 heartbeat_timeout: :class:`float` The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if processing the initial packets take too long to the point of disconnecting you. The default timeout is 60 seconds. guild_ready_timeout: :class:`float` The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY. The default timeout is 2 seconds. .. versionadded:: 1.4 guild_subscriptions: :class:`bool` Whether to dispatch presence or typing events. Defaults to ``True``. .. versionadded:: 1.3 .. warning:: If this is set to ``False`` then the following features will be disabled: - No user related updates (:func:`on_user_update` will not dispatch) - All member related events will be disabled. - :func:`on_member_update` - :func:`on_member_join` - :func:`on_member_remove` - Typing events will be disabled (:func:`on_typing`). - If ``fetch_offline_members`` is set to ``False`` then the user cache will not exist. This makes it difficult or impossible to do many things, for example: - Computing permissions - Querying members in a voice channel via :attr:`VoiceChannel.members` will be empty. - Most forms of receiving :class:`Member` will be receiving :class:`User` instead, except for message events. - :attr:`Guild.owner` will usually resolve to ``None``. - :meth:`Guild.get_member` will usually be unavailable. - Anything that involves using :class:`Member`. - :attr:`users` will not be as populated. - etc. In short, this makes it so the only member you can reliably query is the message author. Useful for bots that do not require any state. assume_unsync_clock: :class:`bool` Whether to assume the system clock is unsynced. This applies to the ratelimit handling code. If this is set to ``True``, the default, then the library uses the time to reset a rate limit bucket given by Discord. If this is ``False`` then your system clock is used to calculate how long to sleep for. If this is set to ``False`` it is recommended to sync your system clock to Google's NTP server. .. versionadded:: 1.3 Attributes ----------- ws The websocket gateway the client is currently connected to. Could be ``None``. loop: :class:`asyncio.AbstractEventLoop` The event loop that the client uses for HTTP requests and websocket operations. """ def __init__(self, *, loop=None, **options): self.ws = None self.loop = asyncio.get_event_loop() if loop is None else loop self._listeners = {} self.shard_id = options.get('shard_id') self.shard_count = options.get('shard_count') connector = options.pop('connector', None) proxy = options.pop('proxy', None) proxy_auth = options.pop('proxy_auth', None) unsync_clock = options.pop('assume_unsync_clock', True) self.http = HTTPClient(connector, proxy=proxy, proxy_auth=proxy_auth, unsync_clock=unsync_clock, loop=self.loop) self._handlers = { 'ready': self._handle_ready } self._hooks = { 'before_identify': self._call_before_identify_hook } self._connection = self._get_state(**options) self._connection.shard_count = self.shard_count self._closed = False self._ready = asyncio.Event() self._connection._get_websocket = self._get_websocket self._connection._get_client = lambda: self if VoiceClient.warn_nacl: VoiceClient.warn_nacl = False log.warning("PyNaCl is not installed, voice will NOT be supported") # internals def _get_websocket(self, guild_id=None, *, shard_id=None): return self.ws def _get_state(self, **options): return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, syncer=self._syncer, http=self.http, loop=self.loop, **options) async def _syncer(self, guilds): await self.ws.request_sync(guilds) def _handle_ready(self): self._ready.set() @property def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This could be referred to as the Discord WebSocket protocol latency. """ ws = self.ws return float('nan') if not ws else ws.latency def is_ws_ratelimited(self): """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. .. versionadded:: 1.6 """ if self.ws: return self.ws.is_ratelimited() return False @property def user(self): """Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in.""" return self._connection.user @property def guilds(self): """List[:class:`.Guild`]: The guilds that the connected client is a member of.""" return self._connection.guilds @property def emojis(self): """List[:class:`.Emoji`]: The emojis that the connected client has.""" return self._connection.emojis @property def cached_messages(self): """Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached. .. versionadded:: 1.1 """ return utils.SequenceProxy(self._connection._messages or []) @property def private_channels(self): """List[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on. .. note:: This returns only up to 128 most recent private channels due to an internal working on how Discord deals with private channels. """ return self._connection.private_channels @property def voice_clients(self): """List[:class:`.VoiceProtocol`]: Represents a list of voice connections. These are usually :class:`.VoiceClient` instances. """ return self._connection.voice_clients def is_ready(self): """:class:`bool`: Specifies if the client's internal cache is ready for use.""" return self._ready.is_set() async def _run_event(self, coro, event_name, *args, **kwargs): try: await coro(*args, **kwargs) except asyncio.CancelledError: pass except Exception: try: await self.on_error(event_name, *args, **kwargs) except asyncio.CancelledError: pass def _schedule_event(self, coro, event_name, *args, **kwargs): wrapped = self._run_event(coro, event_name, *args, **kwargs) # Schedules the task return _ClientEventTask(original_coro=coro, event_name=event_name, coro=wrapped, loop=self.loop) def dispatch(self, event, *args, **kwargs): log.debug('Dispatching event %s', event) method = 'on_' + event listeners = self._listeners.get(event) if listeners: removed = [] for i, (future, condition) in enumerate(listeners): if future.cancelled(): removed.append(i) continue try: result = condition(*args) except Exception as exc: future.set_exception(exc) removed.append(i) else: if result: if len(args) == 0: future.set_result(None) elif len(args) == 1: future.set_result(args[0]) else: future.set_result(args) removed.append(i) if len(removed) == len(listeners): self._listeners.pop(event) else: for idx in reversed(removed): del listeners[idx] try: coro = getattr(self, method) except AttributeError: pass else: self._schedule_event(coro, method, *args, **kwargs) async def on_error(self, event_method, *args, **kwargs): """|coro| The default error handler provided by the client. By default this prints to :data:`sys.stderr` however it could be overridden to have a different implementation. Check :func:`~discord.on_error` for more details. """ print('Ignoring exception in {}'.format(event_method), file=sys.stderr) traceback.print_exc() @utils.deprecated('Guild.chunk') async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`.Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`.Guild.large` is ``True``. .. warning:: This method is deprecated. Use :meth:`Guild.chunk` instead. Parameters ----------- \*guilds: :class:`.Guild` An argument list of guilds to request offline members for. Raises ------- :exc:`.InvalidArgument` If any guild is unavailable in the collection. """ if any(g.unavailable for g in guilds): raise InvalidArgument('An unavailable guild was passed.') for guild in guilds: await self._connection.chunk_guild(guild) # hooks async def _call_before_identify_hook(self, shard_id, *, initial=False): # This hook is an internal hook that actually calls the public one. # It allows the library to have its own hook without stepping on the # toes of those who need to override their own hook. await self.before_identify_hook(shard_id, initial=initial) async def before_identify_hook(self, shard_id, *, initial=False): """|coro| A hook that is called before IDENTIFYing a session. This is useful if you wish to have more control over the synchronization of multiple IDENTIFYing clients. The default implementation sleeps for 5 seconds. .. versionadded:: 1.4 Parameters ------------ shard_id: :class:`int` The shard ID that requested being IDENTIFY'd initial: :class:`bool` Whether this IDENTIFY is the first initial IDENTIFY. """ if not initial: await asyncio.sleep(5.0) # login state management async def login(self, token, *, bot=True): """|coro| Logs in the client with the specified credentials. This function can be used in two different ways. .. warning:: Logging on with a user token is against the Discord `Terms of Service <https://support.discord.com/hc/en-us/articles/115002192352>`_ and doing so might potentially get your account banned. Use this at your own risk. Parameters ----------- token: :class:`str` The authentication token. Do not prefix this token with anything as the library will do it for you. bot: :class:`bool` Keyword argument that specifies if the account logging on is a bot token or not. .. deprecated:: 1.7 Raises ------ :exc:`.LoginFailure` The wrong credentials are passed. :exc:`.HTTPException` An unknown HTTP related error occurred, usually when it isn't 200 or the known incorrect credentials passing status code. """ log.info('logging in using static token') await self.http.static_login(token.strip(), bot=bot) self._connection.is_bot = bot @utils.deprecated('Client.close') async def logout(self): """|coro| Logs out of Discord and closes all connections. .. deprecated:: 1.7 .. note:: This is just an alias to :meth:`close`. If you want to do extraneous cleanup when subclassing, it is suggested to override :meth:`close` instead. """ await self.close() async def connect(self, *, reconnect=True): """|coro| Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated. Parameters ----------- reconnect: :class:`bool` If we should attempt reconnecting, either due to internet failure or a specific failure on Discord's part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens). Raises ------- :exc:`.GatewayNotFound` If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage. :exc:`.ConnectionClosed` The websocket connection has been terminated. """ backoff = ExponentialBackoff() ws_params = { 'initial': True, 'shard_id': self.shard_id, } while not self.is_closed(): try: coro = DiscordWebSocket.from_client(self, **ws_params) self.ws = await asyncio.wait_for(coro, timeout=60.0) ws_params['initial'] = False while True: await self.ws.poll_event() except ReconnectWebSocket as e: log.info('Got a request to %s the websocket.', e.op) self.dispatch('disconnect') ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id) continue except (OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError) as exc: self.dispatch('disconnect') if not reconnect: await self.close() if isinstance(exc, ConnectionClosed) and exc.code == 1000: # clean close, don't re-raise this return raise if self.is_closed(): return # If we get connection reset by peer then try to RESUME if isinstance(exc, OSError) and exc.errno in (54, 10054): ws_params.update(sequence=self.ws.sequence, initial=False, resume=True, session=self.ws.session_id) continue # We should only get this when an unhandled close code happens, # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) # sometimes, discord sends us 1000 for unknown reasons so we should reconnect # regardless and rely on is_closed instead if isinstance(exc, ConnectionClosed): if exc.code == 4014: raise PrivilegedIntentsRequired(exc.shard_id) from None if exc.code != 1000: await self.close() raise retry = backoff.delay() log.exception("Attempting a reconnect in %.2fs", retry) await asyncio.sleep(retry) # Always try to RESUME the connection # If the connection is not RESUME-able then the gateway will invalidate the session. # This is apparently what the official Discord client does. ws_params.update(sequence=self.ws.sequence, resume=True, session=self.ws.session_id) async def close(self): """|coro| Closes the connection to Discord. """ if self._closed: return await self.http.close() self._closed = True for voice in self.voice_clients: try: await voice.disconnect() except Exception: # if an error happens during disconnects, disregard it. pass if self.ws is not None and self.ws.open: await self.ws.close(code=1000) self._ready.clear() def clear(self): """Clears the internal state of the bot. After this, the bot can be considered "re-opened", i.e. :meth:`is_closed` and :meth:`is_ready` both return ``False`` along with the bot's internal cache cleared. """ self._closed = False self._ready.clear() self._connection.clear() self.http.recreate() async def start(self, *args, **kwargs): """|coro| A shorthand coroutine for :meth:`login` + :meth:`connect`. Raises ------- TypeError An unexpected keyword argument was received. """ bot = kwargs.pop('bot', True) reconnect = kwargs.pop('reconnect', True) if kwargs: raise TypeError("unexpected keyword argument(s) %s" % list(kwargs.keys())) await self.login(*args, bot=bot) await self.connect(reconnect=reconnect) def run(self, *args, **kwargs): """A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used. Use :meth:`start` coroutine or :meth:`connect` + :meth:`login`. Roughly Equivalent to: :: try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(close()) # cancel all tasks lingering finally: loop.close() .. warning:: This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns. """ loop = self.loop try: loop.add_signal_handler(signal.SIGINT, lambda: loop.stop()) loop.add_signal_handler(signal.SIGTERM, lambda: loop.stop()) except NotImplementedError: pass async def runner(): try: await self.start(*args, **kwargs) finally: if not self.is_closed(): await self.close() def stop_loop_on_completion(f): loop.stop() future = asyncio.ensure_future(runner(), loop=loop) future.add_done_callback(stop_loop_on_completion) try: loop.run_forever() except KeyboardInterrupt: log.info('Received signal to terminate bot and event loop.') finally: future.remove_done_callback(stop_loop_on_completion) log.info('Cleaning up tasks.') _cleanup_loop(loop) if not future.cancelled(): try: return future.result() except KeyboardInterrupt: # I am unsure why this gets raised here but suppress it anyway return None # properties def is_closed(self): """:class:`bool`: Indicates if the websocket connection is closed.""" return self._closed @property def activity(self): """Optional[:class:`.BaseActivity`]: The activity being used upon logging in. """ return create_activity(self._connection._activity) @activity.setter def activity(self, value): if value is None: self._connection._activity = None elif isinstance(value, BaseActivity): self._connection._activity = value.to_dict() else: raise TypeError('activity must derive from BaseActivity.') @property def allowed_mentions(self): """Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration. .. versionadded:: 1.4 """ return self._connection.allowed_mentions @allowed_mentions.setter def allowed_mentions(self, value): if value is None or isinstance(value, AllowedMentions): self._connection.allowed_mentions = value else: raise TypeError('allowed_mentions must be AllowedMentions not {0.__class__!r}'.format(value)) @property def intents(self): """:class:`~discord.Intents`: The intents configured for this connection. .. versionadded:: 1.5 """ return self._connection.intents # helpers/getters @property def users(self): """List[:class:`~discord.User`]: Returns a list of all the users the bot can see.""" return list(self._connection._users.values()) def get_channel(self, id): """Returns a channel with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`]] The returned channel or ``None`` if not found. """ return self._connection.get_channel(id) def get_guild(self, id): """Returns a guild with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.Guild`] The guild or ``None`` if not found. """ return self._connection._get_guild(id) def get_user(self, id): """Returns a user with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`~discord.User`] The user or ``None`` if not found. """ return self._connection.get_user(id) def get_emoji(self, id): """Returns an emoji with the given ID. Parameters ----------- id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.Emoji`] The custom emoji or ``None`` if not found. """ return self._connection.get_emoji(id) def get_all_channels(self): """A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'. This is equivalent to: :: for guild in client.guilds: for channel in guild.channels: yield channel .. note:: Just because you receive a :class:`.abc.GuildChannel` does not mean that you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` should be used for that. Yields ------ :class:`.abc.GuildChannel` A channel the client can 'access'. """ for guild in self.guilds: for channel in guild.channels: yield channel def get_all_members(self): """Returns a generator with every :class:`.Member` the client can see. This is equivalent to: :: for guild in client.guilds: for member in guild.members: yield member Yields ------ :class:`.Member` A member the client can see. """ for guild in self.guilds: for member in guild.members: yield member # listeners/waiters async def wait_until_ready(self): """|coro| Waits until the client's internal cache is all ready. """ await self._ready.wait() def wait_for(self, event, *, check=None, timeout=None): """|coro| Waits for a WebSocket event to be dispatched. This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way. The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, it does not timeout. Note that this does propagate the :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for ease of use. In case the event returns multiple arguments, a :class:`tuple` containing those arguments is returned instead. Please check the :ref:`documentation <discord-api-events>` for a list of events and their parameters. This function returns the **first event that meets the requirements**. Examples --------- Waiting for a user reply: :: @client.event async def on_message(message): if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(m): return m.content == 'hello' and m.channel == channel msg = await client.wait_for('message', check=check) await channel.send('Hello {.author}!'.format(msg)) Waiting for a thumbs up reaction from the message author: :: @client.event async def on_message(message): if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') def check(reaction, user): return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('\N{THUMBS DOWN SIGN}') else: await channel.send('\N{THUMBS UP SIGN}') Parameters ------------ event: :class:`str` The event name, similar to the :ref:`event reference <discord-api-events>`, but without the ``on_`` prefix, to wait for. check: Optional[Callable[..., :class:`bool`]] A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for. timeout: Optional[:class:`float`] The number of seconds to wait before timing out and raising :exc:`asyncio.TimeoutError`. Raises ------- asyncio.TimeoutError If a timeout is provided and it was reached. Returns -------- Any Returns no arguments, a single argument, or a :class:`tuple` of multiple arguments that mirrors the parameters passed in the :ref:`event reference <discord-api-events>`. """ future = self.loop.create_future() if check is None: def _check(*args): return True check = _check ev = event.lower() try: listeners = self._listeners[ev] except KeyError: listeners = [] self._listeners[ev] = listeners listeners.append((future, check)) return asyncio.wait_for(future, timeout) # event registration def event(self, coro): """A decorator that registers an event to listen to. You can find more info about the events on the :ref:`documentation below <discord-api-events>`. The events must be a :ref:`coroutine <coroutine>`, if not, :exc:`TypeError` is raised. Example --------- .. code-block:: python3 @client.event async def on_ready(): print('Ready!') Raises -------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('event registered must be a coroutine function') setattr(self, coro.__name__, coro) log.debug('%s has successfully been registered as an event', coro.__name__) return coro async def change_presence(self, *, activity=None, status=None, afk=False): """|coro| Changes the client's presence. Example --------- .. code-block:: python3 game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[:class:`.BaseActivity`] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`.Status`] Indicates what status to change to. If ``None``, then :attr:`.Status.online` is used. afk: Optional[:class:`bool`] Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. Raises ------ :exc:`.InvalidArgument` If the ``activity`` parameter is not the proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) await self.ws.change_presence(activity=activity, status=status, afk=afk) for guild in self._connection.guilds: me = guild.me if me is None: continue if activity is not None: me.activities = (activity,) else: me.activities = () me.status = status_enum # Guild stuff def fetch_guilds(self, *, limit=100, before=None, after=None): """Retrieves an :class:`.AsyncIterator` that enables receiving your guilds. .. note:: Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. .. note:: This method is an API call. For general usage, consider :attr:`guilds` instead. Examples --------- Usage :: async for guild in client.fetch_guilds(limit=150): print(guild.name) Flattening into a list :: guilds = await client.fetch_guilds(limit=150).flatten() # guilds is now a list of Guild... All parameters are optional. Parameters ----------- limit: Optional[:class:`int`] The number of guilds to retrieve. If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to ``100``. before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] Retrieves guilds before this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] Retrieve guilds after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ :exc:`.HTTPException` Getting the guilds failed. Yields -------- :class:`.Guild` The guild with the guild data parsed. """ return GuildIterator(self, limit=limit, before=before, after=after) async def fetch_template(self, code): """|coro| Gets a :class:`.Template` from a discord.new URL or code. Parameters ----------- code: Union[:class:`.Template`, :class:`str`] The Discord Template Code or URL (must be a discord.new URL). Raises ------- :exc:`.NotFound` The template is invalid. :exc:`.HTTPException` Getting the template failed. Returns -------- :class:`.Template` The template from the URL/code. """ code = utils.resolve_template(code) data = await self.http.get_template(code) return Template(data=data, state=self._connection) async def fetch_guild(self, guild_id): """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For general usage, consider :meth:`get_guild` instead. Parameters ----------- guild_id: :class:`int` The guild's ID to fetch from. Raises ------ :exc:`.Forbidden` You do not have access to the guild. :exc:`.HTTPException` Getting the guild failed. Returns -------- :class:`.Guild` The guild from the ID. """ data = await self.http.get_guild(guild_id) return Guild(data=data, state=self._connection) async def create_guild(self, name, region=None, icon=None, *, code=None): """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`.VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. code: Optional[:class:`str`] The code for a template to create the guild with. .. versionadded:: 1.4 Raises ------ :exc:`.HTTPException` Guild creation failed. :exc:`.InvalidArgument` Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = utils._bytes_to_base64_data(icon) region = region or VoiceRegion.us_west region_value = region.value if code: data = await self.http.create_from_template(code, name, region_value, icon) else: data = await self.http.create_guild(name, region_value, icon) return Guild(data=data, state=self._connection) # Invite management async def fetch_invite(self, url, *, with_counts=True): """|coro| Gets an :class:`.Invite` from a discord.gg URL or ID. .. note:: If the invite is for a guild you have not joined, the guild and channel attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and :class:`.PartialInviteChannel` respectively. Parameters ----------- url: Union[:class:`.Invite`, :class:`str`] The Discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` fields. Raises ------- :exc:`.NotFound` The invite has expired or is invalid. :exc:`.HTTPException` Getting the invite failed. Returns -------- :class:`.Invite` The invite from the URL/ID. """ invite_id = utils.resolve_invite(url) data = await self.http.get_invite(invite_id, with_counts=with_counts) return Invite.from_incomplete(state=self._connection, data=data) async def delete_invite(self, invite): """|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :class:`str`] The invite to revoke. Raises ------- :exc:`.Forbidden` You do not have permissions to revoke invites. :exc:`.NotFound` The invite is invalid or expired. :exc:`.HTTPException` Revoking the invite failed. """ invite_id = utils.resolve_invite(invite) await self.http.delete_invite(invite_id) # Miscellaneous stuff async def fetch_widget(self, guild_id): """|coro| Gets a :class:`.Widget` from a guild ID. .. note:: The guild must have the widget enabled to get this information. Parameters ----------- guild_id: :class:`int` The ID of the guild. Raises ------- :exc:`.Forbidden` The widget for this guild is disabled. :exc:`.HTTPException` Retrieving the widget failed. Returns -------- :class:`.Widget` The guild's widget. """ data = await self.http.get_widget(guild_id) return Widget(state=self._connection, data=data) async def application_info(self): """|coro| Retrieves the bot's application information. Raises ------- :exc:`.HTTPException` Retrieving the information failed somehow. Returns -------- :class:`.AppInfo` The bot's application information. """ data = await self.http.application_info() if 'rpc_origins' not in data: data['rpc_origins'] = None return AppInfo(self._connection, data) async def fetch_user(self, user_id): """|coro| Retrieves a :class:`~discord.User` based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do. .. note:: This method is an API call. If you have :attr:`Intents.members` and member cache enabled, consider :meth:`get_user` instead. Parameters ----------- user_id: :class:`int` The user's ID to fetch from. Raises ------- :exc:`.NotFound` A user with this ID does not exist. :exc:`.HTTPException` Fetching the user failed. Returns -------- :class:`~discord.User` The user you requested. """ data = await self.http.get_user(user_id) return User(state=self._connection, data=data) @utils.deprecated() async def fetch_user_profile(self, user_id): """|coro| Gets an arbitrary user's profile. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Parameters ------------ user_id: :class:`int` The ID of the user to fetch their profile for. Raises ------- :exc:`.Forbidden` Not allowed to fetch profiles. :exc:`.HTTPException` Fetching the profile failed. Returns -------- :class:`.Profile` The profile of the user. """ state = self._connection data = await self.http.get_user_profile(user_id) def transform(d): return state._get_guild(int(d['id'])) since = data.get('premium_since') mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', [])))) user = data['user'] return Profile(flags=user.get('flags', 0), premium_since=utils.parse_time(since), mutual_guilds=mutual_guilds, user=User(data=user, state=state), connected_accounts=data['connected_accounts']) async def fetch_channel(self, channel_id): """|coro| Retrieves a :class:`.abc.GuildChannel` or :class:`.abc.PrivateChannel` with the specified ID. .. note:: This method is an API call. For general usage, consider :meth:`get_channel` instead. .. versionadded:: 1.2 Raises ------- :exc:`.InvalidData` An unknown channel type was received from Discord. :exc:`.HTTPException` Retrieving the channel failed. :exc:`.NotFound` Invalid Channel ID. :exc:`.Forbidden` You do not have permission to fetch this channel. Returns -------- Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`] The channel from the ID. """ data = await self.http.get_channel(channel_id) factory, ch_type = _channel_factory(data['type']) if factory is None: raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(data)) if ch_type in (ChannelType.group, ChannelType.private): channel = factory(me=self.user, data=data, state=self._connection) else: guild_id = int(data['guild_id']) guild = self.get_guild(guild_id) or Object(id=guild_id) channel = factory(guild=guild, state=self._connection, data=data) return channel async def fetch_webhook(self, webhook_id): """|coro| Retrieves a :class:`.Webhook` with the specified ID. Raises -------- :exc:`.HTTPException` Retrieving the webhook failed. :exc:`.NotFound` Invalid webhook ID. :exc:`.Forbidden` You do not have permission to fetch this webhook. Returns --------- :class:`.Webhook` The webhook you requested. """ data = await self.http.get_webhook(webhook_id) return Webhook.from_state(data, state=self._connection)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/client.py
client.py
import struct from .errors import DiscordException class OggError(DiscordException): """An exception that is thrown for Ogg stream parsing errors.""" pass # https://tools.ietf.org/html/rfc3533 # https://tools.ietf.org/html/rfc7845 class OggPage: _header = struct.Struct('<xBQIIIB') def __init__(self, stream): try: header = stream.read(struct.calcsize(self._header.format)) self.flag, self.gran_pos, self.serial, \ self.pagenum, self.crc, self.segnum = self._header.unpack(header) self.segtable = stream.read(self.segnum) bodylen = sum(struct.unpack('B'*self.segnum, self.segtable)) self.data = stream.read(bodylen) except Exception: raise OggError('bad data stream') from None def iter_packets(self): packetlen = offset = 0 partial = True for seg in self.segtable: if seg == 255: packetlen += 255 partial = True else: packetlen += seg yield self.data[offset:offset+packetlen], True offset += packetlen packetlen = 0 partial = False if partial: yield self.data[offset:], False class OggStream: def __init__(self, stream): self.stream = stream def _next_page(self): head = self.stream.read(4) if head == b'OggS': return OggPage(self.stream) elif not head: return None else: raise OggError('invalid header magic') def _iter_pages(self): page = self._next_page() while page: yield page page = self._next_page() def iter_packets(self): partial = b'' for page in self._iter_pages(): for data, complete in page.iter_packets(): partial += data if complete: yield partial partial = b''
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/oggparse.py
oggparse.py
import datetime from .utils import _get_as_snowflake, get, parse_time from .user import User from .errors import InvalidArgument from .enums import try_enum, ExpireBehaviour class IntegrationAccount: """Represents an integration account. .. versionadded:: 1.4 Attributes ----------- id: :class:`int` The account ID. name: :class:`str` The account name. """ __slots__ = ('id', 'name') def __init__(self, **kwargs): self.id = kwargs.pop('id') self.name = kwargs.pop('name') def __repr__(self): return '<IntegrationAccount id={0.id} name={0.name!r}>'.format(self) class Integration: """Represents a guild integration. .. versionadded:: 1.4 Attributes ----------- id: :class:`int` The integration ID. name: :class:`str` The integration name. guild: :class:`Guild` The guild of the integration. type: :class:`str` The integration type (i.e. Twitch). enabled: :class:`bool` Whether the integration is currently enabled. syncing: :class:`bool` Where the integration is currently syncing. role: :class:`Role` The role which the integration uses for subscribers. enable_emoticons: Optional[:class:`bool`] Whether emoticons should be synced for this integration (currently twitch only). expire_behaviour: :class:`ExpireBehaviour` The behaviour of expiring subscribers. Aliased to ``expire_behavior`` as well. expire_grace_period: :class:`int` The grace period (in days) for expiring subscribers. user: :class:`User` The user for the integration. account: :class:`IntegrationAccount` The integration account information. synced_at: :class:`datetime.datetime` When the integration was last synced. """ __slots__ = ('id', '_state', 'guild', 'name', 'enabled', 'type', 'syncing', 'role', 'expire_behaviour', 'expire_behavior', 'expire_grace_period', 'synced_at', 'user', 'account', 'enable_emoticons', '_role_id') def __init__(self, *, data, guild): self.guild = guild self._state = guild._state self._from_data(data) def __repr__(self): return '<Integration id={0.id} name={0.name!r} type={0.type!r}>'.format(self) def _from_data(self, integ): self.id = _get_as_snowflake(integ, 'id') self.name = integ['name'] self.type = integ['type'] self.enabled = integ['enabled'] self.syncing = integ['syncing'] self._role_id = _get_as_snowflake(integ, 'role_id') self.role = get(self.guild.roles, id=self._role_id) self.enable_emoticons = integ.get('enable_emoticons') self.expire_behaviour = try_enum(ExpireBehaviour, integ['expire_behavior']) self.expire_behavior = self.expire_behaviour self.expire_grace_period = integ['expire_grace_period'] self.synced_at = parse_time(integ['synced_at']) self.user = User(state=self._state, data=integ['user']) self.account = IntegrationAccount(**integ['account']) async def edit(self, **fields): """|coro| Edits the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Parameters ----------- expire_behaviour: :class:`ExpireBehaviour` The behaviour when an integration subscription lapses. Aliased to ``expire_behavior`` as well. expire_grace_period: :class:`int` The period (in days) where the integration will ignore lapsed subscriptions. enable_emoticons: :class:`bool` Where emoticons should be synced for this integration (currently twitch only). Raises ------- Forbidden You do not have permission to edit the integration. HTTPException Editing the guild failed. InvalidArgument ``expire_behaviour`` did not receive a :class:`ExpireBehaviour`. """ try: expire_behaviour = fields['expire_behaviour'] except KeyError: expire_behaviour = fields.get('expire_behavior', self.expire_behaviour) if not isinstance(expire_behaviour, ExpireBehaviour): raise InvalidArgument('expire_behaviour field must be of type ExpireBehaviour') expire_grace_period = fields.get('expire_grace_period', self.expire_grace_period) payload = { 'expire_behavior': expire_behaviour.value, 'expire_grace_period': expire_grace_period, } enable_emoticons = fields.get('enable_emoticons') if enable_emoticons is not None: payload['enable_emoticons'] = enable_emoticons await self._state.http.edit_integration(self.guild.id, self.id, **payload) self.expire_behaviour = expire_behaviour self.expire_behavior = self.expire_behaviour self.expire_grace_period = expire_grace_period self.enable_emoticons = enable_emoticons async def sync(self): """|coro| Syncs the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Raises ------- Forbidden You do not have permission to sync the integration. HTTPException Syncing the integration failed. """ await self._state.http.sync_integration(self.guild.id, self.id) self.synced_at = datetime.datetime.utcnow() async def delete(self): """|coro| Deletes the integration. You must have the :attr:`~Permissions.manage_guild` permission to do this. Raises ------- Forbidden You do not have permission to delete the integration. HTTPException Deleting the integration failed. """ await self._state.http.delete_integration(self.guild.id, self.id)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/integrations.py
integrations.py
from .permissions import Permissions from .errors import InvalidArgument from .colour import Colour from .mixins import Hashable from .utils import snowflake_time, _get_as_snowflake class RoleTags: """Represents tags on a role. A role tag is a piece of extra information attached to a managed role that gives it context for the reason the role is managed. While this can be accessed, a useful interface is also provided in the :class:`Role` and :class:`Guild` classes as well. .. versionadded:: 1.6 Attributes ------------ bot_id: Optional[:class:`int`] The bot's user ID that manages this role. integration_id: Optional[:class:`int`] The integration ID that manages the role. """ __slots__ = ('bot_id', 'integration_id', '_premium_subscriber',) def __init__(self, data): self.bot_id = _get_as_snowflake(data, 'bot_id') self.integration_id = _get_as_snowflake(data, 'integration_id') # NOTE: The API returns "null" for this if it's valid, which corresponds to None. # This is different from other fields where "null" means "not there". # So in this case, a value of None is the same as True. # Which means we would need a different sentinel. For this purpose I used ellipsis. self._premium_subscriber = data.get('premium_subscriber', ...) def is_bot_managed(self): """:class:`bool`: Whether the role is associated with a bot.""" return self.bot_id is not None def is_premium_subscriber(self): """:class:`bool`: Whether the role is the premium subscriber, AKA "boost", role for the guild.""" return self._premium_subscriber is None def is_integration(self): """:class:`bool`: Whether the role is managed by an integration.""" return self.integration_id is not None def __repr__(self): return '<RoleTags bot_id={0.bot_id} integration_id={0.integration_id} ' \ 'premium_subscriber={1}>'.format(self, self.is_premium_subscriber()) class Role(Hashable): """Represents a Discord role in a :class:`Guild`. .. container:: operations .. describe:: x == y Checks if two roles are equal. .. describe:: x != y Checks if two roles are not equal. .. describe:: x > y Checks if a role is higher than another in the hierarchy. .. describe:: x < y Checks if a role is lower than another in the hierarchy. .. describe:: x >= y Checks if a role is higher or equal to another in the hierarchy. .. describe:: x <= y Checks if a role is lower or equal to another in the hierarchy. .. describe:: hash(x) Return the role's hash. .. describe:: str(x) Returns the role's name. Attributes ---------- id: :class:`int` The ID for the role. name: :class:`str` The name of the role. guild: :class:`Guild` The guild the role belongs to. hoist: :class:`bool` Indicates if the role will be displayed separately from other members. position: :class:`int` The position of the role. This number is usually positive. The bottom role has a position of 0. managed: :class:`bool` Indicates if the role is managed by the guild through some form of integrations such as Twitch. mentionable: :class:`bool` Indicates if the role can be mentioned by users. tags: Optional[:class:`RoleTags`] The role tags associated with this role. """ __slots__ = ('id', 'name', '_permissions', '_colour', 'position', 'managed', 'mentionable', 'hoist', 'guild', 'tags', '_state') def __init__(self, *, guild, state, data): self.guild = guild self._state = state self.id = int(data['id']) self._update(data) def __str__(self): return self.name def __repr__(self): return '<Role id={0.id} name={0.name!r}>'.format(self) def __lt__(self, other): if not isinstance(other, Role) or not isinstance(self, Role): return NotImplemented if self.guild != other.guild: raise RuntimeError('cannot compare roles from two different guilds.') # the @everyone role is always the lowest role in hierarchy guild_id = self.guild.id if self.id == guild_id: # everyone_role < everyone_role -> False return other.id != guild_id if self.position < other.position: return True if self.position == other.position: return int(self.id) > int(other.id) return False def __le__(self, other): r = Role.__lt__(other, self) if r is NotImplemented: return NotImplemented return not r def __gt__(self, other): return Role.__lt__(other, self) def __ge__(self, other): r = Role.__lt__(self, other) if r is NotImplemented: return NotImplemented return not r def _update(self, data): self.name = data['name'] self._permissions = int(data.get('permissions_new', 0)) self.position = data.get('position', 0) self._colour = data.get('color', 0) self.hoist = data.get('hoist', False) self.managed = data.get('managed', False) self.mentionable = data.get('mentionable', False) try: self.tags = RoleTags(data['tags']) except KeyError: self.tags = None def is_default(self): """:class:`bool`: Checks if the role is the default role.""" return self.guild.id == self.id def is_bot_managed(self): """:class:`bool`: Whether the role is associated with a bot. .. versionadded:: 1.6 """ return self.tags is not None and self.tags.is_bot_managed() def is_premium_subscriber(self): """:class:`bool`: Whether the role is the premium subscriber, AKA "boost", role for the guild. .. versionadded:: 1.6 """ return self.tags is not None and self.tags.is_premium_subscriber() def is_integration(self): """:class:`bool`: Whether the role is managed by an integration. .. versionadded:: 1.6 """ return self.tags is not None and self.tags.is_integration() @property def permissions(self): """:class:`Permissions`: Returns the role's permissions.""" return Permissions(self._permissions) @property def colour(self): """:class:`Colour`: Returns the role colour. An alias exists under ``color``.""" return Colour(self._colour) @property def color(self): """:class:`Colour`: Returns the role color. An alias exists under ``colour``.""" return self.colour @property def created_at(self): """:class:`datetime.datetime`: Returns the role's creation time in UTC.""" return snowflake_time(self.id) @property def mention(self): """:class:`str`: Returns a string that allows you to mention a role.""" return '<@&%s>' % self.id @property def members(self): """List[:class:`Member`]: Returns all the members with this role.""" all_members = self.guild.members if self.is_default(): return all_members role_id = self.id return [member for member in all_members if member._roles.has(role_id)] async def _move(self, position, reason): if position <= 0: raise InvalidArgument("Cannot move role to position 0 or below") if self.is_default(): raise InvalidArgument("Cannot move default role") if self.position == position: return # Save discord the extra request. http = self._state.http change_range = range(min(self.position, position), max(self.position, position) + 1) roles = [r.id for r in self.guild.roles[1:] if r.position in change_range and r.id != self.id] if self.position > position: roles.insert(0, self.id) else: roles.append(self.id) payload = [{"id": z[0], "position": z[1]} for z in zip(roles, change_range)] await http.move_role_position(self.guild.id, payload, reason=reason) async def edit(self, *, reason=None, **fields): """|coro| Edits the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. All fields are optional. .. versionchanged:: 1.4 Can now pass ``int`` to ``colour`` keyword-only parameter. Parameters ----------- name: :class:`str` The new role name to change to. permissions: :class:`Permissions` The new permissions to change to. colour: Union[:class:`Colour`, :class:`int`] The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. mentionable: :class:`bool` Indicates if the role should be mentionable by others. position: :class:`int` The new role's position. This must be below your top role's position or it will fail. reason: Optional[:class:`str`] The reason for editing this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to change the role. HTTPException Editing the role failed. InvalidArgument An invalid position was given or the default role was asked to be moved. """ position = fields.get('position') if position is not None: await self._move(position, reason=reason) self.position = position try: colour = fields['colour'] except KeyError: colour = fields.get('color', self.colour) if isinstance(colour, int): colour = Colour(value=colour) payload = { 'name': fields.get('name', self.name), 'permissions': str(fields.get('permissions', self.permissions).value), 'color': colour.value, 'hoist': fields.get('hoist', self.hoist), 'mentionable': fields.get('mentionable', self.mentionable) } data = await self._state.http.edit_role(self.guild.id, self.id, reason=reason, **payload) self._update(data) async def delete(self, *, reason=None): """|coro| Deletes the role. You must have the :attr:`~Permissions.manage_roles` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this role. Shows up on the audit log. Raises -------- Forbidden You do not have permissions to delete the role. HTTPException Deleting the role failed. """ await self._state.http.delete_role(self.guild.id, self.id, reason=reason)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/role.py
role.py
import copy from collections import namedtuple from . import utils from .role import Role from .member import Member, VoiceState from .emoji import Emoji from .errors import InvalidData from .permissions import PermissionOverwrite from .colour import Colour from .errors import InvalidArgument, ClientException from .channel import * from .enums import VoiceRegion, ChannelType, try_enum, VerificationLevel, ContentFilter, NotificationLevel from .mixins import Hashable from .user import User from .invite import Invite from .iterators import AuditLogIterator, MemberIterator from .widget import Widget from .asset import Asset from .flags import SystemChannelFlags from .integrations import Integration BanEntry = namedtuple('BanEntry', 'reason user') _GuildLimit = namedtuple('_GuildLimit', 'emoji bitrate filesize') class Guild(Hashable): """Represents a Discord guild. This is referred to as a "server" in the official Discord UI. .. container:: operations .. describe:: x == y Checks if two guilds are equal. .. describe:: x != y Checks if two guilds are not equal. .. describe:: hash(x) Returns the guild's hash. .. describe:: str(x) Returns the guild's name. Attributes ---------- name: :class:`str` The guild name. emojis: Tuple[:class:`Emoji`, ...] All emojis that the guild owns. region: :class:`VoiceRegion` The region the guild belongs on. There is a chance that the region will be a :class:`str` if the value is not recognised by the enumerator. afk_timeout: :class:`int` The timeout to get sent to the AFK channel. afk_channel: Optional[:class:`VoiceChannel`] The channel that denotes the AFK channel. ``None`` if it doesn't exist. icon: Optional[:class:`str`] The guild's icon. id: :class:`int` The guild's ID. owner_id: :class:`int` The guild owner's ID. Use :attr:`Guild.owner` instead. unavailable: :class:`bool` Indicates if the guild is unavailable. If this is ``True`` then the reliability of other attributes outside of :attr:`Guild.id` is slim and they might all be ``None``. It is best to not do anything with the guild if it is unavailable. Check the :func:`on_guild_unavailable` and :func:`on_guild_available` events. max_presences: Optional[:class:`int`] The maximum amount of presences for the guild. max_members: Optional[:class:`int`] The maximum amount of members for the guild. .. note:: This attribute is only available via :meth:`.Client.fetch_guild`. max_video_channel_users: Optional[:class:`int`] The maximum amount of users in a video channel. .. versionadded:: 1.4 banner: Optional[:class:`str`] The guild's banner. description: Optional[:class:`str`] The guild's description. mfa_level: :class:`int` Indicates the guild's two factor authorisation level. If this value is 0 then the guild does not require 2FA for their administrative members. If the value is 1 then they do. verification_level: :class:`VerificationLevel` The guild's verification level. explicit_content_filter: :class:`ContentFilter` The guild's explicit content filter. default_notifications: :class:`NotificationLevel` The guild's notification settings. features: List[:class:`str`] A list of features that the guild has. They are currently as follows: - ``VIP_REGIONS``: Guild has VIP voice regions - ``VANITY_URL``: Guild can have a vanity invite URL (e.g. discord.gg/discord-api) - ``INVITE_SPLASH``: Guild's invite page can have a special splash. - ``VERIFIED``: Guild is a verified server. - ``PARTNERED``: Guild is a partnered server. - ``MORE_EMOJI``: Guild is allowed to have more than 50 custom emoji. - ``DISCOVERABLE``: Guild shows up in Server Discovery. - ``FEATURABLE``: Guild is able to be featured in Server Discovery. - ``COMMUNITY``: Guild is a community server. - ``COMMERCE``: Guild can sell things using store channels. - ``PUBLIC``: Guild is a public guild. - ``NEWS``: Guild can create news channels. - ``BANNER``: Guild can upload and use a banner (i.e. :meth:`banner_url`). - ``ANIMATED_ICON``: Guild can upload an animated icon. - ``PUBLIC_DISABLED``: Guild cannot be public. - ``WELCOME_SCREEN_ENABLED``: Guild has enabled the welcome screen - ``MEMBER_VERIFICATION_GATE_ENABLED``: Guild has Membership Screening enabled. - ``PREVIEW_ENABLED``: Guild can be viewed before being accepted via Membership Screening. splash: Optional[:class:`str`] The guild's invite splash. premium_tier: :class:`int` The premium tier for this guild. Corresponds to "Nitro Server" in the official UI. The number goes from 0 to 3 inclusive. premium_subscription_count: :class:`int` The number of "boosts" this guild currently has. preferred_locale: Optional[:class:`str`] The preferred locale for the guild. Used when filtering Server Discovery results to a specific language. discovery_splash: :class:`str` The guild's discovery splash. .. versionadded:: 1.3 """ __slots__ = ('afk_timeout', 'afk_channel', '_members', '_channels', 'icon', 'name', 'id', 'unavailable', 'banner', 'region', '_state', '_roles', '_member_count', '_large', 'owner_id', 'mfa_level', 'emojis', 'features', 'verification_level', 'explicit_content_filter', 'splash', '_voice_states', '_system_channel_id', 'default_notifications', 'description', 'max_presences', 'max_members', 'max_video_channel_users', 'premium_tier', 'premium_subscription_count', '_system_channel_flags', 'preferred_locale', 'discovery_splash', '_rules_channel_id', '_public_updates_channel_id') _PREMIUM_GUILD_LIMITS = { None: _GuildLimit(emoji=50, bitrate=96e3, filesize=8388608), 0: _GuildLimit(emoji=50, bitrate=96e3, filesize=8388608), 1: _GuildLimit(emoji=100, bitrate=128e3, filesize=8388608), 2: _GuildLimit(emoji=150, bitrate=256e3, filesize=52428800), 3: _GuildLimit(emoji=250, bitrate=384e3, filesize=104857600), } def __init__(self, *, data, state): self._channels = {} self._members = {} self._voice_states = {} self._state = state self._from_data(data) def _add_channel(self, channel): self._channels[channel.id] = channel def _remove_channel(self, channel): self._channels.pop(channel.id, None) def _voice_state_for(self, user_id): return self._voice_states.get(user_id) def _add_member(self, member): self._members[member.id] = member def _remove_member(self, member): self._members.pop(member.id, None) def __str__(self): return self.name or '' def __repr__(self): attrs = ( 'id', 'name', 'shard_id', 'chunked' ) resolved = ['%s=%r' % (attr, getattr(self, attr)) for attr in attrs] resolved.append('member_count=%r' % getattr(self, '_member_count', None)) return '<Guild %s>' % ' '.join(resolved) def _update_voice_state(self, data, channel_id): user_id = int(data['user_id']) channel = self.get_channel(channel_id) try: # check if we should remove the voice state from cache if channel is None: after = self._voice_states.pop(user_id) else: after = self._voice_states[user_id] before = copy.copy(after) after._update(data, channel) except KeyError: # if we're here then we're getting added into the cache after = VoiceState(data=data, channel=channel) before = VoiceState(data=data, channel=None) self._voice_states[user_id] = after member = self.get_member(user_id) if member is None: try: member = Member(data=data['member'], state=self._state, guild=self) except KeyError: member = None return member, before, after def _add_role(self, role): # roles get added to the bottom (position 1, pos 0 is @everyone) # so since self.roles has the @everyone role, we can't increment # its position because it's stuck at position 0. Luckily x += False # is equivalent to adding 0. So we cast the position to a bool and # increment it. for r in self._roles.values(): r.position += (not r.is_default()) self._roles[role.id] = role def _remove_role(self, role_id): # this raises KeyError if it fails.. role = self._roles.pop(role_id) # since it didn't, we can change the positions now # basically the same as above except we only decrement # the position if we're above the role we deleted. for r in self._roles.values(): r.position -= r.position > role.position return role def _from_data(self, guild): # according to Stan, this is always available even if the guild is unavailable # I don't have this guarantee when someone updates the guild. member_count = guild.get('member_count', None) if member_count is not None: self._member_count = member_count self.name = guild.get('name') self.region = try_enum(VoiceRegion, guild.get('region')) self.verification_level = try_enum(VerificationLevel, guild.get('verification_level')) self.default_notifications = try_enum(NotificationLevel, guild.get('default_message_notifications')) self.explicit_content_filter = try_enum(ContentFilter, guild.get('explicit_content_filter', 0)) self.afk_timeout = guild.get('afk_timeout') self.icon = guild.get('icon') self.banner = guild.get('banner') self.unavailable = guild.get('unavailable', False) self.id = int(guild['id']) self._roles = {} state = self._state # speed up attribute access for r in guild.get('roles', []): role = Role(guild=self, data=r, state=state) self._roles[role.id] = role self.mfa_level = guild.get('mfa_level') self.emojis = tuple(map(lambda d: state.store_emoji(self, d), guild.get('emojis', []))) self.features = guild.get('features', []) self.splash = guild.get('splash') self._system_channel_id = utils._get_as_snowflake(guild, 'system_channel_id') self.description = guild.get('description') self.max_presences = guild.get('max_presences') self.max_members = guild.get('max_members') self.max_video_channel_users = guild.get('max_video_channel_users') self.premium_tier = guild.get('premium_tier', 0) self.premium_subscription_count = guild.get('premium_subscription_count') or 0 self._system_channel_flags = guild.get('system_channel_flags', 0) self.preferred_locale = guild.get('preferred_locale') self.discovery_splash = guild.get('discovery_splash') self._rules_channel_id = utils._get_as_snowflake(guild, 'rules_channel_id') self._public_updates_channel_id = utils._get_as_snowflake(guild, 'public_updates_channel_id') cache_online_members = self._state.member_cache_flags.online cache_joined = self._state.member_cache_flags.joined self_id = self._state.self_id for mdata in guild.get('members', []): member = Member(data=mdata, guild=self, state=state) if cache_joined or (cache_online_members and member.raw_status != 'offline') or member.id == self_id: self._add_member(member) self._sync(guild) self._large = None if member_count is None else self._member_count >= 250 self.owner_id = utils._get_as_snowflake(guild, 'owner_id') self.afk_channel = self.get_channel(utils._get_as_snowflake(guild, 'afk_channel_id')) for obj in guild.get('voice_states', []): self._update_voice_state(obj, int(obj['channel_id'])) def _sync(self, data): try: self._large = data['large'] except KeyError: pass empty_tuple = tuple() for presence in data.get('presences', []): user_id = int(presence['user']['id']) member = self.get_member(user_id) if member is not None: member._presence_update(presence, empty_tuple) if 'channels' in data: channels = data['channels'] for c in channels: factory, ch_type = _channel_factory(c['type']) if factory: self._add_channel(factory(guild=self, data=c, state=self._state)) @property def channels(self): """List[:class:`abc.GuildChannel`]: A list of channels that belongs to this guild.""" return list(self._channels.values()) @property def large(self): """:class:`bool`: Indicates if the guild is a 'large' guild. A large guild is defined as having more than ``large_threshold`` count members, which for this library is set to the maximum of 250. """ if self._large is None: try: return self._member_count >= 250 except AttributeError: return len(self._members) >= 250 return self._large @property def voice_channels(self): """List[:class:`VoiceChannel`]: A list of voice channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def stage_channels(self): """List[:class:`StageChannel`]: A list of voice channels that belongs to this guild. .. versionadded:: 1.7 This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, StageChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def me(self): """:class:`Member`: Similar to :attr:`Client.user` except an instance of :class:`Member`. This is essentially used to get the member version of yourself. """ self_id = self._state.user.id return self.get_member(self_id) @property def voice_client(self): """Optional[:class:`VoiceProtocol`]: Returns the :class:`VoiceProtocol` associated with this guild, if any.""" return self._state._get_voice_client(self.id) @property def text_channels(self): """List[:class:`TextChannel`]: A list of text channels that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)] r.sort(key=lambda c: (c.position, c.id)) return r @property def categories(self): """List[:class:`CategoryChannel`]: A list of categories that belongs to this guild. This is sorted by the position and are in UI order from top to bottom. """ r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)] r.sort(key=lambda c: (c.position, c.id)) return r def by_category(self): """Returns every :class:`CategoryChannel` and their associated channels. These channels and categories are sorted in the official Discord UI order. If the channels do not have a category, then the first element of the tuple is ``None``. Returns -------- List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]: The categories and their associated channels. """ grouped = {} for channel in self._channels.values(): if isinstance(channel, CategoryChannel): grouped.setdefault(channel.id, []) continue try: grouped[channel.category_id].append(channel) except KeyError: grouped[channel.category_id] = [channel] def key(t): k, v = t return ((k.position, k.id) if k else (-1, -1), v) _get = self._channels.get as_list = [(_get(k), v) for k, v in grouped.items()] as_list.sort(key=key) for _, channels in as_list: channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id)) return as_list def get_channel(self, channel_id): """Returns a channel with the given ID. Parameters ----------- channel_id: :class:`int` The ID to search for. Returns -------- Optional[:class:`.abc.GuildChannel`] The returned channel or ``None`` if not found. """ return self._channels.get(channel_id) @property def system_channel(self): """Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. If no channel is set, then this returns ``None``. """ channel_id = self._system_channel_id return channel_id and self._channels.get(channel_id) @property def system_channel_flags(self): """:class:`SystemChannelFlags`: Returns the guild's system channel settings.""" return SystemChannelFlags._from_value(self._system_channel_flags) @property def rules_channel(self): """Optional[:class:`TextChannel`]: Return's the guild's channel used for the rules. The guild must be a Community guild. If no channel is set, then this returns ``None``. .. versionadded:: 1.3 """ channel_id = self._rules_channel_id return channel_id and self._channels.get(channel_id) @property def public_updates_channel(self): """Optional[:class:`TextChannel`]: Return's the guild's channel where admins and moderators of the guilds receive notices from Discord. The guild must be a Community guild. If no channel is set, then this returns ``None``. .. versionadded:: 1.4 """ channel_id = self._public_updates_channel_id return channel_id and self._channels.get(channel_id) @property def emoji_limit(self): """:class:`int`: The maximum number of emoji slots this guild has.""" more_emoji = 200 if 'MORE_EMOJI' in self.features else 50 return max(more_emoji, self._PREMIUM_GUILD_LIMITS[self.premium_tier].emoji) @property def bitrate_limit(self): """:class:`float`: The maximum bitrate for voice channels this guild can have.""" vip_guild = self._PREMIUM_GUILD_LIMITS[1].bitrate if 'VIP_REGIONS' in self.features else 96e3 return max(vip_guild, self._PREMIUM_GUILD_LIMITS[self.premium_tier].bitrate) @property def filesize_limit(self): """:class:`int`: The maximum number of bytes files can have when uploaded to this guild.""" return self._PREMIUM_GUILD_LIMITS[self.premium_tier].filesize @property def members(self): """List[:class:`Member`]: A list of members that belong to this guild.""" return list(self._members.values()) def get_member(self, user_id): """Returns a member with the given ID. Parameters ----------- user_id: :class:`int` The ID to search for. Returns -------- Optional[:class:`Member`] The member or ``None`` if not found. """ return self._members.get(user_id) @property def premium_subscribers(self): """List[:class:`Member`]: A list of members who have "boosted" this guild.""" return [member for member in self.members if member.premium_since is not None] @property def roles(self): """List[:class:`Role`]: Returns a :class:`list` of the guild's roles in hierarchy order. The first element of this list will be the lowest role in the hierarchy. """ return sorted(self._roles.values()) def get_role(self, role_id): """Returns a role with the given ID. Parameters ----------- role_id: :class:`int` The ID to search for. Returns -------- Optional[:class:`Role`] The role or ``None`` if not found. """ return self._roles.get(role_id) @property def default_role(self): """:class:`Role`: Gets the @everyone role that all members have by default.""" return self.get_role(self.id) @property def premium_subscriber_role(self): """Optional[:class:`Role`]: Gets the premium subscriber role, AKA "boost" role, in this guild. .. versionadded:: 1.6 """ for role in self._roles.values(): if role.is_premium_subscriber(): return role return None @property def self_role(self): """Optional[:class:`Role`]: Gets the role associated with this client's user, if any. .. versionadded:: 1.6 """ self_id = self._state.self_id for role in self._roles.values(): tags = role.tags if tags and tags.bot_id == self_id: return role return None @property def owner(self): """Optional[:class:`Member`]: The member that owns the guild.""" return self.get_member(self.owner_id) @property def icon_url(self): """:class:`Asset`: Returns the guild's icon asset.""" return self.icon_url_as() def is_icon_animated(self): """:class:`bool`: Returns True if the guild has an animated icon.""" return bool(self.icon and self.icon.startswith('a_')) def icon_url_as(self, *, format=None, static_format='webp', size=1024): """Returns an :class:`Asset` for the guild's icon. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 4096. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the icon to. If the format is ``None``, then it is automatically detected into either 'gif' or static_format depending on the icon being animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated icons to. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_icon(self._state, self, format=format, static_format=static_format, size=size) @property def banner_url(self): """:class:`Asset`: Returns the guild's banner asset.""" return self.banner_url_as() def banner_url_as(self, *, format='webp', size=2048): """Returns an :class:`Asset` for the guild's banner. The format must be one of 'webp', 'jpeg', or 'png'. The size must be a power of 2 between 16 and 4096. Parameters ----------- format: :class:`str` The format to attempt to convert the banner to. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_image(self._state, self.id, self.banner, 'banners', format=format, size=size) @property def splash_url(self): """:class:`Asset`: Returns the guild's invite splash asset.""" return self.splash_url_as() def splash_url_as(self, *, format='webp', size=2048): """Returns an :class:`Asset` for the guild's invite splash. The format must be one of 'webp', 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 4096. Parameters ----------- format: :class:`str` The format to attempt to convert the splash to. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size) @property def discovery_splash_url(self): """:class:`Asset`: Returns the guild's discovery splash asset. .. versionadded:: 1.3 """ return self.discovery_splash_url_as() def discovery_splash_url_as(self, *, format='webp', size=2048): """Returns an :class:`Asset` for the guild's discovery splash. The format must be one of 'webp', 'jpeg', 'jpg', or 'png'. The size must be a power of 2 between 16 and 4096. .. versionadded:: 1.3 Parameters ----------- format: :class:`str` The format to attempt to convert the splash to. size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_guild_image(self._state, self.id, self.discovery_splash, 'discovery-splashes', format=format, size=size) @property def member_count(self): """:class:`int`: Returns the true member count regardless of it being loaded fully or not. .. warning:: Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires :attr:`Intents.members` to be specified. """ return self._member_count @property def chunked(self): """:class:`bool`: Returns a boolean indicating if the guild is "chunked". A chunked guild means that :attr:`member_count` is equal to the number of members stored in the internal :attr:`members` cache. If this value returns ``False``, then you should request for offline members. """ count = getattr(self, '_member_count', None) if count is None: return False return count == len(self._members) @property def shard_id(self): """:class:`int`: Returns the shard ID for this guild if applicable.""" count = self._state.shard_count if count is None: return None return (self.id >> 22) % count @property def created_at(self): """:class:`datetime.datetime`: Returns the guild's creation time in UTC.""" return utils.snowflake_time(self.id) def get_member_named(self, name): """Returns the first member found that matches the name provided. The name can have an optional discriminator argument, e.g. "Jake#0001" or "Jake" will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work. If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique. If no member is found, ``None`` is returned. Parameters ----------- name: :class:`str` The name of the member to lookup with an optional discriminator. Returns -------- Optional[:class:`Member`] The member in this guild with the associated name. If not found then ``None`` is returned. """ result = None members = self.members if len(name) > 5 and name[-5] == '#': # The 5 length is checking to see if #0000 is in the string, # as a#0000 has a length of 6, the minimum for a potential # discriminator lookup. potential_discriminator = name[-4:] # do the actual lookup and return if found # if it isn't found then we'll do a full name lookup below. result = utils.get(members, name=name[:-5], discriminator=potential_discriminator) if result is not None: return result def pred(m): return m.nick == name or m.name == name return utils.find(pred, members) def _create_channel(self, name, overwrites, channel_type, category=None, **options): if overwrites is None: overwrites = {} elif not isinstance(overwrites, dict): raise InvalidArgument('overwrites parameter expects a dict.') perms = [] for target, perm in overwrites.items(): if not isinstance(perm, PermissionOverwrite): raise InvalidArgument('Expected PermissionOverwrite received {0.__name__}'.format(type(perm))) allow, deny = perm.pair() payload = { 'allow': allow.value, 'deny': deny.value, 'id': target.id } if isinstance(target, Role): payload['type'] = 'role' else: payload['type'] = 'member' perms.append(payload) try: options['rate_limit_per_user'] = options.pop('slowmode_delay') except KeyError: pass try: rtc_region = options.pop('rtc_region') except KeyError: pass else: options['rtc_region'] = None if rtc_region is None else str(rtc_region) parent_id = category.id if category else None return self._state.http.create_channel(self.id, channel_type.value, name=name, parent_id=parent_id, permission_overwrites=perms, **options) async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| Creates a :class:`TextChannel` for the guild. Note that you need the :attr:`~Permissions.manage_channels` permission to create the channel. The ``overwrites`` parameter can be used to create a 'secret' channel upon creation. This parameter expects a :class:`dict` of overwrites with the target (either a :class:`Member` or a :class:`Role`) as the key and a :class:`PermissionOverwrite` as the value. .. note:: Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit` will be required to update the position of the channel in the channel list. Examples ---------- Creating a basic channel: .. code-block:: python3 channel = await guild.create_text_channel('cool-channel') Creating a "secret" channel: .. code-block:: python3 overwrites = { guild.default_role: discord.PermissionOverwrite(read_messages=False), guild.me: discord.PermissionOverwrite(read_messages=True) } channel = await guild.create_text_channel('secret', overwrites=overwrites) Parameters ----------- name: :class:`str` The channel's name. overwrites A :class:`dict` of target (either a role or a member) to :class:`PermissionOverwrite` to apply upon creation of a channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided. position: :class:`int` The position in the channel list. This is a number that starts at 0. e.g. the top channel is position 0. topic: Optional[:class:`str`] The new channel's topic. slowmode_delay: :class:`int` Specifies the slowmode rate limit for user in this channel, in seconds. The maximum value possible is `21600`. nsfw: :class:`bool` To mark the channel as NSFW or not. reason: Optional[:class:`str`] The reason for creating this channel. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`TextChannel` The channel that was just created. """ data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options) channel = TextChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel async def create_voice_channel(self, name, *, overwrites=None, category=None, reason=None, **options): """|coro| This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead, in addition to having the following new parameters. Parameters ----------- bitrate: :class:`int` The channel's preferred audio bitrate in bits per second. user_limit: :class:`int` The channel's limit for number of members that can be in a voice channel. rtc_region: Optional[:class:`VoiceRegion`] The region for the voice channel's voice communication. A value of ``None`` indicates automatic voice region detection. .. versionadded:: 1.7 Raises ------ Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`VoiceChannel` The channel that was just created. """ data = await self._create_channel(name, overwrites, ChannelType.voice, category, reason=reason, **options) channel = VoiceChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel async def create_stage_channel(self, name, *, topic=None, category=None, overwrites=None, reason=None, position=None): """|coro| This is similar to :meth:`create_text_channel` except makes a :class:`StageChannel` instead. .. note:: The ``slowmode_delay`` and ``nsfw`` parameters are not supported in this function. .. versionadded:: 1.7 Raises ------ Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`StageChannel` The channel that was just created. """ data = await self._create_channel(name, overwrites, ChannelType.stage_voice, category, reason=reason, position=position, topic=topic) channel = StageChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel async def create_category(self, name, *, overwrites=None, reason=None, position=None): """|coro| Same as :meth:`create_text_channel` except makes a :class:`CategoryChannel` instead. .. note:: The ``category`` parameter is not supported in this function since categories cannot have categories. Raises ------ Forbidden You do not have the proper permissions to create this channel. HTTPException Creating the channel failed. InvalidArgument The permission overwrite information is not in proper form. Returns ------- :class:`CategoryChannel` The channel that was just created. """ data = await self._create_channel(name, overwrites, ChannelType.category, reason=reason, position=position) channel = CategoryChannel(state=self._state, guild=self, data=data) # temporarily add to the cache self._channels[channel.id] = channel return channel create_category_channel = create_category async def leave(self): """|coro| Leaves the guild. .. note:: You cannot leave the guild that you own, you must delete it instead via :meth:`delete`. Raises -------- HTTPException Leaving the guild failed. """ await self._state.http.leave_guild(self.id) async def delete(self): """|coro| Deletes the guild. You must be the guild owner to delete the guild. Raises -------- HTTPException Deleting the guild failed. Forbidden You do not have permissions to delete the guild. """ await self._state.http.delete_guild(self.id) async def edit(self, *, reason=None, **fields): """|coro| Edits the guild. You must have the :attr:`~Permissions.manage_guild` permission to edit the guild. .. versionchanged:: 1.4 The `rules_channel` and `public_updates_channel` keyword-only parameters were added. Parameters ---------- name: :class:`str` The new name of the guild. description: :class:`str` The new description of the guild. This is only available to guilds that contain ``PUBLIC`` in :attr:`Guild.features`. icon: :class:`bytes` A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG is supported. GIF is only available to guilds that contain ``ANIMATED_ICON`` in :attr:`Guild.features`. Could be ``None`` to denote removal of the icon. banner: :class:`bytes` A :term:`py:bytes-like object` representing the banner. Could be ``None`` to denote removal of the banner. splash: :class:`bytes` A :term:`py:bytes-like object` representing the invite splash. Only PNG/JPEG supported. Could be ``None`` to denote removing the splash. This is only available to guilds that contain ``INVITE_SPLASH`` in :attr:`Guild.features`. region: :class:`VoiceRegion` The new region for the guild's voice communication. afk_channel: Optional[:class:`VoiceChannel`] The new channel that is the AFK channel. Could be ``None`` for no AFK channel. afk_timeout: :class:`int` The number of seconds until someone is moved to the AFK channel. owner: :class:`Member` The new owner of the guild to transfer ownership to. Note that you must be owner of the guild to do this. verification_level: :class:`VerificationLevel` The new verification level for the guild. default_notifications: :class:`NotificationLevel` The new default notification level for the guild. explicit_content_filter: :class:`ContentFilter` The new explicit content filter for the guild. vanity_code: :class:`str` The new vanity code for the guild. system_channel: Optional[:class:`TextChannel`] The new channel that is used for the system channel. Could be ``None`` for no system channel. system_channel_flags: :class:`SystemChannelFlags` The new system channel settings to use with the new system channel. preferred_locale: :class:`str` The new preferred locale for the guild. Used as the primary language in the guild. If set, this must be an ISO 639 code, e.g. ``en-US`` or ``ja`` or ``zh-CN``. rules_channel: Optional[:class:`TextChannel`] The new channel that is used for rules. This is only available to guilds that contain ``PUBLIC`` in :attr:`Guild.features`. Could be ``None`` for no rules channel. public_updates_channel: Optional[:class:`TextChannel`] The new channel that is used for public updates from Discord. This is only available to guilds that contain ``PUBLIC`` in :attr:`Guild.features`. Could be ``None`` for no public updates channel. reason: Optional[:class:`str`] The reason for editing this guild. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to edit the guild. HTTPException Editing the guild failed. InvalidArgument The image format passed in to ``icon`` is invalid. It must be PNG or JPG. This is also raised if you are not the owner of the guild and request an ownership transfer. """ http = self._state.http try: icon_bytes = fields['icon'] except KeyError: icon = self.icon else: if icon_bytes is not None: icon = utils._bytes_to_base64_data(icon_bytes) else: icon = None try: banner_bytes = fields['banner'] except KeyError: banner = self.banner else: if banner_bytes is not None: banner = utils._bytes_to_base64_data(banner_bytes) else: banner = None try: vanity_code = fields['vanity_code'] except KeyError: pass else: await http.change_vanity_code(self.id, vanity_code, reason=reason) try: splash_bytes = fields['splash'] except KeyError: splash = self.splash else: if splash_bytes is not None: splash = utils._bytes_to_base64_data(splash_bytes) else: splash = None fields['icon'] = icon fields['banner'] = banner fields['splash'] = splash default_message_notifications = fields.get('default_notifications', self.default_notifications) if not isinstance(default_message_notifications, NotificationLevel): raise InvalidArgument('default_notifications field must be of type NotificationLevel') fields['default_message_notifications'] = default_message_notifications.value try: afk_channel = fields.pop('afk_channel') except KeyError: pass else: if afk_channel is None: fields['afk_channel_id'] = afk_channel else: fields['afk_channel_id'] = afk_channel.id try: system_channel = fields.pop('system_channel') except KeyError: pass else: if system_channel is None: fields['system_channel_id'] = system_channel else: fields['system_channel_id'] = system_channel.id if 'owner' in fields: if self.owner_id != self._state.self_id: raise InvalidArgument('To transfer ownership you must be the owner of the guild.') fields['owner_id'] = fields['owner'].id if 'region' in fields: fields['region'] = str(fields['region']) level = fields.get('verification_level', self.verification_level) if not isinstance(level, VerificationLevel): raise InvalidArgument('verification_level field must be of type VerificationLevel') fields['verification_level'] = level.value explicit_content_filter = fields.get('explicit_content_filter', self.explicit_content_filter) if not isinstance(explicit_content_filter, ContentFilter): raise InvalidArgument('explicit_content_filter field must be of type ContentFilter') fields['explicit_content_filter'] = explicit_content_filter.value system_channel_flags = fields.get('system_channel_flags', self.system_channel_flags) if not isinstance(system_channel_flags, SystemChannelFlags): raise InvalidArgument('system_channel_flags field must be of type SystemChannelFlags') fields['system_channel_flags'] = system_channel_flags.value try: rules_channel = fields.pop('rules_channel') except KeyError: pass else: if rules_channel is None: fields['rules_channel_id'] = rules_channel else: fields['rules_channel_id'] = rules_channel.id try: public_updates_channel = fields.pop('public_updates_channel') except KeyError: pass else: if public_updates_channel is None: fields['public_updates_channel_id'] = public_updates_channel else: fields['public_updates_channel_id'] = public_updates_channel.id await http.edit_guild(self.id, reason=reason, **fields) async def fetch_channels(self): """|coro| Retrieves all :class:`abc.GuildChannel` that the guild has. .. note:: This method is an API call. For general usage, consider :attr:`channels` instead. .. versionadded:: 1.2 Raises ------- InvalidData An unknown channel type was received from Discord. HTTPException Retrieving the channels failed. Returns ------- List[:class:`abc.GuildChannel`] All channels in the guild. """ data = await self._state.http.get_all_guild_channels(self.id) def convert(d): factory, ch_type = _channel_factory(d['type']) if factory is None: raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(d)) channel = factory(guild=self, state=self._state, data=d) return channel return [convert(d) for d in data] def fetch_members(self, *, limit=1000, after=None): """Retrieves an :class:`.AsyncIterator` that enables receiving the guild's members. In order to use this, :meth:`Intents.members` must be enabled. .. note:: This method is an API call. For general usage, consider :attr:`members` instead. .. versionadded:: 1.3 All parameters are optional. Parameters ---------- limit: Optional[:class:`int`] The number of members to retrieve. Defaults to 1000. Pass ``None`` to fetch all members. Note that this is potentially slow. after: Optional[Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]] Retrieve members after this date or object. If a date is provided it must be a timezone-naive datetime representing UTC time. Raises ------ ClientException The members intent is not enabled. HTTPException Getting the members failed. Yields ------ :class:`.Member` The member with the member data parsed. Examples -------- Usage :: async for member in guild.fetch_members(limit=150): print(member.name) Flattening into a list :: members = await guild.fetch_members(limit=150).flatten() # members is now a list of Member... """ if not self._state._intents.members: raise ClientException('Intents.members must be enabled to use this.') return MemberIterator(self, limit=limit, after=after) async def fetch_member(self, member_id): """|coro| Retrieves a :class:`Member` from a guild ID, and a member ID. .. note:: This method is an API call. If you have :attr:`Intents.members` and member cache enabled, consider :meth:`get_member` instead. Parameters ----------- member_id: :class:`int` The member's ID to fetch from. Raises ------- Forbidden You do not have access to the guild. HTTPException Fetching the member failed. Returns -------- :class:`Member` The member from the member ID. """ data = await self._state.http.get_member(self.id, member_id) return Member(data=data, state=self._state, guild=self) async def fetch_ban(self, user): """|coro| Retrieves the :class:`BanEntry` for a user. You must have the :attr:`~Permissions.ban_members` permission to get this information. Parameters ----------- user: :class:`abc.Snowflake` The user to get ban information from. Raises ------ Forbidden You do not have proper permissions to get the information. NotFound This user is not banned. HTTPException An error occurred while fetching the information. Returns ------- :class:`BanEntry` The :class:`BanEntry` object for the specified user. """ data = await self._state.http.get_ban(user.id, self.id) return BanEntry( user=User(state=self._state, data=data['user']), reason=data['reason'] ) async def bans(self): """|coro| Retrieves all the users that are banned from the guild as a :class:`list` of :class:`BanEntry`. You must have the :attr:`~Permissions.ban_members` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns -------- List[:class:`BanEntry`] A list of :class:`BanEntry` objects. """ data = await self._state.http.get_bans(self.id) return [BanEntry(user=User(state=self._state, data=e['user']), reason=e['reason']) for e in data] async def prune_members(self, *, days, compute_prune_count=True, roles=None, reason=None): r"""|coro| Prunes the guild from its inactive members. The inactive members are denoted if they have not logged on in ``days`` number of days and they have no roles. You must have the :attr:`~Permissions.kick_members` permission to use this. To check how many members you would prune without actually pruning, see the :meth:`estimate_pruned_members` function. To prune members that have specific roles see the ``roles`` parameter. .. versionchanged:: 1.4 The ``roles`` keyword-only parameter was added. Parameters ----------- days: :class:`int` The number of days before counting as inactive. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. compute_prune_count: :class:`bool` Whether to compute the prune count. This defaults to ``True`` which makes it prone to timeouts in very large guilds. In order to prevent timeouts, you must set this to ``False``. If this is set to ``False``\, then this function will always return ``None``. roles: Optional[List[:class:`abc.Snowflake`]] A list of :class:`abc.Snowflake` that represent roles to include in the pruning process. If a member has a role that is not specified, they'll be excluded. Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while pruning members. InvalidArgument An integer was not passed for ``days``. Returns --------- Optional[:class:`int`] The number of members pruned. If ``compute_prune_count`` is ``False`` then this returns ``None``. """ if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) if roles: roles = [str(role.id) for role in roles] data = await self._state.http.prune_members(self.id, days, compute_prune_count=compute_prune_count, roles=roles, reason=reason) return data['pruned'] async def templates(self): """|coro| Gets the list of templates from this guild. Requires :attr:`~.Permissions.manage_guild` permissions. .. versionadded:: 1.7 Raises ------- Forbidden You don't have permissions to get the templates. Returns -------- List[:class:`Template`] The templates for this guild. """ from .template import Template data = await self._state.http.guild_templates(self.id) return [Template(data=d, state=self._state) for d in data] async def webhooks(self): """|coro| Gets the list of webhooks from this guild. Requires :attr:`~.Permissions.manage_webhooks` permissions. Raises ------- Forbidden You don't have permissions to get the webhooks. Returns -------- List[:class:`Webhook`] The webhooks for this guild. """ from .webhook import Webhook data = await self._state.http.guild_webhooks(self.id) return [Webhook.from_state(d, state=self._state) for d in data] async def estimate_pruned_members(self, *, days, roles=None): """|coro| Similar to :meth:`prune_members` except instead of actually pruning members, it returns how many members it would prune from the guild had it been called. Parameters ----------- days: :class:`int` The number of days before counting as inactive. roles: Optional[List[:class:`abc.Snowflake`]] A list of :class:`abc.Snowflake` that represent roles to include in the estimate. If a member has a role that is not specified, they'll be excluded. .. versionadded:: 1.7 Raises ------- Forbidden You do not have permissions to prune members. HTTPException An error occurred while fetching the prune members estimate. InvalidArgument An integer was not passed for ``days``. Returns --------- :class:`int` The number of members estimated to be pruned. """ if not isinstance(days, int): raise InvalidArgument('Expected int for ``days``, received {0.__class__.__name__} instead.'.format(days)) if roles: roles = [str(role.id) for role in roles] data = await self._state.http.estimate_pruned_members(self.id, days, roles) return data['pruned'] async def invites(self): """|coro| Returns a list of all active instant invites from the guild. You must have the :attr:`~Permissions.manage_guild` permission to get this information. Raises ------- Forbidden You do not have proper permissions to get the information. HTTPException An error occurred while fetching the information. Returns ------- List[:class:`Invite`] The list of invites that are currently active. """ data = await self._state.http.invites_from(self.id) result = [] for invite in data: channel = self.get_channel(int(invite['channel']['id'])) invite['channel'] = channel invite['guild'] = self result.append(Invite(state=self._state, data=invite)) return result async def create_template(self, *, name, description=None): """|coro| Creates a template for the guild. You must have the :attr:`~Permissions.manage_guild` permission to do this. .. versionadded:: 1.7 Parameters ----------- name: :class:`str` The name of the template. description: Optional[:class:`str`] The description of the template. """ from .template import Template payload = { 'name': name } if description: payload['description'] = description data = await self._state.http.create_template(self.id, payload) return Template(state=self._state, data=data) async def create_integration(self, *, type, id): """|coro| Attaches an integration to the guild. You must have the :attr:`~Permissions.manage_guild` permission to do this. .. versionadded:: 1.4 Parameters ----------- type: :class:`str` The integration type (e.g. Twitch). id: :class:`int` The integration ID. Raises ------- Forbidden You do not have permission to create the integration. HTTPException The account could not be found. """ await self._state.http.create_integration(self.id, type, id) async def integrations(self): """|coro| Returns a list of all integrations attached to the guild. You must have the :attr:`~Permissions.manage_guild` permission to do this. .. versionadded:: 1.4 Raises ------- Forbidden You do not have permission to create the integration. HTTPException Fetching the integrations failed. Returns -------- List[:class:`Integration`] The list of integrations that are attached to the guild. """ data = await self._state.http.get_all_integrations(self.id) return [Integration(guild=self, data=d) for d in data] async def fetch_emojis(self): r"""|coro| Retrieves all custom :class:`Emoji`\s from the guild. .. note:: This method is an API call. For general usage, consider :attr:`emojis` instead. Raises --------- HTTPException An error occurred fetching the emojis. Returns -------- List[:class:`Emoji`] The retrieved emojis. """ data = await self._state.http.get_all_custom_emojis(self.id) return [Emoji(guild=self, state=self._state, data=d) for d in data] async def fetch_emoji(self, emoji_id): """|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :class:`int` The emoji's ID. Raises --------- NotFound The emoji requested could not be found. HTTPException An error occurred fetching the emoji. Returns -------- :class:`Emoji` The retrieved emoji. """ data = await self._state.http.get_custom_emoji(self.id, emoji_id) return Emoji(guild=self, state=self._state, data=data) async def create_custom_emoji(self, *, name, image, roles=None, reason=None): r"""|coro| Creates a custom :class:`Emoji` for the guild. There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the ``MORE_EMOJI`` feature which extends the limit to 200. You must have the :attr:`~Permissions.manage_emojis` permission to do this. Parameters ----------- name: :class:`str` The emoji name. Must be at least 2 characters. image: :class:`bytes` The :term:`py:bytes-like object` representing the image data to use. Only JPG, PNG and GIF images are supported. roles: Optional[List[:class:`Role`]] A :class:`list` of :class:`Role`\s that can use this emoji. Leave empty to make it available to everyone. reason: Optional[:class:`str`] The reason for creating this emoji. Shows up on the audit log. Raises ------- Forbidden You are not allowed to create emojis. HTTPException An error occurred creating an emoji. Returns -------- :class:`Emoji` The created emoji. """ img = utils._bytes_to_base64_data(image) if roles: roles = [role.id for role in roles] data = await self._state.http.create_custom_emoji(self.id, name, img, roles=roles, reason=reason) return self._state.store_emoji(self, data) async def fetch_roles(self): """|coro| Retrieves all :class:`Role` that the guild has. .. note:: This method is an API call. For general usage, consider :attr:`roles` instead. .. versionadded:: 1.3 Raises ------- HTTPException Retrieving the roles failed. Returns ------- List[:class:`Role`] All roles in the guild. """ data = await self._state.http.get_roles(self.id) return [Role(guild=self, state=self._state, data=d) for d in data] async def create_role(self, *, reason=None, **fields): """|coro| Creates a :class:`Role` for the guild. All fields are optional. You must have the :attr:`~Permissions.manage_roles` permission to do this. .. versionchanged:: 1.6 Can now pass ``int`` to ``colour`` keyword-only parameter. Parameters ----------- name: :class:`str` The role name. Defaults to 'new role'. permissions: :class:`Permissions` The permissions to have. Defaults to no permissions. colour: Union[:class:`Colour`, :class:`int`] The colour for the role. Defaults to :meth:`Colour.default`. This is aliased to ``color`` as well. hoist: :class:`bool` Indicates if the role should be shown separately in the member list. Defaults to ``False``. mentionable: :class:`bool` Indicates if the role should be mentionable by others. Defaults to ``False``. reason: Optional[:class:`str`] The reason for creating this role. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to create the role. HTTPException Creating the role failed. InvalidArgument An invalid keyword argument was given. Returns -------- :class:`Role` The newly created role. """ try: perms = fields.pop('permissions') except KeyError: fields['permissions'] = 0 else: fields['permissions'] = perms.value try: colour = fields.pop('colour') except KeyError: colour = fields.get('color', Colour.default()) finally: if isinstance(colour, int): colour = Colour(value=colour) fields['color'] = colour.value valid_keys = ('name', 'permissions', 'color', 'hoist', 'mentionable') for key in fields: if key not in valid_keys: raise InvalidArgument('%r is not a valid field.' % key) data = await self._state.http.create_role(self.id, reason=reason, **fields) role = Role(guild=self, data=data, state=self._state) # TODO: add to cache return role async def edit_role_positions(self, positions, *, reason=None): """|coro| Bulk edits a list of :class:`Role` in the guild. You must have the :attr:`~Permissions.manage_roles` permission to do this. .. versionadded:: 1.4 Example: .. code-block:: python3 positions = { bots_role: 1, # penultimate role tester_role: 2, admin_role: 6 } await guild.edit_role_positions(positions=positions) Parameters ----------- positions A :class:`dict` of :class:`Role` to :class:`int` to change the positions of each given role. reason: Optional[:class:`str`] The reason for editing the role positions. Shows up on the audit log. Raises ------- Forbidden You do not have permissions to move the roles. HTTPException Moving the roles failed. InvalidArgument An invalid keyword argument was given. Returns -------- List[:class:`Role`] A list of all the roles in the guild. """ if not isinstance(positions, dict): raise InvalidArgument('positions parameter expects a dict.') role_positions = [] for role, position in positions.items(): payload = { 'id': role.id, 'position': position } role_positions.append(payload) data = await self._state.http.move_role_position(self.id, role_positions, reason=reason) roles = [] for d in data: role = Role(guild=self, data=d, state=self._state) roles.append(role) self._roles[role.id] = role return roles async def kick(self, user, *, reason=None): """|coro| Kicks a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.kick_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to kick from their guild. reason: Optional[:class:`str`] The reason the user got kicked. Raises ------- Forbidden You do not have the proper permissions to kick. HTTPException Kicking failed. """ await self._state.http.kick(user.id, self.id, reason=reason) async def ban(self, user, *, reason=None, delete_message_days=1): """|coro| Bans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to ban from their guild. delete_message_days: :class:`int` The number of days worth of messages to delete from the user in the guild. The minimum is 0 and the maximum is 7. reason: Optional[:class:`str`] The reason the user got banned. Raises ------- Forbidden You do not have the proper permissions to ban. HTTPException Banning failed. """ await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason) async def unban(self, user, *, reason=None): """|coro| Unbans a user from the guild. The user must meet the :class:`abc.Snowflake` abc. You must have the :attr:`~Permissions.ban_members` permission to do this. Parameters ----------- user: :class:`abc.Snowflake` The user to unban. reason: Optional[:class:`str`] The reason for doing this action. Shows up on the audit log. Raises ------- Forbidden You do not have the proper permissions to unban. HTTPException Unbanning failed. """ await self._state.http.unban(user.id, self.id, reason=reason) async def vanity_invite(self): """|coro| Returns the guild's special vanity invite. The guild must have ``VANITY_URL`` in :attr:`~Guild.features`. You must have the :attr:`~Permissions.manage_guild` permission to use this as well. Raises ------- Forbidden You do not have the proper permissions to get this. HTTPException Retrieving the vanity invite failed. Returns -------- :class:`Invite` The special vanity invite. """ # we start with { code: abc } payload = await self._state.http.get_vanity_code(self.id) # get the vanity URL channel since default channels aren't # reliable or a thing anymore data = await self._state.http.get_invite(payload['code']) payload['guild'] = self payload['channel'] = self.get_channel(int(data['channel']['id'])) payload['revoked'] = False payload['temporary'] = False payload['max_uses'] = 0 payload['max_age'] = 0 return Invite(state=self._state, data=payload) @utils.deprecated() def ack(self): """|coro| Marks every message in this guild as read. The user must not be a bot user. .. deprecated:: 1.7 Raises ------- HTTPException Acking failed. ClientException You must not be a bot user. """ state = self._state if state.is_bot: raise ClientException('Must not be a bot account to ack messages.') return state.http.ack_guild(self.id) def audit_logs(self, *, limit=100, before=None, after=None, oldest_first=None, user=None, action=None): """Returns an :class:`AsyncIterator` that enables receiving the guild's audit logs. You must have the :attr:`~Permissions.view_audit_log` permission to use this. Examples ---------- Getting the first 100 entries: :: async for entry in guild.audit_logs(limit=100): print('{0.user} did {0.action} to {0.target}'.format(entry)) Getting entries for a specific action: :: async for entry in guild.audit_logs(action=discord.AuditLogAction.ban): print('{0.user} banned {0.target}'.format(entry)) Getting entries made by a specific user: :: entries = await guild.audit_logs(limit=None, user=guild.me).flatten() await channel.send('I made {} moderation actions.'.format(len(entries))) Parameters ----------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. before: Union[:class:`abc.Snowflake`, :class:`datetime.datetime`] Retrieve entries before this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. after: Union[:class:`abc.Snowflake`, :class:`datetime.datetime`] Retrieve entries after this date or entry. If a date is provided it must be a timezone-naive datetime representing UTC time. oldest_first: :class:`bool` If set to ``True``, return entries in oldest->newest order. Defaults to ``True`` if ``after`` is specified, otherwise ``False``. user: :class:`abc.Snowflake` The moderator to filter entries from. action: :class:`AuditLogAction` The action to filter with. Raises ------- Forbidden You are not allowed to fetch audit logs HTTPException An error occurred while fetching the audit logs. Yields -------- :class:`AuditLogEntry` The audit log entry. """ if user: user = user.id if action: action = action.value return AuditLogIterator(self, before=before, after=after, limit=limit, oldest_first=oldest_first, user_id=user, action_type=action) async def widget(self): """|coro| Returns the widget of the guild. .. note:: The guild must have the widget enabled to get this information. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retrieving the widget failed. Returns -------- :class:`Widget` The guild's widget. """ data = await self._state.http.get_widget(self.id) return Widget(state=self._state, data=data) async def chunk(self, *, cache=True): """|coro| Requests all members that belong to this guild. In order to use this, :meth:`Intents.members` must be enabled. This is a websocket operation and can be slow. .. versionadded:: 1.5 Parameters ----------- cache: :class:`bool` Whether to cache the members as well. Raises ------- ClientException The members intent is not enabled. """ if not self._state._intents.members: raise ClientException('Intents.members must be enabled to use this.') if not self._state.is_guild_evicted(self): return await self._state.chunk_guild(self, cache=cache) async def query_members(self, query=None, *, limit=5, user_ids=None, presences=False, cache=True): """|coro| Request members that belong to this guild whose username starts with the query given. This is a websocket operation and can be slow. .. versionadded:: 1.3 Parameters ----------- query: Optional[:class:`str`] The string that the username's start with. limit: :class:`int` The maximum number of members to send back. This must be a number between 5 and 100. presences: :class:`bool` Whether to request for presences to be provided. This defaults to ``False``. .. versionadded:: 1.6 cache: :class:`bool` Whether to cache the members internally. This makes operations such as :meth:`get_member` work for those that matched. user_ids: Optional[List[:class:`int`]] List of user IDs to search for. If the user ID is not in the guild then it won't be returned. .. versionadded:: 1.4 Raises ------- asyncio.TimeoutError The query timed out waiting for the members. ValueError Invalid parameters were passed to the function ClientException The presences intent is not enabled. Returns -------- List[:class:`Member`] The list of members that have matched the query. """ if presences and not self._state._intents.presences: raise ClientException('Intents.presences must be enabled to use this.') if query is None: if query == '': raise ValueError('Cannot pass empty query string.') if user_ids is None: raise ValueError('Must pass either query or user_ids') if user_ids is not None and query is not None: raise ValueError('Cannot pass both query and user_ids') if user_ids is not None and not user_ids: raise ValueError('user_ids must contain at least 1 value') limit = min(100, limit or 5) return await self._state.query_members(self, query=query, limit=limit, user_ids=user_ids, presences=presences, cache=cache) async def change_voice_state(self, *, channel, self_mute=False, self_deaf=False): """|coro| Changes client's voice state in the guild. .. versionadded:: 1.4 Parameters ----------- channel: Optional[:class:`VoiceChannel`] Channel the client wants to join. Use ``None`` to disconnect. self_mute: :class:`bool` Indicates if the client should be self-muted. self_deaf: :class:`bool` Indicates if the client should be self-deafened. """ ws = self._state._get_websocket(self.id) channel_id = channel.id if channel else None await ws.voice_state(self.id, channel_id, self_mute, self_deaf)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/guild.py
guild.py
class DiscordException(Exception): """Base exception class for discord.py Ideally speaking, this could be caught to handle any exceptions thrown from this library. """ pass class ClientException(DiscordException): """Exception that's thrown when an operation in the :class:`Client` fails. These are usually for exceptions that happened due to user input. """ pass class NoMoreItems(DiscordException): """Exception that is thrown when an async iteration operation has no more items.""" pass class GatewayNotFound(DiscordException): """An exception that is usually thrown when the gateway hub for the :class:`Client` websocket is not found.""" def __init__(self): message = 'The gateway to connect to discord was not found.' super(GatewayNotFound, self).__init__(message) def flatten_error_dict(d, key=''): items = [] for k, v in d.items(): new_key = key + '.' + k if key else k if isinstance(v, dict): try: _errors = v['_errors'] except KeyError: items.extend(flatten_error_dict(v, new_key).items()) else: items.append((new_key, ' '.join(x.get('message', '') for x in _errors))) else: items.append((new_key, v)) return dict(items) class HTTPException(DiscordException): """Exception that's thrown when an HTTP request operation fails. Attributes ------------ response: :class:`aiohttp.ClientResponse` The response of the failed HTTP request. This is an instance of :class:`aiohttp.ClientResponse`. In some cases this could also be a :class:`requests.Response`. text: :class:`str` The text of the error. Could be an empty string. status: :class:`int` The status code of the HTTP request. code: :class:`int` The Discord specific error code for the failure. """ def __init__(self, response, message): self.response = response self.status = response.status if isinstance(message, dict): self.code = message.get('code', 0) base = message.get('message', '') errors = message.get('errors') if errors: errors = flatten_error_dict(errors) helpful = '\n'.join('In %s: %s' % t for t in errors.items()) self.text = base + '\n' + helpful else: self.text = base else: self.text = message self.code = 0 fmt = '{0.status} {0.reason} (error code: {1})' if len(self.text): fmt += ': {2}' super().__init__(fmt.format(self.response, self.code, self.text)) class Forbidden(HTTPException): """Exception that's thrown for when status code 403 occurs. Subclass of :exc:`HTTPException` """ pass class NotFound(HTTPException): """Exception that's thrown for when status code 404 occurs. Subclass of :exc:`HTTPException` """ pass class DiscordServerError(HTTPException): """Exception that's thrown for when a 500 range status code occurs. Subclass of :exc:`HTTPException`. .. versionadded:: 1.5 """ pass class InvalidData(ClientException): """Exception that's raised when the library encounters unknown or invalid data from Discord. """ pass class InvalidArgument(ClientException): """Exception that's thrown when an argument to a function is invalid some way (e.g. wrong value or wrong type). This could be considered the analogous of ``ValueError`` and ``TypeError`` except inherited from :exc:`ClientException` and thus :exc:`DiscordException`. """ pass class LoginFailure(ClientException): """Exception that's thrown when the :meth:`Client.login` function fails to log you in from improper credentials or some other misc. failure. """ pass class ConnectionClosed(ClientException): """Exception that's thrown when the gateway connection is closed for reasons that could not be handled internally. Attributes ----------- code: :class:`int` The close code of the websocket. reason: :class:`str` The reason provided for the closure. shard_id: Optional[:class:`int`] The shard ID that got closed if applicable. """ def __init__(self, socket, *, shard_id, code=None): # This exception is just the same exception except # reconfigured to subclass ClientException for users self.code = code or socket.close_code # aiohttp doesn't seem to consistently provide close reason self.reason = '' self.shard_id = shard_id super().__init__('Shard ID %s WebSocket closed with %s' % (self.shard_id, self.code)) class PrivilegedIntentsRequired(ClientException): """Exception that's thrown when the gateway is requesting privileged intents but they're not ticked in the developer page yet. Go to https://discord.com/developers/applications/ and enable the intents that are required. Currently these are as follows: - :attr:`Intents.members` - :attr:`Intents.presences` Attributes ----------- shard_id: Optional[:class:`int`] The shard ID that got closed if applicable. """ def __init__(self, shard_id): self.shard_id = shard_id msg = 'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the ' \ 'developer portal. It is recommended to go to https://discord.com/developers/applications/ ' \ 'and explicitly enable the privileged intents within your application\'s page. If this is not ' \ 'possible, then consider disabling the privileged intents instead.' super().__init__(msg % shard_id)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/errors.py
errors.py
import types from collections import namedtuple __all__ = ( 'Enum', 'ChannelType', 'MessageType', 'VoiceRegion', 'SpeakingState', 'VerificationLevel', 'ContentFilter', 'Status', 'DefaultAvatar', 'RelationshipType', 'AuditLogAction', 'AuditLogActionCategory', 'UserFlags', 'ActivityType', 'HypeSquadHouse', 'NotificationLevel', 'PremiumType', 'UserContentFilter', 'FriendFlags', 'TeamMembershipState', 'Theme', 'WebhookType', 'ExpireBehaviour', 'ExpireBehavior', 'StickerType', ) def _create_value_cls(name): cls = namedtuple('_EnumValue_' + name, 'name value') cls.__repr__ = lambda self: '<%s.%s: %r>' % (name, self.name, self.value) cls.__str__ = lambda self: '%s.%s' % (name, self.name) return cls def _is_descriptor(obj): return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__') class EnumMeta(type): def __new__(cls, name, bases, attrs): value_mapping = {} member_mapping = {} member_names = [] value_cls = _create_value_cls(name) for key, value in list(attrs.items()): is_descriptor = _is_descriptor(value) if key[0] == '_' and not is_descriptor: continue # Special case classmethod to just pass through if isinstance(value, classmethod): continue if is_descriptor: setattr(value_cls, key, value) del attrs[key] continue try: new_value = value_mapping[value] except KeyError: new_value = value_cls(name=key, value=value) value_mapping[value] = new_value member_names.append(key) member_mapping[key] = new_value attrs[key] = new_value attrs['_enum_value_map_'] = value_mapping attrs['_enum_member_map_'] = member_mapping attrs['_enum_member_names_'] = member_names actual_cls = super().__new__(cls, name, bases, attrs) value_cls._actual_enum_cls_ = actual_cls return actual_cls def __iter__(cls): return (cls._enum_member_map_[name] for name in cls._enum_member_names_) def __reversed__(cls): return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_)) def __len__(cls): return len(cls._enum_member_names_) def __repr__(cls): return '<enum %r>' % cls.__name__ @property def __members__(cls): return types.MappingProxyType(cls._enum_member_map_) def __call__(cls, value): try: return cls._enum_value_map_[value] except (KeyError, TypeError): raise ValueError("%r is not a valid %s" % (value, cls.__name__)) def __getitem__(cls, key): return cls._enum_member_map_[key] def __setattr__(cls, name, value): raise TypeError('Enums are immutable.') def __delattr__(cls, attr): raise TypeError('Enums are immutable') def __instancecheck__(self, instance): # isinstance(x, Y) # -> __instancecheck__(Y, x) try: return instance._actual_enum_cls_ is self except AttributeError: return False class Enum(metaclass=EnumMeta): @classmethod def try_value(cls, value): try: return cls._enum_value_map_[value] except (KeyError, TypeError): return value class ChannelType(Enum): text = 0 private = 1 voice = 2 group = 3 category = 4 news = 5 store = 6 stage_voice = 13 def __str__(self): return self.name class MessageType(Enum): default = 0 recipient_add = 1 recipient_remove = 2 call = 3 channel_name_change = 4 channel_icon_change = 5 pins_add = 6 new_member = 7 premium_guild_subscription = 8 premium_guild_tier_1 = 9 premium_guild_tier_2 = 10 premium_guild_tier_3 = 11 channel_follow_add = 12 guild_stream = 13 guild_discovery_disqualified = 14 guild_discovery_requalified = 15 guild_discovery_grace_period_initial_warning = 16 guild_discovery_grace_period_final_warning = 17 class VoiceRegion(Enum): us_west = 'us-west' us_east = 'us-east' us_south = 'us-south' us_central = 'us-central' eu_west = 'eu-west' eu_central = 'eu-central' singapore = 'singapore' london = 'london' sydney = 'sydney' amsterdam = 'amsterdam' frankfurt = 'frankfurt' brazil = 'brazil' hongkong = 'hongkong' russia = 'russia' japan = 'japan' southafrica = 'southafrica' south_korea = 'south-korea' india = 'india' europe = 'europe' dubai = 'dubai' vip_us_east = 'vip-us-east' vip_us_west = 'vip-us-west' vip_amsterdam = 'vip-amsterdam' def __str__(self): return self.value class SpeakingState(Enum): none = 0 voice = 1 soundshare = 2 priority = 4 def __str__(self): return self.name def __int__(self): return self.value class VerificationLevel(Enum): none = 0 low = 1 medium = 2 high = 3 table_flip = 3 extreme = 4 double_table_flip = 4 very_high = 4 def __str__(self): return self.name class ContentFilter(Enum): disabled = 0 no_role = 1 all_members = 2 def __str__(self): return self.name class UserContentFilter(Enum): disabled = 0 friends = 1 all_messages = 2 class FriendFlags(Enum): noone = 0 mutual_guilds = 1 mutual_friends = 2 guild_and_friends = 3 everyone = 4 class Theme(Enum): light = 'light' dark = 'dark' class Status(Enum): online = 'online' offline = 'offline' idle = 'idle' dnd = 'dnd' do_not_disturb = 'dnd' invisible = 'invisible' def __str__(self): return self.value class DefaultAvatar(Enum): blurple = 0 grey = 1 gray = 1 green = 2 orange = 3 red = 4 def __str__(self): return self.name class RelationshipType(Enum): friend = 1 blocked = 2 incoming_request = 3 outgoing_request = 4 class NotificationLevel(Enum): all_messages = 0 only_mentions = 1 class AuditLogActionCategory(Enum): create = 1 delete = 2 update = 3 class AuditLogAction(Enum): guild_update = 1 channel_create = 10 channel_update = 11 channel_delete = 12 overwrite_create = 13 overwrite_update = 14 overwrite_delete = 15 kick = 20 member_prune = 21 ban = 22 unban = 23 member_update = 24 member_role_update = 25 member_move = 26 member_disconnect = 27 bot_add = 28 role_create = 30 role_update = 31 role_delete = 32 invite_create = 40 invite_update = 41 invite_delete = 42 webhook_create = 50 webhook_update = 51 webhook_delete = 52 emoji_create = 60 emoji_update = 61 emoji_delete = 62 message_delete = 72 message_bulk_delete = 73 message_pin = 74 message_unpin = 75 integration_create = 80 integration_update = 81 integration_delete = 82 @property def category(self): lookup = { AuditLogAction.guild_update: AuditLogActionCategory.update, AuditLogAction.channel_create: AuditLogActionCategory.create, AuditLogAction.channel_update: AuditLogActionCategory.update, AuditLogAction.channel_delete: AuditLogActionCategory.delete, AuditLogAction.overwrite_create: AuditLogActionCategory.create, AuditLogAction.overwrite_update: AuditLogActionCategory.update, AuditLogAction.overwrite_delete: AuditLogActionCategory.delete, AuditLogAction.kick: None, AuditLogAction.member_prune: None, AuditLogAction.ban: None, AuditLogAction.unban: None, AuditLogAction.member_update: AuditLogActionCategory.update, AuditLogAction.member_role_update: AuditLogActionCategory.update, AuditLogAction.member_move: None, AuditLogAction.member_disconnect: None, AuditLogAction.bot_add: None, AuditLogAction.role_create: AuditLogActionCategory.create, AuditLogAction.role_update: AuditLogActionCategory.update, AuditLogAction.role_delete: AuditLogActionCategory.delete, AuditLogAction.invite_create: AuditLogActionCategory.create, AuditLogAction.invite_update: AuditLogActionCategory.update, AuditLogAction.invite_delete: AuditLogActionCategory.delete, AuditLogAction.webhook_create: AuditLogActionCategory.create, AuditLogAction.webhook_update: AuditLogActionCategory.update, AuditLogAction.webhook_delete: AuditLogActionCategory.delete, AuditLogAction.emoji_create: AuditLogActionCategory.create, AuditLogAction.emoji_update: AuditLogActionCategory.update, AuditLogAction.emoji_delete: AuditLogActionCategory.delete, AuditLogAction.message_delete: AuditLogActionCategory.delete, AuditLogAction.message_bulk_delete: AuditLogActionCategory.delete, AuditLogAction.message_pin: None, AuditLogAction.message_unpin: None, AuditLogAction.integration_create: AuditLogActionCategory.create, AuditLogAction.integration_update: AuditLogActionCategory.update, AuditLogAction.integration_delete: AuditLogActionCategory.delete, } return lookup[self] @property def target_type(self): v = self.value if v == -1: return 'all' elif v < 10: return 'guild' elif v < 20: return 'channel' elif v < 30: return 'user' elif v < 40: return 'role' elif v < 50: return 'invite' elif v < 60: return 'webhook' elif v < 70: return 'emoji' elif v == 73: return 'channel' elif v < 80: return 'message' elif v < 90: return 'integration' class UserFlags(Enum): staff = 1 partner = 2 hypesquad = 4 bug_hunter = 8 mfa_sms = 16 premium_promo_dismissed = 32 hypesquad_bravery = 64 hypesquad_brilliance = 128 hypesquad_balance = 256 early_supporter = 512 team_user = 1024 system = 4096 has_unread_urgent_messages = 8192 bug_hunter_level_2 = 16384 verified_bot = 65536 verified_bot_developer = 131072 class ActivityType(Enum): unknown = -1 playing = 0 streaming = 1 listening = 2 watching = 3 custom = 4 competing = 5 def __int__(self): return self.value class HypeSquadHouse(Enum): bravery = 1 brilliance = 2 balance = 3 class PremiumType(Enum): nitro_classic = 1 nitro = 2 class TeamMembershipState(Enum): invited = 1 accepted = 2 class WebhookType(Enum): incoming = 1 channel_follower = 2 class ExpireBehaviour(Enum): remove_role = 0 kick = 1 ExpireBehavior = ExpireBehaviour class StickerType(Enum): png = 1 apng = 2 lottie = 3 def try_enum(cls, val): """A function that tries to turn the value into enum ``cls``. If it fails it returns the value instead. """ try: return cls._enum_value_map_[val] except (KeyError, TypeError, AttributeError): return val
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/enums.py
enums.py
class _RawReprMixin: def __repr__(self): value = ' '.join('%s=%r' % (attr, getattr(self, attr)) for attr in self.__slots__) return '<%s %s>' % (self.__class__.__name__, value) class RawMessageDeleteEvent(_RawReprMixin): """Represents the event payload for a :func:`on_raw_message_delete` event. Attributes ------------ channel_id: :class:`int` The channel ID where the deletion took place. guild_id: Optional[:class:`int`] The guild ID where the deletion took place, if applicable. message_id: :class:`int` The message ID that got deleted. cached_message: Optional[:class:`Message`] The cached message, if found in the internal message cache. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'cached_message') def __init__(self, data): self.message_id = int(data['id']) self.channel_id = int(data['channel_id']) self.cached_message = None try: self.guild_id = int(data['guild_id']) except KeyError: self.guild_id = None class RawBulkMessageDeleteEvent(_RawReprMixin): """Represents the event payload for a :func:`on_raw_bulk_message_delete` event. Attributes ----------- message_ids: Set[:class:`int`] A :class:`set` of the message IDs that were deleted. channel_id: :class:`int` The channel ID where the message got deleted. guild_id: Optional[:class:`int`] The guild ID where the message got deleted, if applicable. cached_messages: List[:class:`Message`] The cached messages, if found in the internal message cache. """ __slots__ = ('message_ids', 'channel_id', 'guild_id', 'cached_messages') def __init__(self, data): self.message_ids = {int(x) for x in data.get('ids', [])} self.channel_id = int(data['channel_id']) self.cached_messages = [] try: self.guild_id = int(data['guild_id']) except KeyError: self.guild_id = None class RawMessageUpdateEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_message_edit` event. Attributes ----------- message_id: :class:`int` The message ID that got updated. channel_id: :class:`int` The channel ID where the update took place. .. versionadded:: 1.3 guild_id: Optional[:class:`int`] The guild ID where the message got updated, if applicable. .. versionadded:: 1.7 data: :class:`dict` The raw data given by the `gateway <https://discord.com/developers/docs/topics/gateway#message-update>`_ cached_message: Optional[:class:`Message`] The cached message, if found in the internal message cache. Represents the message before it is modified by the data in :attr:`RawMessageUpdateEvent.data`. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'data', 'cached_message') def __init__(self, data): self.message_id = int(data['id']) self.channel_id = int(data['channel_id']) self.data = data self.cached_message = None try: self.guild_id = int(data['guild_id']) except KeyError: self.guild_id = None class RawReactionActionEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_add` or :func:`on_raw_reaction_remove` event. Attributes ----------- message_id: :class:`int` The message ID that got or lost a reaction. user_id: :class:`int` The user ID who added the reaction or whose reaction was removed. channel_id: :class:`int` The channel ID where the reaction got added or removed. guild_id: Optional[:class:`int`] The guild ID where the reaction got added or removed, if applicable. emoji: :class:`PartialEmoji` The custom or unicode emoji being used. member: Optional[:class:`Member`] The member who added the reaction. Only available if `event_type` is `REACTION_ADD` and the reaction is inside a guild. .. versionadded:: 1.3 event_type: :class:`str` The event type that triggered this action. Can be ``REACTION_ADD`` for reaction addition or ``REACTION_REMOVE`` for reaction removal. .. versionadded:: 1.3 """ __slots__ = ('message_id', 'user_id', 'channel_id', 'guild_id', 'emoji', 'event_type', 'member') def __init__(self, data, emoji, event_type): self.message_id = int(data['message_id']) self.channel_id = int(data['channel_id']) self.user_id = int(data['user_id']) self.emoji = emoji self.event_type = event_type self.member = None try: self.guild_id = int(data['guild_id']) except KeyError: self.guild_id = None class RawReactionClearEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_clear` event. Attributes ----------- message_id: :class:`int` The message ID that got its reactions cleared. channel_id: :class:`int` The channel ID where the reactions got cleared. guild_id: Optional[:class:`int`] The guild ID where the reactions got cleared. """ __slots__ = ('message_id', 'channel_id', 'guild_id') def __init__(self, data): self.message_id = int(data['message_id']) self.channel_id = int(data['channel_id']) try: self.guild_id = int(data['guild_id']) except KeyError: self.guild_id = None class RawReactionClearEmojiEvent(_RawReprMixin): """Represents the payload for a :func:`on_raw_reaction_clear_emoji` event. .. versionadded:: 1.3 Attributes ----------- message_id: :class:`int` The message ID that got its reactions cleared. channel_id: :class:`int` The channel ID where the reactions got cleared. guild_id: Optional[:class:`int`] The guild ID where the reactions got cleared. emoji: :class:`PartialEmoji` The custom or unicode emoji being removed. """ __slots__ = ('message_id', 'channel_id', 'guild_id', 'emoji') def __init__(self, data, emoji): self.emoji = emoji self.message_id = int(data['message_id']) self.channel_id = int(data['channel_id']) try: self.guild_id = int(data['guild_id']) except KeyError: self.guild_id = None
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/raw_models.py
raw_models.py
import array import asyncio import collections.abc import unicodedata from base64 import b64encode from bisect import bisect_left import datetime import functools from inspect import isawaitable as _isawaitable, signature as _signature from operator import attrgetter import json import re import warnings from .errors import InvalidArgument DISCORD_EPOCH = 1420070400000 MAX_ASYNCIO_SECONDS = 3456000 class cached_property: def __init__(self, function): self.function = function self.__doc__ = getattr(function, '__doc__') def __get__(self, instance, owner): if instance is None: return self value = self.function(instance) setattr(instance, self.function.__name__, value) return value class CachedSlotProperty: def __init__(self, name, function): self.name = name self.function = function self.__doc__ = getattr(function, '__doc__') def __get__(self, instance, owner): if instance is None: return self try: return getattr(instance, self.name) except AttributeError: value = self.function(instance) setattr(instance, self.name, value) return value def cached_slot_property(name): def decorator(func): return CachedSlotProperty(name, func) return decorator class SequenceProxy(collections.abc.Sequence): """Read-only proxy of a Sequence.""" def __init__(self, proxied): self.__proxied = proxied def __getitem__(self, idx): return self.__proxied[idx] def __len__(self): return len(self.__proxied) def __contains__(self, item): return item in self.__proxied def __iter__(self): return iter(self.__proxied) def __reversed__(self): return reversed(self.__proxied) def index(self, value, *args, **kwargs): return self.__proxied.index(value, *args, **kwargs) def count(self, value): return self.__proxied.count(value) def parse_time(timestamp): if timestamp: return datetime.datetime(*map(int, re.split(r'[^\d]', timestamp.replace('+00:00', '')))) return None def copy_doc(original): def decorator(overriden): overriden.__doc__ = original.__doc__ overriden.__signature__ = _signature(original) return overriden return decorator def deprecated(instead=None): def actual_decorator(func): @functools.wraps(func) def decorated(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off filter if instead: fmt = "{0.__name__} is deprecated, use {1} instead." else: fmt = '{0.__name__} is deprecated.' warnings.warn(fmt.format(func, instead), stacklevel=3, category=DeprecationWarning) warnings.simplefilter('default', DeprecationWarning) # reset filter return func(*args, **kwargs) return decorated return actual_decorator def oauth_url(client_id, permissions=None, guild=None, redirect_uri=None, scopes=None): """A helper function that returns the OAuth2 URL for inviting the bot into guilds. Parameters ----------- client_id: :class:`str` The client ID for your bot. permissions: :class:`~discord.Permissions` The permissions you're requesting. If not given then you won't be requesting any permissions. guild: :class:`~discord.Guild` The guild to pre-select in the authorization screen, if available. redirect_uri: :class:`str` An optional valid redirect URI. scopes: Iterable[:class:`str`] An optional valid list of scopes. Defaults to ``('bot',)``. .. versionadded:: 1.7 Returns -------- :class:`str` The OAuth2 URL for inviting the bot into guilds. """ url = 'https://discord.com/oauth2/authorize?client_id={}'.format(client_id) url = url + '&scope=' + '+'.join(scopes or ('bot',)) if permissions is not None: url = url + '&permissions=' + str(permissions.value) if guild is not None: url = url + "&guild_id=" + str(guild.id) if redirect_uri is not None: from urllib.parse import urlencode url = url + "&response_type=code&" + urlencode({'redirect_uri': redirect_uri}) return url def snowflake_time(id): """ Parameters ----------- id: :class:`int` The snowflake ID. Returns -------- :class:`datetime.datetime` The creation date in UTC of a Discord snowflake ID.""" return datetime.datetime.utcfromtimestamp(((id >> 22) + DISCORD_EPOCH) / 1000) def time_snowflake(datetime_obj, high=False): """Returns a numeric snowflake pretending to be created at the given date. When using as the lower end of a range, use ``time_snowflake(high=False) - 1`` to be inclusive, ``high=True`` to be exclusive When using as the higher end of a range, use ``time_snowflake(high=True)`` + 1 to be inclusive, ``high=False`` to be exclusive Parameters ----------- datetime_obj: :class:`datetime.datetime` A timezone-naive datetime object representing UTC time. high: :class:`bool` Whether or not to set the lower 22 bit to high or low. """ unix_seconds = (datetime_obj - type(datetime_obj)(1970, 1, 1)).total_seconds() discord_millis = int(unix_seconds * 1000 - DISCORD_EPOCH) return (discord_millis << 22) + (2**22-1 if high else 0) def find(predicate, seq): """A helper to return the first element found in the sequence that meets the predicate. For example: :: member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members) would find the first :class:`~discord.Member` whose name is 'Mighty' and return it. If an entry is not found, then ``None`` is returned. This is different from :func:`py:filter` due to the fact it stops the moment it finds a valid entry. Parameters ----------- predicate A function that returns a boolean-like result. seq: iterable The iterable to search through. """ for element in seq: if predicate(element): return element return None def get(iterable, **attrs): r"""A helper that returns the first element in the iterable that meets all the traits passed in ``attrs``. This is an alternative for :func:`~discord.utils.find`. When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them. To have a nested attribute search (i.e. search by ``x.y``) then pass in ``x__y`` as the keyword argument. If nothing is found that matches the attributes passed, then ``None`` is returned. Examples --------- Basic usage: .. code-block:: python3 member = discord.utils.get(message.guild.members, name='Foo') Multiple attribute matching: .. code-block:: python3 channel = discord.utils.get(guild.voice_channels, name='Foo', bitrate=64000) Nested attribute matching: .. code-block:: python3 channel = discord.utils.get(client.get_all_channels(), guild__name='Cool', name='general') Parameters ----------- iterable An iterable to search through. \*\*attrs Keyword arguments that denote attributes to search with. """ # global -> local _all = all attrget = attrgetter # Special case the single element call if len(attrs) == 1: k, v = attrs.popitem() pred = attrget(k.replace('__', '.')) for elem in iterable: if pred(elem) == v: return elem return None converted = [ (attrget(attr.replace('__', '.')), value) for attr, value in attrs.items() ] for elem in iterable: if _all(pred(elem) == value for pred, value in converted): return elem return None def _unique(iterable): seen = set() adder = seen.add return [x for x in iterable if not (x in seen or adder(x))] def _get_as_snowflake(data, key): try: value = data[key] except KeyError: return None else: return value and int(value) def _get_mime_type_for_image(data): if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'): return 'image/png' elif data[0:3] == b'\xff\xd8\xff' or data[6:10] in (b'JFIF', b'Exif'): return 'image/jpeg' elif data.startswith((b'\x47\x49\x46\x38\x37\x61', b'\x47\x49\x46\x38\x39\x61')): return 'image/gif' elif data.startswith(b'RIFF') and data[8:12] == b'WEBP': return 'image/webp' else: raise InvalidArgument('Unsupported image type given') def _bytes_to_base64_data(data): fmt = 'data:{mime};base64,{data}' mime = _get_mime_type_for_image(data) b64 = b64encode(data).decode('ascii') return fmt.format(mime=mime, data=b64) def to_json(obj): return json.dumps(obj, separators=(',', ':'), ensure_ascii=True) def _parse_ratelimit_header(request, *, use_clock=False): reset_after = request.headers.get('X-Ratelimit-Reset-After') if use_clock or not reset_after: utc = datetime.timezone.utc now = datetime.datetime.now(utc) reset = datetime.datetime.fromtimestamp(float(request.headers['X-Ratelimit-Reset']), utc) return (reset - now).total_seconds() else: return float(reset_after) async def maybe_coroutine(f, *args, **kwargs): value = f(*args, **kwargs) if _isawaitable(value): return await value else: return value async def async_all(gen, *, check=_isawaitable): for elem in gen: if check(elem): elem = await elem if not elem: return False return True async def sane_wait_for(futures, *, timeout): ensured = [ asyncio.ensure_future(fut) for fut in futures ] done, pending = await asyncio.wait(ensured, timeout=timeout, return_when=asyncio.ALL_COMPLETED) if len(pending) != 0: raise asyncio.TimeoutError() return done async def sleep_until(when, result=None): """|coro| Sleep until a specified time. If the time supplied is in the past this function will yield instantly. .. versionadded:: 1.3 Parameters ----------- when: :class:`datetime.datetime` The timestamp in which to sleep until. If the datetime is naive then it is assumed to be in UTC. result: Any If provided is returned to the caller when the coroutine completes. """ if when.tzinfo is None: when = when.replace(tzinfo=datetime.timezone.utc) now = datetime.datetime.now(datetime.timezone.utc) delta = (when - now).total_seconds() while delta > MAX_ASYNCIO_SECONDS: await asyncio.sleep(MAX_ASYNCIO_SECONDS) delta -= MAX_ASYNCIO_SECONDS return await asyncio.sleep(max(delta, 0), result) def valid_icon_size(size): """Icons must be power of 2 within [16, 4096].""" return not size & (size - 1) and size in range(16, 4097) class SnowflakeList(array.array): """Internal data storage class to efficiently store a list of snowflakes. This should have the following characteristics: - Low memory usage - O(n) iteration (obviously) - O(n log n) initial creation if data is unsorted - O(log n) search and indexing - O(n) insertion """ __slots__ = () def __new__(cls, data, *, is_sorted=False): return array.array.__new__(cls, 'Q', data if is_sorted else sorted(data)) def add(self, element): i = bisect_left(self, element) self.insert(i, element) def get(self, element): i = bisect_left(self, element) return self[i] if i != len(self) and self[i] == element else None def has(self, element): i = bisect_left(self, element) return i != len(self) and self[i] == element _IS_ASCII = re.compile(r'^[\x00-\x7f]+$') def _string_width(string, *, _IS_ASCII=_IS_ASCII): """Returns string's width.""" match = _IS_ASCII.match(string) if match: return match.endpos UNICODE_WIDE_CHAR_TYPE = 'WFA' func = unicodedata.east_asian_width return sum(2 if func(char) in UNICODE_WIDE_CHAR_TYPE else 1 for char in string) def resolve_invite(invite): """ Resolves an invite from a :class:`~discord.Invite`, URL or code. Parameters ----------- invite: Union[:class:`~discord.Invite`, :class:`str`] The invite. Returns -------- :class:`str` The invite code. """ from .invite import Invite # circular import if isinstance(invite, Invite): return invite.code else: rx = r'(?:https?\:\/\/)?discord(?:\.gg|(?:app)?\.com\/invite)\/(.+)' m = re.match(rx, invite) if m: return m.group(1) return invite def resolve_template(code): """ Resolves a template code from a :class:`~discord.Template`, URL or code. .. versionadded:: 1.4 Parameters ----------- code: Union[:class:`~discord.Template`, :class:`str`] The code. Returns -------- :class:`str` The template code. """ from .template import Template # circular import if isinstance(code, Template): return code.code else: rx = r'(?:https?\:\/\/)?discord(?:\.new|(?:app)?\.com\/template)\/(.+)' m = re.match(rx, code) if m: return m.group(1) return code _MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c) for c in ('*', '`', '_', '~', '|')) _MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)' _MARKDOWN_ESCAPE_REGEX = re.compile(r'(?P<markdown>%s|%s)' % (_MARKDOWN_ESCAPE_SUBREGEX, _MARKDOWN_ESCAPE_COMMON), re.MULTILINE) _URL_REGEX = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])' _MARKDOWN_STOCK_REGEX = r'(?P<markdown>[_\\~|\*`]|%s)' % _MARKDOWN_ESCAPE_COMMON def remove_markdown(text, *, ignore_links=True): """A helper function that removes markdown characters. .. versionadded:: 1.7 .. note:: This function is not markdown aware and may remove meaning from the original text. For example, if the input contains ``10 * 5`` then it will be converted into ``10 5``. Parameters ----------- text: :class:`str` The text to remove markdown from. ignore_links: :class:`bool` Whether to leave links alone when removing markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters removed. """ def replacement(match): groupdict = match.groupdict() return groupdict.get('url', '') regex = _MARKDOWN_STOCK_REGEX if ignore_links: regex = '(?:%s|%s)' % (_URL_REGEX, regex) return re.sub(regex, replacement, text, 0, re.MULTILINE) def escape_markdown(text, *, as_needed=False, ignore_links=True): r"""A helper function that escapes Discord's markdown. Parameters ----------- text: :class:`str` The text to escape markdown from. as_needed: :class:`bool` Whether to escape the markdown characters as needed. This means that it does not escape extraneous characters if it's not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**`` instead of ``\*\*hello\*\*``. Note however that this can open you up to some clever syntax abuse. Defaults to ``False``. ignore_links: :class:`bool` Whether to leave links alone when escaping markdown. For example, if a URL in the text contains characters such as ``_`` then it will be left alone. This option is not supported with ``as_needed``. Defaults to ``True``. Returns -------- :class:`str` The text with the markdown special characters escaped with a slash. """ if not as_needed: def replacement(match): groupdict = match.groupdict() is_url = groupdict.get('url') if is_url: return is_url return '\\' + groupdict['markdown'] regex = _MARKDOWN_STOCK_REGEX if ignore_links: regex = '(?:%s|%s)' % (_URL_REGEX, regex) return re.sub(regex, replacement, text, 0, re.MULTILINE) else: text = re.sub(r'\\', r'\\\\', text) return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text) def escape_mentions(text): """A helper function that escapes everyone, here, role, and user mentions. .. note:: This does not include channel mentions. .. note:: For more granular control over what mentions should be escaped within messages, refer to the :class:`~discord.AllowedMentions` class. Parameters ----------- text: :class:`str` The text to escape mentions from. Returns -------- :class:`str` The text with the mentions removed. """ return re.sub(r'@(everyone|here|[!&]?[0-9]{17,20})', '@\u200b\\1', text)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/utils.py
utils.py
class _FakeBool: def __repr__(self): return 'True' def __eq__(self, other): return other is True def __bool__(self): return True default = _FakeBool() class AllowedMentions: """A class that represents what mentions are allowed in a message. This class can be set during :class:`Client` initialisation to apply to every message sent. It can also be applied on a per message basis via :meth:`abc.Messageable.send` for more fine-grained control. Attributes ------------ everyone: :class:`bool` Whether to allow everyone and here mentions. Defaults to ``True``. users: Union[:class:`bool`, List[:class:`abc.Snowflake`]] Controls the users being mentioned. If ``True`` (the default) then users are mentioned based on the message content. If ``False`` then users are not mentioned at all. If a list of :class:`abc.Snowflake` is given then only the users provided will be mentioned, provided those users are in the message content. roles: Union[:class:`bool`, List[:class:`abc.Snowflake`]] Controls the roles being mentioned. If ``True`` (the default) then roles are mentioned based on the message content. If ``False`` then roles are not mentioned at all. If a list of :class:`abc.Snowflake` is given then only the roles provided will be mentioned, provided those roles are in the message content. replied_user: :class:`bool` Whether to mention the author of the message being replied to. Defaults to ``True``. .. versionadded:: 1.6 """ __slots__ = ('everyone', 'users', 'roles', 'replied_user') def __init__(self, *, everyone=default, users=default, roles=default, replied_user=default): self.everyone = everyone self.users = users self.roles = roles self.replied_user = replied_user @classmethod def all(cls): """A factory method that returns a :class:`AllowedMentions` with all fields explicitly set to ``True`` .. versionadded:: 1.5 """ return cls(everyone=True, users=True, roles=True, replied_user=True) @classmethod def none(cls): """A factory method that returns a :class:`AllowedMentions` with all fields set to ``False`` .. versionadded:: 1.5 """ return cls(everyone=False, users=False, roles=False, replied_user=False) def to_dict(self): parse = [] data = {} if self.everyone: parse.append('everyone') if self.users == True: parse.append('users') elif self.users != False: data['users'] = [x.id for x in self.users] if self.roles == True: parse.append('roles') elif self.roles != False: data['roles'] = [x.id for x in self.roles] if self.replied_user: data['replied_user'] = True data['parse'] = parse return data def merge(self, other): # Creates a new AllowedMentions by merging from another one. # Merge is done by using the 'self' values unless explicitly # overridden by the 'other' values. everyone = self.everyone if other.everyone is default else other.everyone users = self.users if other.users is default else other.users roles = self.roles if other.roles is default else other.roles replied_user = self.replied_user if other.replied_user is default else other.replied_user return AllowedMentions(everyone=everyone, roles=roles, users=users, replied_user=replied_user) def __repr__(self): return '{0.__class__.__qualname__}(everyone={0.everyone}, users={0.users}, roles={0.roles}, replied_user={0.replied_user})'.format(self)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/mentions.py
mentions.py
from collections import namedtuple import discord.abc from .flags import PublicUserFlags from .utils import snowflake_time, _bytes_to_base64_data, parse_time from .enums import DefaultAvatar, RelationshipType, UserFlags, HypeSquadHouse, PremiumType, try_enum from .errors import ClientException from .colour import Colour from .asset import Asset from .utils import deprecated class Profile(namedtuple('Profile', 'flags user mutual_guilds connected_accounts premium_since')): __slots__ = () @property def nitro(self): return self.premium_since is not None premium = nitro def _has_flag(self, o): v = o.value return (self.flags & v) == v @property def staff(self): return self._has_flag(UserFlags.staff) @property def partner(self): return self._has_flag(UserFlags.partner) @property def bug_hunter(self): return self._has_flag(UserFlags.bug_hunter) @property def early_supporter(self): return self._has_flag(UserFlags.early_supporter) @property def hypesquad(self): return self._has_flag(UserFlags.hypesquad) @property def hypesquad_houses(self): flags = (UserFlags.hypesquad_bravery, UserFlags.hypesquad_brilliance, UserFlags.hypesquad_balance) return [house for house, flag in zip(HypeSquadHouse, flags) if self._has_flag(flag)] @property def team_user(self): return self._has_flag(UserFlags.team_user) @property def system(self): return self._has_flag(UserFlags.system) _BaseUser = discord.abc.User class BaseUser(_BaseUser): __slots__ = ('name', 'id', 'discriminator', 'avatar', 'bot', 'system', '_public_flags', '_state') def __init__(self, *, state, data): self._state = state self._update(data) def __str__(self): return '{0.name}#{0.discriminator}'.format(self) def __eq__(self, other): return isinstance(other, _BaseUser) and other.id == self.id def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return self.id >> 22 def _update(self, data): self.name = data['username'] self.id = int(data['id']) self.discriminator = data['discriminator'] self.avatar = data['avatar'] self._public_flags = data.get('public_flags', 0) self.bot = data.get('bot', False) self.system = data.get('system', False) @classmethod def _copy(cls, user): self = cls.__new__(cls) # bypass __init__ self.name = user.name self.id = user.id self.discriminator = user.discriminator self.avatar = user.avatar self.bot = user.bot self._state = user._state self._public_flags = user._public_flags return self def _to_minimal_user_json(self): return { 'username': self.name, 'id': self.id, 'avatar': self.avatar, 'discriminator': self.discriminator, 'bot': self.bot, } @property def public_flags(self): """:class:`PublicUserFlags`: The publicly available flags the user has.""" return PublicUserFlags._from_value(self._public_flags) @property def avatar_url(self): """:class:`Asset`: Returns an :class:`Asset` for the avatar the user has. If the user does not have a traditional avatar, an asset for the default avatar is returned instead. This is equivalent to calling :meth:`avatar_url_as` with the default parameters (i.e. webp/gif detection and a size of 1024). """ return self.avatar_url_as(format=None, size=1024) def is_avatar_animated(self): """:class:`bool`: Indicates if the user has an animated avatar.""" return bool(self.avatar and self.avatar.startswith('a_')) def avatar_url_as(self, *, format=None, static_format='webp', size=1024): """Returns an :class:`Asset` for the avatar the user has. If the user does not have a traditional avatar, an asset for the default avatar is returned instead. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif', and 'gif' is only valid for animated avatars. The size must be a power of 2 between 16 and 4096. Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the avatar to. If the format is ``None``, then it is automatically detected into either 'gif' or static_format depending on the avatar being animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated avatars to. Defaults to 'webp' size: :class:`int` The size of the image to display. Raises ------ InvalidArgument Bad image format passed to ``format`` or ``static_format``, or invalid ``size``. Returns -------- :class:`Asset` The resulting CDN asset. """ return Asset._from_avatar(self._state, self, format=format, static_format=static_format, size=size) @property def default_avatar(self): """:class:`DefaultAvatar`: Returns the default avatar for a given user. This is calculated by the user's discriminator.""" return try_enum(DefaultAvatar, int(self.discriminator) % len(DefaultAvatar)) @property def default_avatar_url(self): """:class:`Asset`: Returns a URL for a user's default avatar.""" return Asset(self._state, '/embed/avatars/{}.png'.format(self.default_avatar.value)) @property def colour(self): """:class:`Colour`: A property that returns a colour denoting the rendered colour for the user. This always returns :meth:`Colour.default`. There is an alias for this named :attr:`color`. """ return Colour.default() @property def color(self): """:class:`Colour`: A property that returns a color denoting the rendered color for the user. This always returns :meth:`Colour.default`. There is an alias for this named :attr:`colour`. """ return self.colour @property def mention(self): """:class:`str`: Returns a string that allows you to mention the given user.""" return '<@{0.id}>'.format(self) def permissions_in(self, channel): """An alias for :meth:`abc.GuildChannel.permissions_for`. Basically equivalent to: .. code-block:: python3 channel.permissions_for(self) Parameters ----------- channel: :class:`abc.GuildChannel` The channel to check your permissions for. """ return channel.permissions_for(self) @property def created_at(self): """:class:`datetime.datetime`: Returns the user's creation time in UTC. This is when the user's Discord account was created.""" return snowflake_time(self.id) @property def display_name(self): """:class:`str`: Returns the user's display name. For regular users this is just their username, but if they have a guild specific nickname then that is returned instead. """ return self.name def mentioned_in(self, message): """Checks if the user is mentioned in the specified message. Parameters ----------- message: :class:`Message` The message to check if you're mentioned in. Returns ------- :class:`bool` Indicates if the user is mentioned in the message. """ if message.mention_everyone: return True return any(user.id == self.id for user in message.mentions) class ClientUser(BaseUser): """Represents your Discord user. .. container:: operations .. describe:: x == y Checks if two users are equal. .. describe:: x != y Checks if two users are not equal. .. describe:: hash(x) Return the user's hash. .. describe:: str(x) Returns the user's name with discriminator. Attributes ----------- name: :class:`str` The user's username. id: :class:`int` The user's unique ID. discriminator: :class:`str` The user's discriminator. This is given when the username has conflicts. avatar: Optional[:class:`str`] The avatar hash the user has. Could be ``None``. bot: :class:`bool` Specifies if the user is a bot account. system: :class:`bool` Specifies if the user is a system user (i.e. represents Discord officially). .. versionadded:: 1.3 verified: :class:`bool` Specifies if the user's email is verified. email: Optional[:class:`str`] The email the user used when registering. .. deprecated:: 1.7 locale: Optional[:class:`str`] The IETF language tag used to identify the language the user is using. mfa_enabled: :class:`bool` Specifies if the user has MFA turned on and working. premium: :class:`bool` Specifies if the user is a premium user (e.g. has Discord Nitro). .. deprecated:: 1.7 premium_type: Optional[:class:`PremiumType`] Specifies the type of premium a user has (e.g. Nitro or Nitro Classic). Could be None if the user is not premium. .. deprecated:: 1.7 """ __slots__ = BaseUser.__slots__ + \ ('email', 'locale', '_flags', 'verified', 'mfa_enabled', 'premium', 'premium_type', '_relationships', '__weakref__') def __init__(self, *, state, data): super().__init__(state=state, data=data) self._relationships = {} def __repr__(self): return '<ClientUser id={0.id} name={0.name!r} discriminator={0.discriminator!r}' \ ' bot={0.bot} verified={0.verified} mfa_enabled={0.mfa_enabled}>'.format(self) def _update(self, data): super()._update(data) # There's actually an Optional[str] phone field as well but I won't use it self.verified = data.get('verified', False) self.email = data.get('email') self.locale = data.get('locale') self._flags = data.get('flags', 0) self.mfa_enabled = data.get('mfa_enabled', False) self.premium = data.get('premium', False) self.premium_type = try_enum(PremiumType, data.get('premium_type', None)) @deprecated() def get_relationship(self, user_id): """Retrieves the :class:`Relationship` if applicable. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Parameters ----------- user_id: :class:`int` The user ID to check if we have a relationship with them. Returns -------- Optional[:class:`Relationship`] The relationship if available or ``None``. """ return self._relationships.get(user_id) @property def relationships(self): """List[:class:`User`]: Returns all the relationships that the user has. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. """ return list(self._relationships.values()) @property def friends(self): r"""List[:class:`User`]: Returns all the users that the user is friends with. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. """ return [r.user for r in self._relationships.values() if r.type is RelationshipType.friend] @property def blocked(self): r"""List[:class:`User`]: Returns all the users that the user has blocked. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. """ return [r.user for r in self._relationships.values() if r.type is RelationshipType.blocked] async def edit(self, **fields): """|coro| Edits the current profile of the client. If a bot account is used then a password field is optional, otherwise it is required. .. warning:: The user account-only fields are deprecated. .. note:: To upload an avatar, a :term:`py:bytes-like object` must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via ``open('some_filename', 'rb')`` and the :term:`py:bytes-like object` is given through the use of ``fp.read()``. The only image formats supported for uploading is JPEG and PNG. Parameters ----------- password: :class:`str` The current password for the client's account. Only applicable to user accounts. new_password: :class:`str` The new password you wish to change to. Only applicable to user accounts. email: :class:`str` The new email you wish to change to. Only applicable to user accounts. house: Optional[:class:`HypeSquadHouse`] The hypesquad house you wish to change to. Could be ``None`` to leave the current house. Only applicable to user accounts. username: :class:`str` The new username you wish to change to. avatar: :class:`bytes` A :term:`py:bytes-like object` representing the image to upload. Could be ``None`` to denote no avatar. Raises ------ HTTPException Editing your profile failed. InvalidArgument Wrong image format passed for ``avatar``. ClientException Password is required for non-bot accounts. House field was not a HypeSquadHouse. """ try: avatar_bytes = fields['avatar'] except KeyError: avatar = self.avatar else: if avatar_bytes is not None: avatar = _bytes_to_base64_data(avatar_bytes) else: avatar = None not_bot_account = not self.bot password = fields.get('password') if not_bot_account and password is None: raise ClientException('Password is required for non-bot accounts.') args = { 'password': password, 'username': fields.get('username', self.name), 'avatar': avatar } if not_bot_account: args['email'] = fields.get('email', self.email) if 'new_password' in fields: args['new_password'] = fields['new_password'] http = self._state.http if 'house' in fields: house = fields['house'] if house is None: await http.leave_hypesquad_house() elif not isinstance(house, HypeSquadHouse): raise ClientException('`house` parameter was not a HypeSquadHouse') else: value = house.value await http.change_hypesquad_house(value) data = await http.edit_profile(**args) if not_bot_account: self.email = data['email'] try: http._token(data['token'], bot=False) except KeyError: pass self._update(data) @deprecated() async def create_group(self, *recipients): r"""|coro| Creates a group direct message with the recipients provided. These recipients must be have a relationship of type :attr:`RelationshipType.friend`. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Parameters ----------- \*recipients: :class:`User` An argument :class:`list` of :class:`User` to have in your group. Raises ------- HTTPException Failed to create the group direct message. ClientException Attempted to create a group with only one recipient. This does not include yourself. Returns ------- :class:`GroupChannel` The new group channel. """ from .channel import GroupChannel if len(recipients) < 2: raise ClientException('You must have two or more recipients to create a group.') users = [str(u.id) for u in recipients] data = await self._state.http.start_group(self.id, users) return GroupChannel(me=self, data=data, state=self._state) @deprecated() async def edit_settings(self, **kwargs): """|coro| Edits the client user's settings. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Parameters ------- afk_timeout: :class:`int` How long (in seconds) the user needs to be AFK until Discord sends push notifications to your mobile device. animate_emojis: :class:`bool` Whether or not to animate emojis in the chat. convert_emoticons: :class:`bool` Whether or not to automatically convert emoticons into emojis. e.g. :-) -> 😃 default_guilds_restricted: :class:`bool` Whether or not to automatically disable DMs between you and members of new guilds you join. detect_platform_accounts: :class:`bool` Whether or not to automatically detect accounts from services like Steam and Blizzard when you open the Discord client. developer_mode: :class:`bool` Whether or not to enable developer mode. disable_games_tab: :class:`bool` Whether or not to disable the showing of the Games tab. enable_tts_command: :class:`bool` Whether or not to allow tts messages to be played/sent. explicit_content_filter: :class:`UserContentFilter` The filter for explicit content in all messages. friend_source_flags: :class:`FriendFlags` Who can add you as a friend. gif_auto_play: :class:`bool` Whether or not to automatically play gifs that are in the chat. guild_positions: List[:class:`abc.Snowflake`] A list of guilds in order of the guild/guild icons that are on the left hand side of the UI. inline_attachment_media: :class:`bool` Whether or not to display attachments when they are uploaded in chat. inline_embed_media: :class:`bool` Whether or not to display videos and images from links posted in chat. locale: :class:`str` The :rfc:`3066` language identifier of the locale to use for the language of the Discord client. message_display_compact: :class:`bool` Whether or not to use the compact Discord display mode. render_embeds: :class:`bool` Whether or not to render embeds that are sent in the chat. render_reactions: :class:`bool` Whether or not to render reactions that are added to messages. restricted_guilds: List[:class:`abc.Snowflake`] A list of guilds that you will not receive DMs from. show_current_game: :class:`bool` Whether or not to display the game that you are currently playing. status: :class:`Status` The clients status that is shown to others. theme: :class:`Theme` The theme of the Discord UI. timezone_offset: :class:`int` The timezone offset to use. Raises ------- HTTPException Editing the settings failed. Forbidden The client is a bot user and not a user account. Returns ------- :class:`dict` The client user's updated settings. """ payload = {} content_filter = kwargs.pop('explicit_content_filter', None) if content_filter: payload.update({'explicit_content_filter': content_filter.value}) friend_flags = kwargs.pop('friend_source_flags', None) if friend_flags: dicts = [{}, {'mutual_guilds': True}, {'mutual_friends': True}, {'mutual_guilds': True, 'mutual_friends': True}, {'all': True}] payload.update({'friend_source_flags': dicts[friend_flags.value]}) guild_positions = kwargs.pop('guild_positions', None) if guild_positions: guild_positions = [str(x.id) for x in guild_positions] payload.update({'guild_positions': guild_positions}) restricted_guilds = kwargs.pop('restricted_guilds', None) if restricted_guilds: restricted_guilds = [str(x.id) for x in restricted_guilds] payload.update({'restricted_guilds': restricted_guilds}) status = kwargs.pop('status', None) if status: payload.update({'status': status.value}) theme = kwargs.pop('theme', None) if theme: payload.update({'theme': theme.value}) payload.update(kwargs) data = await self._state.http.edit_settings(**payload) return data class User(BaseUser, discord.abc.Messageable): """Represents a Discord user. .. container:: operations .. describe:: x == y Checks if two users are equal. .. describe:: x != y Checks if two users are not equal. .. describe:: hash(x) Return the user's hash. .. describe:: str(x) Returns the user's name with discriminator. Attributes ----------- name: :class:`str` The user's username. id: :class:`int` The user's unique ID. discriminator: :class:`str` The user's discriminator. This is given when the username has conflicts. avatar: Optional[:class:`str`] The avatar hash the user has. Could be None. bot: :class:`bool` Specifies if the user is a bot account. system: :class:`bool` Specifies if the user is a system user (i.e. represents Discord officially). """ __slots__ = BaseUser.__slots__ + ('__weakref__',) def __repr__(self): return '<User id={0.id} name={0.name!r} discriminator={0.discriminator!r} bot={0.bot}>'.format(self) async def _get_channel(self): ch = await self.create_dm() return ch @property def dm_channel(self): """Optional[:class:`DMChannel`]: Returns the channel associated with this user if it exists. If this returns ``None``, you can create a DM channel by calling the :meth:`create_dm` coroutine function. """ return self._state._get_private_channel_by_user(self.id) @property def mutual_guilds(self): """List[:class:`Guild`]: The guilds that the user shares with the client. .. note:: This will only return mutual guilds within the client's internal cache. .. versionadded:: 1.7 """ return [guild for guild in self._state._guilds.values() if guild.get_member(self.id)] async def create_dm(self): """|coro| Creates a :class:`DMChannel` with this user. This should be rarely called, as this is done transparently for most people. Returns ------- :class:`.DMChannel` The channel that was created. """ found = self.dm_channel if found is not None: return found state = self._state data = await state.http.start_private_message(self.id) return state.add_dm_channel(data) @property def relationship(self): """Optional[:class:`Relationship`]: Returns the :class:`Relationship` with this user if applicable, ``None`` otherwise. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. """ return self._state.user.get_relationship(self.id) @deprecated() async def mutual_friends(self): """|coro| Gets all mutual friends of this user. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Raises ------- Forbidden Not allowed to get mutual friends of this user. HTTPException Getting mutual friends failed. Returns ------- List[:class:`User`] The users that are mutual friends. """ state = self._state mutuals = await state.http.get_mutual_friends(self.id) return [User(state=state, data=friend) for friend in mutuals] @deprecated() def is_friend(self): """:class:`bool`: Checks if the user is your friend. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. """ r = self.relationship if r is None: return False return r.type is RelationshipType.friend @deprecated() def is_blocked(self): """:class:`bool`: Checks if the user is blocked. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. """ r = self.relationship if r is None: return False return r.type is RelationshipType.blocked @deprecated() async def block(self): """|coro| Blocks the user. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Raises ------- Forbidden Not allowed to block this user. HTTPException Blocking the user failed. """ await self._state.http.add_relationship(self.id, type=RelationshipType.blocked.value) @deprecated() async def unblock(self): """|coro| Unblocks the user. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Raises ------- Forbidden Not allowed to unblock this user. HTTPException Unblocking the user failed. """ await self._state.http.remove_relationship(self.id) @deprecated() async def remove_friend(self): """|coro| Removes the user as a friend. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Raises ------- Forbidden Not allowed to remove this user as a friend. HTTPException Removing the user as a friend failed. """ await self._state.http.remove_relationship(self.id) @deprecated() async def send_friend_request(self): """|coro| Sends the user a friend request. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Raises ------- Forbidden Not allowed to send a friend request to the user. HTTPException Sending the friend request failed. """ await self._state.http.send_friend_request(username=self.name, discriminator=self.discriminator) @deprecated() async def profile(self): """|coro| Gets the user's profile. .. deprecated:: 1.7 .. note:: This can only be used by non-bot accounts. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns -------- :class:`Profile` The profile of the user. """ state = self._state data = await state.http.get_user_profile(self.id) def transform(d): return state._get_guild(int(d['id'])) since = data.get('premium_since') mutual_guilds = list(filter(None, map(transform, data.get('mutual_guilds', [])))) return Profile(flags=data['user'].get('flags', 0), premium_since=parse_time(since), mutual_guilds=mutual_guilds, user=self, connected_accounts=data['connected_accounts'])
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/user.py
user.py
from .iterators import ReactionIterator class Reaction: """Represents a reaction to a message. Depending on the way this object was created, some of the attributes can have a value of ``None``. .. container:: operations .. describe:: x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered "equal". .. describe:: x != y Checks if two reactions are not equal. .. describe:: hash(x) Returns the reaction's hash. .. describe:: str(x) Returns the string form of the reaction's emoji. Attributes ----------- emoji: Union[:class:`Emoji`, :class:`PartialEmoji`, :class:`str`] The reaction emoji. May be a custom emoji, or a unicode emoji. count: :class:`int` Number of times this reaction was made me: :class:`bool` If the user sent this reaction. message: :class:`Message` Message this reaction is for. """ __slots__ = ('message', 'count', 'emoji', 'me') def __init__(self, *, message, data, emoji=None): self.message = message self.emoji = emoji or message._state.get_reaction_emoji(data['emoji']) self.count = data.get('count', 1) self.me = data.get('me') @property def custom_emoji(self): """:class:`bool`: If this is a custom emoji.""" return not isinstance(self.emoji, str) def __eq__(self, other): return isinstance(other, self.__class__) and other.emoji == self.emoji def __ne__(self, other): if isinstance(other, self.__class__): return other.emoji != self.emoji return True def __hash__(self): return hash(self.emoji) def __str__(self): return str(self.emoji) def __repr__(self): return '<Reaction emoji={0.emoji!r} me={0.me} count={0.count}>'.format(self) async def remove(self, user): """|coro| Remove the reaction by the provided :class:`User` from the message. If the reaction is not your own (i.e. ``user`` parameter is not you) then the :attr:`~Permissions.manage_messages` permission is needed. The ``user`` parameter must represent a user or member and meet the :class:`abc.Snowflake` abc. Parameters ----------- user: :class:`abc.Snowflake` The user or member from which to remove the reaction. Raises ------- HTTPException Removing the reaction failed. Forbidden You do not have the proper permissions to remove the reaction. NotFound The user you specified, or the reaction's message was not found. """ await self.message.remove_reaction(self.emoji, user) async def clear(self): """|coro| Clears this reaction from the message. You need the :attr:`~Permissions.manage_messages` permission to use this. .. versionadded:: 1.3 Raises -------- HTTPException Clearing the reaction failed. Forbidden You do not have the proper permissions to clear the reaction. NotFound The emoji you specified was not found. InvalidArgument The emoji parameter is invalid. """ await self.message.clear_reaction(self.emoji) def users(self, limit=None, after=None): """Returns an :class:`AsyncIterator` representing the users that have reacted to the message. The ``after`` parameter must represent a member and meet the :class:`abc.Snowflake` abc. Examples --------- Usage :: # I do not actually recommend doing this. async for user in reaction.users(): await channel.send('{0} has reacted with {1.emoji}!'.format(user, reaction)) Flattening into a list: :: users = await reaction.users().flatten() # users is now a list of User... winner = random.choice(users) await channel.send('{} has won the raffle.'.format(winner)) Parameters ------------ limit: :class:`int` The maximum number of results to return. If not provided, returns all the users who reacted to the message. after: :class:`abc.Snowflake` For pagination, reactions are sorted by member. Raises -------- HTTPException Getting the users for the reaction failed. Yields -------- Union[:class:`User`, :class:`Member`] The member (if retrievable) or the user that has reacted to this message. The case where it can be a :class:`Member` is in a guild message context. Sometimes it can be a :class:`User` if the member has left the guild. """ if self.custom_emoji: emoji = '{0.name}:{0.id}'.format(self.emoji) else: emoji = self.emoji if limit is None: limit = self.count return ReactionIterator(self.message, emoji, limit, after)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/reaction.py
reaction.py
import asyncio import datetime from .errors import NoMoreItems from .utils import time_snowflake, maybe_coroutine from .object import Object from .audit_logs import AuditLogEntry OLDEST_OBJECT = Object(id=0) class _AsyncIterator: __slots__ = () def get(self, **attrs): def predicate(elem): for attr, val in attrs.items(): nested = attr.split('__') obj = elem for attribute in nested: obj = getattr(obj, attribute) if obj != val: return False return True return self.find(predicate) async def find(self, predicate): while True: try: elem = await self.next() except NoMoreItems: return None ret = await maybe_coroutine(predicate, elem) if ret: return elem def chunk(self, max_size): if max_size <= 0: raise ValueError('async iterator chunk sizes must be greater than 0.') return _ChunkedAsyncIterator(self, max_size) def map(self, func): return _MappedAsyncIterator(self, func) def filter(self, predicate): return _FilteredAsyncIterator(self, predicate) async def flatten(self): ret = [] while True: try: item = await self.next() except NoMoreItems: return ret else: ret.append(item) def __aiter__(self): return self async def __anext__(self): try: msg = await self.next() except NoMoreItems: raise StopAsyncIteration() else: return msg def _identity(x): return x class _ChunkedAsyncIterator(_AsyncIterator): def __init__(self, iterator, max_size): self.iterator = iterator self.max_size = max_size async def next(self): ret = [] n = 0 while n < self.max_size: try: item = await self.iterator.next() except NoMoreItems: if ret: return ret raise else: ret.append(item) n += 1 return ret class _MappedAsyncIterator(_AsyncIterator): def __init__(self, iterator, func): self.iterator = iterator self.func = func async def next(self): # this raises NoMoreItems and will propagate appropriately item = await self.iterator.next() return await maybe_coroutine(self.func, item) class _FilteredAsyncIterator(_AsyncIterator): def __init__(self, iterator, predicate): self.iterator = iterator if predicate is None: predicate = _identity self.predicate = predicate async def next(self): getter = self.iterator.next pred = self.predicate while True: # propagate NoMoreItems similar to _MappedAsyncIterator item = await getter() ret = await maybe_coroutine(pred, item) if ret: return item class ReactionIterator(_AsyncIterator): def __init__(self, message, emoji, limit=100, after=None): self.message = message self.limit = limit self.after = after state = message._state self.getter = state.http.get_reaction_users self.state = state self.emoji = emoji self.guild = message.guild self.channel_id = message.channel.id self.users = asyncio.Queue() async def next(self): if self.users.empty(): await self.fill_users() try: return self.users.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() async def fill_users(self): # this is a hack because >circular imports< from .user import User if self.limit > 0: retrieve = self.limit if self.limit <= 100 else 100 after = self.after.id if self.after else None data = await self.getter(self.channel_id, self.message.id, self.emoji, retrieve, after=after) if data: self.limit -= retrieve self.after = Object(id=int(data[-1]['id'])) if self.guild is None or isinstance(self.guild, Object): for element in reversed(data): await self.users.put(User(state=self.state, data=element)) else: for element in reversed(data): member_id = int(element['id']) member = self.guild.get_member(member_id) if member is not None: await self.users.put(member) else: await self.users.put(User(state=self.state, data=element)) class HistoryIterator(_AsyncIterator): """Iterator for receiving a channel's message history. The messages endpoint has two behaviours we care about here: If ``before`` is specified, the messages endpoint returns the `limit` newest messages before ``before``, sorted with newest first. For filling over 100 messages, update the ``before`` parameter to the oldest message received. Messages will be returned in order by time. If ``after`` is specified, it returns the ``limit`` oldest messages after ``after``, sorted with newest first. For filling over 100 messages, update the ``after`` parameter to the newest message received. If messages are not reversed, they will be out of order (99-0, 199-100, so on) A note that if both ``before`` and ``after`` are specified, ``before`` is ignored by the messages endpoint. Parameters ----------- messageable: :class:`abc.Messageable` Messageable class to retrieve message history from. limit: :class:`int` Maximum number of messages to retrieve before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message before which all messages must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message after which all messages must be. around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message around which all messages must be. Limit max 101. Note that if limit is an even number, this will return at most limit+1 messages. oldest_first: Optional[:class:`bool`] If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if `after` is specified, otherwise ``False``. """ def __init__(self, messageable, limit, before=None, after=None, around=None, oldest_first=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if isinstance(around, datetime.datetime): around = Object(id=time_snowflake(around)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.messageable = messageable self.limit = limit self.before = before self.after = after or OLDEST_OBJECT self.around = around self._filter = None # message dict -> bool self.state = self.messageable._state self.logs_from = self.state.http.logs_from self.messages = asyncio.Queue() if self.around: if self.limit is None: raise ValueError('history does not support around with limit=None') if self.limit > 101: raise ValueError("history max limit 101 when specifying around parameter") elif self.limit == 101: self.limit = 100 # Thanks discord self._retrieve_messages = self._retrieve_messages_around_strategy if self.before and self.after: self._filter = lambda m: self.after.id < int(m['id']) < self.before.id elif self.before: self._filter = lambda m: int(m['id']) < self.before.id elif self.after: self._filter = lambda m: self.after.id < int(m['id']) else: if self.reverse: self._retrieve_messages = self._retrieve_messages_after_strategy if (self.before): self._filter = lambda m: int(m['id']) < self.before.id else: self._retrieve_messages = self._retrieve_messages_before_strategy if (self.after and self.after != OLDEST_OBJECT): self._filter = lambda m: int(m['id']) > self.after.id async def next(self): if self.messages.empty(): await self.fill_messages() try: return self.messages.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def flatten(self): # this is similar to fill_messages except it uses a list instead # of a queue to place the messages in. result = [] channel = await self.messageable._get_channel() self.channel = channel while self._get_retrieve(): data = await self._retrieve_messages(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) for element in data: result.append(self.state.create_message(channel=channel, data=element)) return result async def fill_messages(self): if not hasattr(self, 'channel'): # do the required set up channel = await self.messageable._get_channel() self.channel = channel if self._get_retrieve(): data = await self._retrieve_messages(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) channel = self.channel for element in data: await self.messages.put(self.state.create_message(channel=channel, data=element)) async def _retrieve_messages(self, retrieve): """Retrieve messages and update next parameters.""" pass async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter.""" after = self.after.id if self.after else None data = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter.""" if self.around: around = self.around.id if self.around else None data = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return [] class AuditLogIterator(_AsyncIterator): def __init__(self, guild, limit=None, before=None, after=None, oldest_first=None, user_id=None, action_type=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.guild = guild self.loop = guild._state.loop self.request = guild._state.http.get_audit_logs self.limit = limit self.before = before self.user_id = user_id self.action_type = action_type self.after = OLDEST_OBJECT self._users = {} self._state = guild._state self._filter = None # entry dict -> bool self.entries = asyncio.Queue() if self.reverse: self._strategy = self._after_strategy if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._strategy = self._before_strategy if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def _before_strategy(self, retrieve): before = self.before.id if self.before else None data = await self.request(self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, before=before) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(entries[-1]['id'])) return data.get('users', []), entries async def _after_strategy(self, retrieve): after = self.after.id if self.after else None data = await self.request(self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, after=after) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(entries[0]['id'])) return data.get('users', []), entries async def next(self): if self.entries.empty(): await self._fill() try: return self.entries.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def _fill(self): from .user import User if self._get_retrieve(): users, data = await self._strategy(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) for user in users: u = User(data=user, state=self._state) self._users[u.id] = u for element in data: # TODO: remove this if statement later if element['action_type'] is None: continue await self.entries.put(AuditLogEntry(data=element, users=self._users, guild=self.guild)) class GuildIterator(_AsyncIterator): """Iterator for receiving the client's guilds. The guilds endpoint has the same two behaviours as described in :class:`HistoryIterator`: If ``before`` is specified, the guilds endpoint returns the ``limit`` newest guilds before ``before``, sorted with newest first. For filling over 100 guilds, update the ``before`` parameter to the oldest guild received. Guilds will be returned in order by time. If `after` is specified, it returns the ``limit`` oldest guilds after ``after``, sorted with newest first. For filling over 100 guilds, update the ``after`` parameter to the newest guild received, If guilds are not reversed, they will be out of order (99-0, 199-100, so on) Not that if both ``before`` and ``after`` are specified, ``before`` is ignored by the guilds endpoint. Parameters ----------- bot: :class:`discord.Client` The client to retrieve the guilds from. limit: :class:`int` Maximum number of guilds to retrieve. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object before which all guilds must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object after which all guilds must be. """ def __init__(self, bot, limit, before=None, after=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.bot = bot self.limit = limit self.before = before self.after = after self._filter = None self.state = self.bot._connection self.get_guilds = self.bot.http.get_guilds self.guilds = asyncio.Queue() if self.before and self.after: self._retrieve_guilds = self._retrieve_guilds_before_strategy self._filter = lambda m: int(m['id']) > self.after.id elif self.after: self._retrieve_guilds = self._retrieve_guilds_after_strategy else: self._retrieve_guilds = self._retrieve_guilds_before_strategy async def next(self): if self.guilds.empty(): await self.fill_guilds() try: return self.guilds.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 def create_guild(self, data): from .guild import Guild return Guild(state=self.state, data=data) async def flatten(self): result = [] while self._get_retrieve(): data = await self._retrieve_guilds(self.retrieve) if len(data) < 100: self.limit = 0 if self._filter: data = filter(self._filter, data) for element in data: result.append(self.create_guild(element)) return result async def fill_guilds(self): if self._get_retrieve(): data = await self._retrieve_guilds(self.retrieve) if self.limit is None or len(data) < 100: self.limit = 0 if self._filter: data = filter(self._filter, data) for element in data: await self.guilds.put(self.create_guild(element)) async def _retrieve_guilds(self, retrieve): """Retrieve guilds and update next parameters.""" pass async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter.""" before = self.before.id if self.before else None data = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter.""" after = self.after.id if self.after else None data = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data class MemberIterator(_AsyncIterator): def __init__(self, guild, limit=1000, after=None): if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.guild = guild self.limit = limit self.after = after or OLDEST_OBJECT self.state = self.guild._state self.get_members = self.state.http.get_members self.members = asyncio.Queue() async def next(self): if self.members.empty(): await self.fill_members() try: return self.members.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 1000: r = 1000 else: r = l self.retrieve = r return r > 0 async def fill_members(self): if self._get_retrieve(): after = self.after.id if self.after else None data = await self.get_members(self.guild.id, self.retrieve, after) if not data: # no data, terminate return if len(data) < 1000: self.limit = 0 # terminate loop self.after = Object(id=int(data[-1]['user']['id'])) for element in reversed(data): await self.members.put(self.create_member(element)) def create_member(self, data): from .member import Member return Member(data=data, guild=self.guild, state=self.state)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/iterators.py
iterators.py
from .utils import parse_time, _get_as_snowflake, _bytes_to_base64_data from .enums import VoiceRegion from .guild import Guild __all__ = ( 'Template', ) class _FriendlyHttpAttributeErrorHelper: __slots__ = () def __getattr__(self, attr): raise AttributeError('PartialTemplateState does not support http methods.') class _PartialTemplateState: def __init__(self, *, state): self.__state = state self.http = _FriendlyHttpAttributeErrorHelper() @property def is_bot(self): return self.__state.is_bot @property def shard_count(self): return self.__state.shard_count @property def user(self): return self.__state.user @property def self_id(self): return self.__state.user.id @property def member_cache_flags(self): return self.__state.member_cache_flags def store_emoji(self, guild, packet): return None def _get_voice_client(self, id): return None def _get_message(self, id): return None async def query_members(self, **kwargs): return [] def __getattr__(self, attr): raise AttributeError('PartialTemplateState does not support {0!r}.'.format(attr)) class Template: """Represents a Discord template. .. versionadded:: 1.4 Attributes ----------- code: :class:`str` The template code. uses: :class:`int` How many times the template has been used. name: :class:`str` The name of the template. description: :class:`str` The description of the template. creator: :class:`User` The creator of the template. created_at: :class:`datetime.datetime` When the template was created. updated_at: :class:`datetime.datetime` When the template was last updated (referred to as "last synced" in the client). source_guild: :class:`Guild` The source guild. """ def __init__(self, *, state, data): self._state = state self._store(data) def _store(self, data): self.code = data['code'] self.uses = data['usage_count'] self.name = data['name'] self.description = data['description'] creator_data = data.get('creator') self.creator = None if creator_data is None else self._state.store_user(creator_data) self.created_at = parse_time(data.get('created_at')) self.updated_at = parse_time(data.get('updated_at')) id = _get_as_snowflake(data, 'source_guild_id') guild = self._state._get_guild(id) if guild is None: source_serialised = data['serialized_source_guild'] source_serialised['id'] = id state = _PartialTemplateState(state=self._state) guild = Guild(data=source_serialised, state=state) self.source_guild = guild def __repr__(self): return '<Template code={0.code!r} uses={0.uses} name={0.name!r}' \ ' creator={0.creator!r} source_guild={0.source_guild!r}>'.format(self) async def create_guild(self, name, region=None, icon=None): """|coro| Creates a :class:`.Guild` using the template. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`.VoiceRegion` The region for the voice communication server. Defaults to :attr:`.VoiceRegion.us_west`. icon: :class:`bytes` The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` for more details on what is expected. Raises ------ HTTPException Guild creation failed. InvalidArgument Invalid icon image format given. Must be PNG or JPG. Returns ------- :class:`.Guild` The guild created. This is not the same guild that is added to cache. """ if icon is not None: icon = _bytes_to_base64_data(icon) region = region or VoiceRegion.us_west region_value = region.value data = await self._state.http.create_from_template(self.code, name, region_value, icon) return Guild(data=data, state=self._state) async def sync(self): """|coro| Sync the template to the guild's current state. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. """ data = await self._state.http.sync_template(self.source_guild.id, self.code) self._store(data) async def edit(self, **kwargs): """|coro| Edit the template metadata. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 Parameters ------------ name: Optional[:class:`str`] The template's new name. description: Optional[:class:`str`] The template's description. Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. """ data = await self._state.http.edit_template(self.source_guild.id, self.code, kwargs) self._store(data) async def delete(self): """|coro| Delete the template. You must have the :attr:`~Permissions.manage_guild` permission in the source guild to do this. .. versionadded:: 1.7 Raises ------- HTTPException Editing the template failed. Forbidden You don't have permissions to edit the template. NotFound This template does not exist. """ await self._state.http.delete_template(self.source_guild.id, self.code)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/template.py
template.py
import asyncio from collections import deque, OrderedDict import copy import datetime import itertools import logging import weakref import warnings import inspect import gc import os from .guild import Guild from .activity import BaseActivity from .user import User, ClientUser from .emoji import Emoji from .mentions import AllowedMentions from .partial_emoji import PartialEmoji from .message import Message from .relationship import Relationship from .channel import * from .raw_models import * from .member import Member from .role import Role from .enums import ChannelType, try_enum, Status from . import utils from .flags import Intents, MemberCacheFlags from .object import Object from .invite import Invite class ChunkRequest: def __init__(self, guild_id, loop, resolver, *, cache=True): self.guild_id = guild_id self.resolver = resolver self.loop = loop self.cache = cache self.nonce = os.urandom(16).hex() self.buffer = [] # List[Member] self.waiters = [] def add_members(self, members): self.buffer.extend(members) if self.cache: guild = self.resolver(self.guild_id) if guild is None: return for member in members: existing = guild.get_member(member.id) if existing is None or existing.joined_at is None: guild._add_member(member) async def wait(self): future = self.loop.create_future() self.waiters.append(future) try: return await future finally: self.waiters.remove(future) def get_future(self): future = self.loop.create_future() self.waiters.append(future) return future def done(self): for future in self.waiters: if not future.done(): future.set_result(self.buffer) log = logging.getLogger(__name__) async def logging_coroutine(coroutine, *, info): try: await coroutine except Exception: log.exception('Exception occurred during %s', info) class ConnectionState: def __init__(self, *, dispatch, handlers, hooks, syncer, http, loop, **options): self.loop = loop self.http = http self.max_messages = options.get('max_messages', 1000) if self.max_messages is not None and self.max_messages <= 0: self.max_messages = 1000 self.dispatch = dispatch self.syncer = syncer self.is_bot = None self.handlers = handlers self.hooks = hooks self.shard_count = None self._ready_task = None self.heartbeat_timeout = options.get('heartbeat_timeout', 60.0) self.guild_ready_timeout = options.get('guild_ready_timeout', 2.0) if self.guild_ready_timeout < 0: raise ValueError('guild_ready_timeout cannot be negative') self.guild_subscriptions = options.get('guild_subscriptions', True) allowed_mentions = options.get('allowed_mentions') if allowed_mentions is not None and not isinstance(allowed_mentions, AllowedMentions): raise TypeError('allowed_mentions parameter must be AllowedMentions') self.allowed_mentions = allowed_mentions self._chunk_requests = {} # Dict[Union[int, str], ChunkRequest] activity = options.get('activity', None) if activity: if not isinstance(activity, BaseActivity): raise TypeError('activity parameter must derive from BaseActivity.') activity = activity.to_dict() status = options.get('status', None) if status: if status is Status.offline: status = 'invisible' else: status = str(status) intents = options.get('intents', None) if intents is not None: if not isinstance(intents, Intents): raise TypeError('intents parameter must be Intent not %r' % type(intents)) else: intents = Intents.default() if not intents.guilds: log.warning('Guilds intent seems to be disabled. This may cause state related issues.') try: chunk_guilds = options['fetch_offline_members'] except KeyError: chunk_guilds = options.get('chunk_guilds_at_startup', intents.members) else: msg = 'fetch_offline_members is deprecated, use chunk_guilds_at_startup instead' warnings.warn(msg, DeprecationWarning, stacklevel=4) self._chunk_guilds = chunk_guilds # Ensure these two are set properly if not intents.members and self._chunk_guilds: raise ValueError('Intents.members must be enabled to chunk guilds at startup.') cache_flags = options.get('member_cache_flags', None) if cache_flags is None: cache_flags = MemberCacheFlags.from_intents(intents) else: if not isinstance(cache_flags, MemberCacheFlags): raise TypeError('member_cache_flags parameter must be MemberCacheFlags not %r' % type(cache_flags)) cache_flags._verify_intents(intents) self.member_cache_flags = cache_flags self._activity = activity self._status = status self._intents = intents if not intents.members or cache_flags._empty: self.store_user = self.store_user_no_intents self.parsers = parsers = {} for attr, func in inspect.getmembers(self): if attr.startswith('parse_'): parsers[attr[6:].upper()] = func self.clear() def clear(self): self.user = None self._users = weakref.WeakValueDictionary() self._emojis = {} self._calls = {} self._guilds = {} self._voice_clients = {} # LRU of max size 128 self._private_channels = OrderedDict() # extra dict to look up private channels by user id self._private_channels_by_user = {} self._messages = self.max_messages and deque(maxlen=self.max_messages) # In cases of large deallocations the GC should be called explicitly # To free the memory more immediately, especially true when it comes # to reconnect loops which cause mass allocations and deallocations. gc.collect() def process_chunk_requests(self, guild_id, nonce, members, complete): removed = [] for key, request in self._chunk_requests.items(): if request.guild_id == guild_id and request.nonce == nonce: request.add_members(members) if complete: request.done() removed.append(key) for key in removed: del self._chunk_requests[key] def call_handlers(self, key, *args, **kwargs): try: func = self.handlers[key] except KeyError: pass else: func(*args, **kwargs) async def call_hooks(self, key, *args, **kwargs): try: coro = self.hooks[key] except KeyError: pass else: await coro(*args, **kwargs) @property def self_id(self): u = self.user return u.id if u else None @property def intents(self): ret = Intents.none() ret.value = self._intents.value return ret @property def voice_clients(self): return list(self._voice_clients.values()) def _get_voice_client(self, guild_id): return self._voice_clients.get(guild_id) def _add_voice_client(self, guild_id, voice): self._voice_clients[guild_id] = voice def _remove_voice_client(self, guild_id): self._voice_clients.pop(guild_id, None) def _update_references(self, ws): for vc in self.voice_clients: vc.main_ws = ws def store_user(self, data): # this way is 300% faster than `dict.setdefault`. user_id = int(data['id']) try: return self._users[user_id] except KeyError: user = User(state=self, data=data) if user.discriminator != '0000': self._users[user_id] = user return user def store_user_no_intents(self, data): return User(state=self, data=data) def get_user(self, id): return self._users.get(id) def store_emoji(self, guild, data): emoji_id = int(data['id']) self._emojis[emoji_id] = emoji = Emoji(guild=guild, state=self, data=data) return emoji @property def guilds(self): return list(self._guilds.values()) def _get_guild(self, guild_id): return self._guilds.get(guild_id) def _add_guild(self, guild): self._guilds[guild.id] = guild def _remove_guild(self, guild): self._guilds.pop(guild.id, None) for emoji in guild.emojis: self._emojis.pop(emoji.id, None) del guild # Much like clear(), if we have a massive deallocation # then it's better to explicitly call the GC gc.collect() @property def emojis(self): return list(self._emojis.values()) def get_emoji(self, emoji_id): return self._emojis.get(emoji_id) @property def private_channels(self): return list(self._private_channels.values()) def _get_private_channel(self, channel_id): try: value = self._private_channels[channel_id] except KeyError: return None else: self._private_channels.move_to_end(channel_id) return value def _get_private_channel_by_user(self, user_id): return self._private_channels_by_user.get(user_id) def _add_private_channel(self, channel): channel_id = channel.id self._private_channels[channel_id] = channel if self.is_bot and len(self._private_channels) > 128: _, to_remove = self._private_channels.popitem(last=False) if isinstance(to_remove, DMChannel): self._private_channels_by_user.pop(to_remove.recipient.id, None) if isinstance(channel, DMChannel): self._private_channels_by_user[channel.recipient.id] = channel def add_dm_channel(self, data): channel = DMChannel(me=self.user, state=self, data=data) self._add_private_channel(channel) return channel def _remove_private_channel(self, channel): self._private_channels.pop(channel.id, None) if isinstance(channel, DMChannel): self._private_channels_by_user.pop(channel.recipient.id, None) def _get_message(self, msg_id): return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None def _add_guild_from_data(self, guild): guild = Guild(data=guild, state=self) self._add_guild(guild) return guild def _guild_needs_chunking(self, guild): # If presences are enabled then we get back the old guild.large behaviour return self._chunk_guilds and not guild.chunked and not (self._intents.presences and not guild.large) def _get_guild_channel(self, data): channel_id = int(data['channel_id']) try: guild = self._get_guild(int(data['guild_id'])) except KeyError: channel = self.get_channel(channel_id) guild = None else: channel = guild and guild.get_channel(channel_id) return channel or Object(id=channel_id), guild async def chunker(self, guild_id, query='', limit=0, presences=False, *, nonce=None): ws = self._get_websocket(guild_id) # This is ignored upstream await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce) async def query_members(self, guild, query, limit, user_ids, cache, presences): guild_id = guild.id ws = self._get_websocket(guild_id) if ws is None: raise RuntimeError('Somehow do not have a websocket for this guild_id') request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache) self._chunk_requests[request.nonce] = request try: # start the query operation await ws.request_chunks(guild_id, query=query, limit=limit, user_ids=user_ids, presences=presences, nonce=request.nonce) return await asyncio.wait_for(request.wait(), timeout=30.0) except asyncio.TimeoutError: log.warning('Timed out waiting for chunks with query %r and limit %d for guild_id %d', query, limit, guild_id) raise async def _delay_ready(self): try: # only real bots wait for GUILD_CREATE streaming if self.is_bot: states = [] while True: # this snippet of code is basically waiting N seconds # until the last GUILD_CREATE was sent try: guild = await asyncio.wait_for(self._ready_state.get(), timeout=self.guild_ready_timeout) except asyncio.TimeoutError: break else: if self._guild_needs_chunking(guild): future = await self.chunk_guild(guild, wait=False) states.append((guild, future)) else: if guild.unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) for guild, future in states: try: await asyncio.wait_for(future, timeout=5.0) except asyncio.TimeoutError: log.warning('Shard ID %s timed out waiting for chunks for guild_id %s.', guild.shard_id, guild.id) if guild.unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) # remove the state try: del self._ready_state except AttributeError: pass # already been deleted somehow # call GUILD_SYNC after we're done chunking if not self.is_bot: log.info('Requesting GUILD_SYNC for %s guilds', len(self.guilds)) await self.syncer([s.id for s in self.guilds]) except asyncio.CancelledError: pass else: # dispatch the event self.call_handlers('ready') self.dispatch('ready') finally: self._ready_task = None def parse_ready(self, data): if self._ready_task is not None: self._ready_task.cancel() self._ready_state = asyncio.Queue() self.clear() self.user = user = ClientUser(state=self, data=data['user']) self._users[user.id] = user for guild_data in data['guilds']: self._add_guild_from_data(guild_data) for relationship in data.get('relationships', []): try: r_id = int(relationship['id']) except KeyError: continue else: user._relationships[r_id] = Relationship(state=self, data=relationship) for pm in data.get('private_channels', []): factory, _ = _channel_factory(pm['type']) self._add_private_channel(factory(me=user, data=pm, state=self)) self.dispatch('connect') self._ready_task = asyncio.ensure_future(self._delay_ready(), loop=self.loop) def parse_resumed(self, data): self.dispatch('resumed') def parse_message_create(self, data): channel, _ = self._get_guild_channel(data) message = Message(channel=channel, data=data, state=self) self.dispatch('message', message) if self._messages is not None: self._messages.append(message) if channel and channel.__class__ is TextChannel: channel.last_message_id = message.id def parse_message_delete(self, data): raw = RawMessageDeleteEvent(data) found = self._get_message(raw.message_id) raw.cached_message = found self.dispatch('raw_message_delete', raw) if self._messages is not None and found is not None: self.dispatch('message_delete', found) self._messages.remove(found) def parse_message_delete_bulk(self, data): raw = RawBulkMessageDeleteEvent(data) if self._messages: found_messages = [message for message in self._messages if message.id in raw.message_ids] else: found_messages = [] raw.cached_messages = found_messages self.dispatch('raw_bulk_message_delete', raw) if found_messages: self.dispatch('bulk_message_delete', found_messages) for msg in found_messages: self._messages.remove(msg) def parse_message_update(self, data): raw = RawMessageUpdateEvent(data) message = self._get_message(raw.message_id) if message is not None: older_message = copy.copy(message) raw.cached_message = older_message self.dispatch('raw_message_edit', raw) message._update(data) # Coerce the `after` parameter to take the new updated Member # ref: #5999 older_message.author = message.author self.dispatch('message_edit', older_message, message) else: self.dispatch('raw_message_edit', raw) def parse_message_reaction_add(self, data): emoji = data['emoji'] emoji_id = utils._get_as_snowflake(emoji, 'id') emoji = PartialEmoji.with_state(self, id=emoji_id, animated=emoji.get('animated', False), name=emoji['name']) raw = RawReactionActionEvent(data, emoji, 'REACTION_ADD') member_data = data.get('member') if member_data: guild = self._get_guild(raw.guild_id) raw.member = Member(data=member_data, guild=guild, state=self) else: raw.member = None self.dispatch('raw_reaction_add', raw) # rich interface here message = self._get_message(raw.message_id) if message is not None: emoji = self._upgrade_partial_emoji(emoji) reaction = message._add_reaction(data, emoji, raw.user_id) user = raw.member or self._get_reaction_user(message.channel, raw.user_id) if user: self.dispatch('reaction_add', reaction, user) def parse_message_reaction_remove_all(self, data): raw = RawReactionClearEvent(data) self.dispatch('raw_reaction_clear', raw) message = self._get_message(raw.message_id) if message is not None: old_reactions = message.reactions.copy() message.reactions.clear() self.dispatch('reaction_clear', message, old_reactions) def parse_message_reaction_remove(self, data): emoji = data['emoji'] emoji_id = utils._get_as_snowflake(emoji, 'id') emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji['name']) raw = RawReactionActionEvent(data, emoji, 'REACTION_REMOVE') self.dispatch('raw_reaction_remove', raw) message = self._get_message(raw.message_id) if message is not None: emoji = self._upgrade_partial_emoji(emoji) try: reaction = message._remove_reaction(data, emoji, raw.user_id) except (AttributeError, ValueError): # eventual consistency lol pass else: user = self._get_reaction_user(message.channel, raw.user_id) if user: self.dispatch('reaction_remove', reaction, user) def parse_message_reaction_remove_emoji(self, data): emoji = data['emoji'] emoji_id = utils._get_as_snowflake(emoji, 'id') emoji = PartialEmoji.with_state(self, id=emoji_id, name=emoji['name']) raw = RawReactionClearEmojiEvent(data, emoji) self.dispatch('raw_reaction_clear_emoji', raw) message = self._get_message(raw.message_id) if message is not None: try: reaction = message._clear_emoji(emoji) except (AttributeError, ValueError): # eventual consistency lol pass else: if reaction: self.dispatch('reaction_clear_emoji', reaction) def parse_presence_update(self, data): guild_id = utils._get_as_snowflake(data, 'guild_id') guild = self._get_guild(guild_id) if guild is None: log.debug('PRESENCE_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id) return user = data['user'] member_id = int(user['id']) member = guild.get_member(member_id) flags = self.member_cache_flags if member is None: if 'username' not in user: # sometimes we receive 'incomplete' member data post-removal. # skip these useless cases. return member, old_member = Member._from_presence_update(guild=guild, data=data, state=self) if flags.online or (flags._online_only and member.raw_status != 'offline'): guild._add_member(member) else: old_member = Member._copy(member) user_update = member._presence_update(data=data, user=user) if user_update: self.dispatch('user_update', user_update[0], user_update[1]) if member.id != self.self_id and flags._online_only and member.raw_status == 'offline': guild._remove_member(member) self.dispatch('member_update', old_member, member) def parse_user_update(self, data): self.user._update(data) def parse_invite_create(self, data): invite = Invite.from_gateway(state=self, data=data) self.dispatch('invite_create', invite) def parse_invite_delete(self, data): invite = Invite.from_gateway(state=self, data=data) self.dispatch('invite_delete', invite) def parse_channel_delete(self, data): guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id')) channel_id = int(data['id']) if guild is not None: channel = guild.get_channel(channel_id) if channel is not None: guild._remove_channel(channel) self.dispatch('guild_channel_delete', channel) else: # the reason we're doing this is so it's also removed from the # private channel by user cache as well channel = self._get_private_channel(channel_id) if channel is not None: self._remove_private_channel(channel) self.dispatch('private_channel_delete', channel) def parse_channel_update(self, data): channel_type = try_enum(ChannelType, data.get('type')) channel_id = int(data['id']) if channel_type is ChannelType.group: channel = self._get_private_channel(channel_id) old_channel = copy.copy(channel) channel._update_group(data) self.dispatch('private_channel_update', old_channel, channel) return guild_id = utils._get_as_snowflake(data, 'guild_id') guild = self._get_guild(guild_id) if guild is not None: channel = guild.get_channel(channel_id) if channel is not None: old_channel = copy.copy(channel) channel._update(guild, data) self.dispatch('guild_channel_update', old_channel, channel) else: log.debug('CHANNEL_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id) else: log.debug('CHANNEL_UPDATE referencing an unknown guild ID: %s. Discarding.', guild_id) def parse_channel_create(self, data): factory, ch_type = _channel_factory(data['type']) if factory is None: log.debug('CHANNEL_CREATE referencing an unknown channel type %s. Discarding.', data['type']) return if ch_type in (ChannelType.group, ChannelType.private): channel_id = int(data['id']) if self._get_private_channel(channel_id) is None: channel = factory(me=self.user, data=data, state=self) self._add_private_channel(channel) self.dispatch('private_channel_create', channel) else: guild_id = utils._get_as_snowflake(data, 'guild_id') guild = self._get_guild(guild_id) if guild is not None: channel = factory(guild=guild, state=self, data=data) guild._add_channel(channel) self.dispatch('guild_channel_create', channel) else: log.debug('CHANNEL_CREATE referencing an unknown guild ID: %s. Discarding.', guild_id) return def parse_channel_pins_update(self, data): channel_id = int(data['channel_id']) channel = self.get_channel(channel_id) if channel is None: log.debug('CHANNEL_PINS_UPDATE referencing an unknown channel ID: %s. Discarding.', channel_id) return last_pin = utils.parse_time(data['last_pin_timestamp']) if data['last_pin_timestamp'] else None try: # I have not imported discord.abc in this file # the isinstance check is also 2x slower than just checking this attribute # so we're just gonna check it since it's easier and faster and lazier channel.guild except AttributeError: self.dispatch('private_channel_pins_update', channel, last_pin) else: self.dispatch('guild_channel_pins_update', channel, last_pin) def parse_channel_recipient_add(self, data): channel = self._get_private_channel(int(data['channel_id'])) user = self.store_user(data['user']) channel.recipients.append(user) self.dispatch('group_join', channel, user) def parse_channel_recipient_remove(self, data): channel = self._get_private_channel(int(data['channel_id'])) user = self.store_user(data['user']) try: channel.recipients.remove(user) except ValueError: pass else: self.dispatch('group_remove', channel, user) def parse_guild_member_add(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is None: log.debug('GUILD_MEMBER_ADD referencing an unknown guild ID: %s. Discarding.', data['guild_id']) return member = Member(guild=guild, data=data, state=self) if self.member_cache_flags.joined: guild._add_member(member) try: guild._member_count += 1 except AttributeError: pass self.dispatch('member_join', member) def parse_guild_member_remove(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is not None: try: guild._member_count -= 1 except AttributeError: pass user_id = int(data['user']['id']) member = guild.get_member(user_id) if member is not None: guild._remove_member(member) self.dispatch('member_remove', member) else: log.debug('GUILD_MEMBER_REMOVE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) def parse_guild_member_update(self, data): guild = self._get_guild(int(data['guild_id'])) user = data['user'] user_id = int(user['id']) if guild is None: log.debug('GUILD_MEMBER_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) return member = guild.get_member(user_id) if member is not None: old_member = Member._copy(member) member._update(data) user_update = member._update_inner_user(user) if user_update: self.dispatch('user_update', user_update[0], user_update[1]) self.dispatch('member_update', old_member, member) else: if self.member_cache_flags.joined: member = Member(data=data, guild=guild, state=self) # Force an update on the inner user if necessary user_update = member._update_inner_user(user) if user_update: self.dispatch('user_update', user_update[0], user_update[1]) guild._add_member(member) log.debug('GUILD_MEMBER_UPDATE referencing an unknown member ID: %s. Discarding.', user_id) def parse_guild_emojis_update(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is None: log.debug('GUILD_EMOJIS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) return before_emojis = guild.emojis for emoji in before_emojis: self._emojis.pop(emoji.id, None) guild.emojis = tuple(map(lambda d: self.store_emoji(guild, d), data['emojis'])) self.dispatch('guild_emojis_update', guild, before_emojis, guild.emojis) def _get_create_guild(self, data): if data.get('unavailable') is False: # GUILD_CREATE with unavailable in the response # usually means that the guild has become available # and is therefore in the cache guild = self._get_guild(int(data['id'])) if guild is not None: guild.unavailable = False guild._from_data(data) return guild return self._add_guild_from_data(data) def is_guild_evicted(self, guild) -> bool: return guild.id not in self._guilds async def chunk_guild(self, guild, *, wait=True, cache=None): cache = cache or self.member_cache_flags.joined request = self._chunk_requests.get(guild.id) if request is None: self._chunk_requests[guild.id] = request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache) await self.chunker(guild.id, nonce=request.nonce) if wait: return await request.wait() return request.get_future() async def _chunk_and_dispatch(self, guild, unavailable): try: await asyncio.wait_for(self.chunk_guild(guild), timeout=60.0) except asyncio.TimeoutError: log.info('Somehow timed out waiting for chunks.') if unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) def parse_guild_create(self, data): unavailable = data.get('unavailable') if unavailable is True: # joined a guild with unavailable == True so.. return guild = self._get_create_guild(data) try: # Notify the on_ready state, if any, that this guild is complete. self._ready_state.put_nowait(guild) except AttributeError: pass else: # If we're waiting for the event, put the rest on hold return # check if it requires chunking if self._guild_needs_chunking(guild): asyncio.ensure_future(self._chunk_and_dispatch(guild, unavailable), loop=self.loop) return # Dispatch available if newly available if unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) def parse_guild_sync(self, data): guild = self._get_guild(int(data['id'])) guild._sync(data) def parse_guild_update(self, data): guild = self._get_guild(int(data['id'])) if guild is not None: old_guild = copy.copy(guild) guild._from_data(data) self.dispatch('guild_update', old_guild, guild) else: log.debug('GUILD_UPDATE referencing an unknown guild ID: %s. Discarding.', data['id']) def parse_guild_delete(self, data): guild = self._get_guild(int(data['id'])) if guild is None: log.debug('GUILD_DELETE referencing an unknown guild ID: %s. Discarding.', data['id']) return if data.get('unavailable', False): # GUILD_DELETE with unavailable being True means that the # guild that was available is now currently unavailable guild.unavailable = True self.dispatch('guild_unavailable', guild) return # do a cleanup of the messages cache if self._messages is not None: self._messages = deque((msg for msg in self._messages if msg.guild != guild), maxlen=self.max_messages) self._remove_guild(guild) self.dispatch('guild_remove', guild) def parse_guild_ban_add(self, data): # we make the assumption that GUILD_BAN_ADD is done # before GUILD_MEMBER_REMOVE is called # hence we don't remove it from cache or do anything # strange with it, the main purpose of this event # is mainly to dispatch to another event worth listening to for logging guild = self._get_guild(int(data['guild_id'])) if guild is not None: try: user = User(data=data['user'], state=self) except KeyError: pass else: member = guild.get_member(user.id) or user self.dispatch('member_ban', guild, member) def parse_guild_ban_remove(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is not None and 'user' in data: user = self.store_user(data['user']) self.dispatch('member_unban', guild, user) def parse_guild_role_create(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is None: log.debug('GUILD_ROLE_CREATE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) return role_data = data['role'] role = Role(guild=guild, data=role_data, state=self) guild._add_role(role) self.dispatch('guild_role_create', role) def parse_guild_role_delete(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is not None: role_id = int(data['role_id']) try: role = guild._remove_role(role_id) except KeyError: return else: self.dispatch('guild_role_delete', role) else: log.debug('GUILD_ROLE_DELETE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) def parse_guild_role_update(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is not None: role_data = data['role'] role_id = int(role_data['id']) role = guild.get_role(role_id) if role is not None: old_role = copy.copy(role) role._update(role_data) self.dispatch('guild_role_update', old_role, role) else: log.debug('GUILD_ROLE_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) def parse_guild_members_chunk(self, data): guild_id = int(data['guild_id']) guild = self._get_guild(guild_id) presences = data.get('presences', []) members = [Member(guild=guild, data=member, state=self) for member in data.get('members', [])] log.debug('Processed a chunk for %s members in guild ID %s.', len(members), guild_id) if presences: member_dict = {str(member.id): member for member in members} for presence in presences: user = presence['user'] member_id = user['id'] member = member_dict.get(member_id) member._presence_update(presence, user) complete = data.get('chunk_index', 0) + 1 == data.get('chunk_count') self.process_chunk_requests(guild_id, data.get('nonce'), members, complete) def parse_guild_integrations_update(self, data): guild = self._get_guild(int(data['guild_id'])) if guild is not None: self.dispatch('guild_integrations_update', guild) else: log.debug('GUILD_INTEGRATIONS_UPDATE referencing an unknown guild ID: %s. Discarding.', data['guild_id']) def parse_webhooks_update(self, data): channel = self.get_channel(int(data['channel_id'])) if channel is not None: self.dispatch('webhooks_update', channel) else: log.debug('WEBHOOKS_UPDATE referencing an unknown channel ID: %s. Discarding.', data['channel_id']) def parse_voice_state_update(self, data): guild = self._get_guild(utils._get_as_snowflake(data, 'guild_id')) channel_id = utils._get_as_snowflake(data, 'channel_id') flags = self.member_cache_flags self_id = self.user.id if guild is not None: if int(data['user_id']) == self_id: voice = self._get_voice_client(guild.id) if voice is not None: coro = voice.on_voice_state_update(data) asyncio.ensure_future(logging_coroutine(coro, info='Voice Protocol voice state update handler')) member, before, after = guild._update_voice_state(data, channel_id) if member is not None: if flags.voice: if channel_id is None and flags._voice_only and member.id != self_id: # Only remove from cache iff we only have the voice flag enabled guild._remove_member(member) elif channel_id is not None: guild._add_member(member) self.dispatch('voice_state_update', member, before, after) else: log.debug('VOICE_STATE_UPDATE referencing an unknown member ID: %s. Discarding.', data['user_id']) else: # in here we're either at private or group calls call = self._calls.get(channel_id) if call is not None: call._update_voice_state(data) def parse_voice_server_update(self, data): try: key_id = int(data['guild_id']) except KeyError: key_id = int(data['channel_id']) vc = self._get_voice_client(key_id) if vc is not None: coro = vc.on_voice_server_update(data) asyncio.ensure_future(logging_coroutine(coro, info='Voice Protocol voice server update handler')) def parse_typing_start(self, data): channel, guild = self._get_guild_channel(data) if channel is not None: member = None user_id = utils._get_as_snowflake(data, 'user_id') if isinstance(channel, DMChannel): member = channel.recipient elif isinstance(channel, TextChannel) and guild is not None: member = guild.get_member(user_id) if member is None: member_data = data.get('member') if member_data: member = Member(data=member_data, state=self, guild=guild) elif isinstance(channel, GroupChannel): member = utils.find(lambda x: x.id == user_id, channel.recipients) if member is not None: timestamp = datetime.datetime.utcfromtimestamp(data.get('timestamp')) self.dispatch('typing', channel, member, timestamp) def parse_relationship_add(self, data): key = int(data['id']) old = self.user.get_relationship(key) new = Relationship(state=self, data=data) self.user._relationships[key] = new if old is not None: self.dispatch('relationship_update', old, new) else: self.dispatch('relationship_add', new) def parse_relationship_remove(self, data): key = int(data['id']) try: old = self.user._relationships.pop(key) except KeyError: pass else: self.dispatch('relationship_remove', old) def _get_reaction_user(self, channel, user_id): if isinstance(channel, TextChannel): return channel.guild.get_member(user_id) return self.get_user(user_id) def get_reaction_emoji(self, data): emoji_id = utils._get_as_snowflake(data, 'id') if not emoji_id: return data['name'] try: return self._emojis[emoji_id] except KeyError: return PartialEmoji.with_state(self, animated=data.get('animated', False), id=emoji_id, name=data['name']) def _upgrade_partial_emoji(self, emoji): emoji_id = emoji.id if not emoji_id: return emoji.name try: return self._emojis[emoji_id] except KeyError: return emoji def get_channel(self, id): if id is None: return None pm = self._get_private_channel(id) if pm is not None: return pm for guild in self.guilds: channel = guild.get_channel(id) if channel is not None: return channel def create_message(self, *, channel, data): return Message(state=self, channel=channel, data=data) class AutoShardedConnectionState(ConnectionState): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._ready_task = None self.shard_ids = () self.shards_launched = asyncio.Event() def _update_message_references(self): for msg in self._messages: if not msg.guild: continue new_guild = self._get_guild(msg.guild.id) if new_guild is not None and new_guild is not msg.guild: channel_id = msg.channel.id channel = new_guild.get_channel(channel_id) or Object(id=channel_id) msg._rebind_channel_reference(channel) async def chunker(self, guild_id, query='', limit=0, presences=False, *, shard_id=None, nonce=None): ws = self._get_websocket(guild_id, shard_id=shard_id) await ws.request_chunks(guild_id, query=query, limit=limit, presences=presences, nonce=nonce) async def _delay_ready(self): await self.shards_launched.wait() processed = [] max_concurrency = len(self.shard_ids) * 2 current_bucket = [] while True: # this snippet of code is basically waiting N seconds # until the last GUILD_CREATE was sent try: guild = await asyncio.wait_for(self._ready_state.get(), timeout=self.guild_ready_timeout) except asyncio.TimeoutError: break else: if self._guild_needs_chunking(guild): log.debug('Guild ID %d requires chunking, will be done in the background.', guild.id) if len(current_bucket) >= max_concurrency: try: await utils.sane_wait_for(current_bucket, timeout=max_concurrency * 70.0) except asyncio.TimeoutError: fmt = 'Shard ID %s failed to wait for chunks from a sub-bucket with length %d' log.warning(fmt, guild.shard_id, len(current_bucket)) finally: current_bucket = [] # Chunk the guild in the background while we wait for GUILD_CREATE streaming future = asyncio.ensure_future(self.chunk_guild(guild)) current_bucket.append(future) else: future = self.loop.create_future() future.set_result([]) processed.append((guild, future)) guilds = sorted(processed, key=lambda g: g[0].shard_id) for shard_id, info in itertools.groupby(guilds, key=lambda g: g[0].shard_id): children, futures = zip(*info) # 110 reqs/minute w/ 1 req/guild plus some buffer timeout = 61 * (len(children) / 110) try: await utils.sane_wait_for(futures, timeout=timeout) except asyncio.TimeoutError: log.warning('Shard ID %s failed to wait for chunks (timeout=%.2f) for %d guilds', shard_id, timeout, len(guilds)) for guild in children: if guild.unavailable is False: self.dispatch('guild_available', guild) else: self.dispatch('guild_join', guild) self.dispatch('shard_ready', shard_id) # remove the state try: del self._ready_state except AttributeError: pass # already been deleted somehow # regular users cannot shard so we won't worry about it here. # clear the current task self._ready_task = None # dispatch the event self.call_handlers('ready') self.dispatch('ready') def parse_ready(self, data): if not hasattr(self, '_ready_state'): self._ready_state = asyncio.Queue() self.user = user = ClientUser(state=self, data=data['user']) self._users[user.id] = user for guild_data in data['guilds']: self._add_guild_from_data(guild_data) if self._messages: self._update_message_references() for pm in data.get('private_channels', []): factory, _ = _channel_factory(pm['type']) self._add_private_channel(factory(me=user, data=pm, state=self)) self.dispatch('connect') self.dispatch('shard_connect', data['__shard_id__']) # Much like clear(), if we have a massive deallocation # then it's better to explicitly call the GC # Note that in the original ready parsing code this was done # implicitly via clear() but in the auto sharded client clearing # the cache would have the consequence of clearing data on other # shards as well. gc.collect() if self._ready_task is None: self._ready_task = asyncio.ensure_future(self._delay_ready(), loop=self.loop) def parse_resumed(self, data): self.dispatch('resumed') self.dispatch('shard_resumed', data['__shard_id__'])
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/state.py
state.py
import datetime from . import utils from .enums import VoiceRegion, try_enum from .member import VoiceState class CallMessage: """Represents a group call message from Discord. This is only received in cases where the message type is equivalent to :attr:`MessageType.call`. .. deprecated:: 1.7 Attributes ----------- ended_timestamp: Optional[:class:`datetime.datetime`] A naive UTC datetime object that represents the time that the call has ended. participants: List[:class:`User`] The list of users that are participating in this call. message: :class:`Message` The message associated with this call message. """ def __init__(self, message, **kwargs): self.message = message self.ended_timestamp = utils.parse_time(kwargs.get('ended_timestamp')) self.participants = kwargs.get('participants') @property def call_ended(self): """:class:`bool`: Indicates if the call has ended. .. deprecated:: 1.7 """ return self.ended_timestamp is not None @property def channel(self): r""":class:`GroupChannel`\: The private channel associated with this message. .. deprecated:: 1.7 """ return self.message.channel @property def duration(self): """Queries the duration of the call. If the call has not ended then the current duration will be returned. .. deprecated:: 1.7 Returns --------- :class:`datetime.timedelta` The timedelta object representing the duration. """ if self.ended_timestamp is None: return datetime.datetime.utcnow() - self.message.created_at else: return self.ended_timestamp - self.message.created_at class GroupCall: """Represents the actual group call from Discord. This is accompanied with a :class:`CallMessage` denoting the information. .. deprecated:: 1.7 Attributes ----------- call: :class:`CallMessage` The call message associated with this group call. unavailable: :class:`bool` Denotes if this group call is unavailable. ringing: List[:class:`User`] A list of users that are currently being rung to join the call. region: :class:`VoiceRegion` The guild region the group call is being hosted on. """ def __init__(self, **kwargs): self.call = kwargs.get('call') self.unavailable = kwargs.get('unavailable') self._voice_states = {} for state in kwargs.get('voice_states', []): self._update_voice_state(state) self._update(**kwargs) def _update(self, **kwargs): self.region = try_enum(VoiceRegion, kwargs.get('region')) lookup = {u.id: u for u in self.call.channel.recipients} me = self.call.channel.me lookup[me.id] = me self.ringing = list(filter(None, map(lookup.get, kwargs.get('ringing', [])))) def _update_voice_state(self, data): user_id = int(data['user_id']) # left the voice channel? if data['channel_id'] is None: self._voice_states.pop(user_id, None) else: self._voice_states[user_id] = VoiceState(data=data, channel=self.channel) @property def connected(self): """List[:class:`User`]: A property that returns all users that are currently in this call. .. deprecated:: 1.7 """ ret = [u for u in self.channel.recipients if self.voice_state_for(u) is not None] me = self.channel.me if self.voice_state_for(me) is not None: ret.append(me) return ret @property def channel(self): r""":class:`GroupChannel`\: Returns the channel the group call is in. .. deprecated:: 1.7 """ return self.call.channel @utils.deprecated() def voice_state_for(self, user): """Retrieves the :class:`VoiceState` for a specified :class:`User`. If the :class:`User` has no voice state then this function returns ``None``. .. deprecated:: 1.7 Parameters ------------ user: :class:`User` The user to retrieve the voice state for. Returns -------- Optional[:class:`VoiceState`] The voice state associated with this user. """ return self._voice_states.get(user.id)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/calls.py
calls.py
import asyncio import itertools import logging import aiohttp from .state import AutoShardedConnectionState from .client import Client from .backoff import ExponentialBackoff from .gateway import * from .errors import ( ClientException, InvalidArgument, HTTPException, GatewayNotFound, ConnectionClosed, PrivilegedIntentsRequired, ) from . import utils from .enums import Status log = logging.getLogger(__name__) class EventType: close = 0 reconnect = 1 resume = 2 identify = 3 terminate = 4 clean_close = 5 class EventItem: __slots__ = ('type', 'shard', 'error') def __init__(self, etype, shard, error): self.type = etype self.shard = shard self.error = error def __lt__(self, other): if not isinstance(other, EventItem): return NotImplemented return self.type < other.type def __eq__(self, other): if not isinstance(other, EventItem): return NotImplemented return self.type == other.type def __hash__(self): return hash(self.type) class Shard: def __init__(self, ws, client, queue_put): self.ws = ws self._client = client self._dispatch = client.dispatch self._queue_put = queue_put self.loop = self._client.loop self._disconnect = False self._reconnect = client._reconnect self._backoff = ExponentialBackoff() self._task = None self._handled_exceptions = ( OSError, HTTPException, GatewayNotFound, ConnectionClosed, aiohttp.ClientError, asyncio.TimeoutError, ) @property def id(self): return self.ws.shard_id def launch(self): self._task = self.loop.create_task(self.worker()) def _cancel_task(self): if self._task is not None and not self._task.done(): self._task.cancel() async def close(self): self._cancel_task() await self.ws.close(code=1000) async def disconnect(self): await self.close() self._dispatch('shard_disconnect', self.id) async def _handle_disconnect(self, e): self._dispatch('disconnect') self._dispatch('shard_disconnect', self.id) if not self._reconnect: self._queue_put(EventItem(EventType.close, self, e)) return if self._client.is_closed(): return if isinstance(e, OSError) and e.errno in (54, 10054): # If we get Connection reset by peer then always try to RESUME the connection. exc = ReconnectWebSocket(self.id, resume=True) self._queue_put(EventItem(EventType.resume, self, exc)) return if isinstance(e, ConnectionClosed): if e.code == 4014: self._queue_put(EventItem(EventType.terminate, self, PrivilegedIntentsRequired(self.id))) return if e.code != 1000: self._queue_put(EventItem(EventType.close, self, e)) return retry = self._backoff.delay() log.error('Attempting a reconnect for shard ID %s in %.2fs', self.id, retry, exc_info=e) await asyncio.sleep(retry) self._queue_put(EventItem(EventType.reconnect, self, e)) async def worker(self): while not self._client.is_closed(): try: await self.ws.poll_event() except ReconnectWebSocket as e: etype = EventType.resume if e.resume else EventType.identify self._queue_put(EventItem(etype, self, e)) break except self._handled_exceptions as e: await self._handle_disconnect(e) break except asyncio.CancelledError: break except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) break async def reidentify(self, exc): self._cancel_task() self._dispatch('disconnect') self._dispatch('shard_disconnect', self.id) log.info('Got a request to %s the websocket at Shard ID %s.', exc.op, self.id) try: coro = DiscordWebSocket.from_client(self._client, resume=exc.resume, shard_id=self.id, session=self.ws.session_id, sequence=self.ws.sequence) self.ws = await asyncio.wait_for(coro, timeout=60.0) except self._handled_exceptions as e: await self._handle_disconnect(e) except asyncio.CancelledError: return except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) else: self.launch() async def reconnect(self): self._cancel_task() try: coro = DiscordWebSocket.from_client(self._client, shard_id=self.id) self.ws = await asyncio.wait_for(coro, timeout=60.0) except self._handled_exceptions as e: await self._handle_disconnect(e) except asyncio.CancelledError: return except Exception as e: self._queue_put(EventItem(EventType.terminate, self, e)) else: self.launch() class ShardInfo: """A class that gives information and control over a specific shard. You can retrieve this object via :meth:`AutoShardedClient.get_shard` or :attr:`AutoShardedClient.shards`. .. versionadded:: 1.4 Attributes ------------ id: :class:`int` The shard ID for this shard. shard_count: Optional[:class:`int`] The shard count for this cluster. If this is ``None`` then the bot has not started yet. """ __slots__ = ('_parent', 'id', 'shard_count') def __init__(self, parent, shard_count): self._parent = parent self.id = parent.id self.shard_count = shard_count def is_closed(self): """:class:`bool`: Whether the shard connection is currently closed.""" return not self._parent.ws.open async def disconnect(self): """|coro| Disconnects a shard. When this is called, the shard connection will no longer be open. If the shard is already disconnected this does nothing. """ if self.is_closed(): return await self._parent.disconnect() async def reconnect(self): """|coro| Disconnects and then connects the shard again. """ if not self.is_closed(): await self._parent.disconnect() await self._parent.reconnect() async def connect(self): """|coro| Connects a shard. If the shard is already connected this does nothing. """ if not self.is_closed(): return await self._parent.reconnect() @property def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.""" return self._parent.ws.latency def is_ws_ratelimited(self): """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. .. versionadded:: 1.6 """ return self._parent.ws.is_ratelimited() class AutoShardedClient(Client): """A client similar to :class:`Client` except it handles the complications of sharding for the user into a more manageable and transparent single process bot. When using this client, you will be able to use it as-if it was a regular :class:`Client` with a single shard when implementation wise internally it is split up into multiple shards. This allows you to not have to deal with IPC or other complicated infrastructure. It is recommended to use this client only if you have surpassed at least 1000 guilds. If no :attr:`.shard_count` is provided, then the library will use the Bot Gateway endpoint call to figure out how many shards to use. If a ``shard_ids`` parameter is given, then those shard IDs will be used to launch the internal shards. Note that :attr:`.shard_count` must be provided if this is used. By default, when omitted, the client will launch shards from 0 to ``shard_count - 1``. Attributes ------------ shard_ids: Optional[List[:class:`int`]] An optional list of shard_ids to launch the shards with. """ def __init__(self, *args, loop=None, **kwargs): kwargs.pop('shard_id', None) self.shard_ids = kwargs.pop('shard_ids', None) super().__init__(*args, loop=loop, **kwargs) if self.shard_ids is not None: if self.shard_count is None: raise ClientException('When passing manual shard_ids, you must provide a shard_count.') elif not isinstance(self.shard_ids, (list, tuple)): raise ClientException('shard_ids parameter must be a list or a tuple.') # instead of a single websocket, we have multiple # the key is the shard_id self.__shards = {} self._connection._get_websocket = self._get_websocket self._connection._get_client = lambda: self self.__queue = asyncio.PriorityQueue() def _get_websocket(self, guild_id=None, *, shard_id=None): if shard_id is None: shard_id = (guild_id >> 22) % self.shard_count return self.__shards[shard_id].ws def _get_state(self, **options): return AutoShardedConnectionState(dispatch=self.dispatch, handlers=self._handlers, syncer=self._syncer, hooks=self._hooks, http=self.http, loop=self.loop, **options) @property def latency(self): """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This operates similarly to :meth:`Client.latency` except it uses the average latency of every shard's latency. To get a list of shard latency, check the :attr:`latencies` property. Returns ``nan`` if there are no shards ready. """ if not self.__shards: return float('nan') return sum(latency for _, latency in self.latencies) / len(self.__shards) @property def latencies(self): """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.__shards.items()] def get_shard(self, shard_id): """Optional[:class:`ShardInfo`]: Gets the shard information at a given shard ID or ``None`` if not found.""" try: parent = self.__shards[shard_id] except KeyError: return None else: return ShardInfo(parent, self.shard_count) @property def shards(self): """Mapping[int, :class:`ShardInfo`]: Returns a mapping of shard IDs to their respective info object.""" return { shard_id: ShardInfo(parent, self.shard_count) for shard_id, parent in self.__shards.items() } @utils.deprecated('Guild.chunk') async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter set to ``False``. When the client logs on and connects to the websocket, Discord does not provide the library with offline members if the number of members in the guild is larger than 250. You can check if a guild is large if :attr:`Guild.large` is ``True``. .. warning:: This method is deprecated. Use :meth:`Guild.chunk` instead. Parameters ----------- \*guilds: :class:`Guild` An argument list of guilds to request offline members for. Raises ------- InvalidArgument If any guild is unavailable in the collection. """ if any(g.unavailable for g in guilds): raise InvalidArgument('An unavailable or non-large guild was passed.') _guilds = sorted(guilds, key=lambda g: g.shard_id) for shard_id, sub_guilds in itertools.groupby(_guilds, key=lambda g: g.shard_id): for guild in sub_guilds: await self._connection.chunk_guild(guild) async def launch_shard(self, gateway, shard_id, *, initial=False): try: coro = DiscordWebSocket.from_client(self, initial=initial, gateway=gateway, shard_id=shard_id) ws = await asyncio.wait_for(coro, timeout=180.0) except Exception: log.exception('Failed to connect for shard_id: %s. Retrying...', shard_id) await asyncio.sleep(5.0) return await self.launch_shard(gateway, shard_id) # keep reading the shard while others connect self.__shards[shard_id] = ret = Shard(ws, self, self.__queue.put_nowait) ret.launch() async def launch_shards(self): if self.shard_count is None: self.shard_count, gateway = await self.http.get_bot_gateway() else: gateway = await self.http.get_gateway() self._connection.shard_count = self.shard_count shard_ids = self.shard_ids or range(self.shard_count) self._connection.shard_ids = shard_ids for shard_id in shard_ids: initial = shard_id == shard_ids[0] await self.launch_shard(gateway, shard_id, initial=initial) self._connection.shards_launched.set() async def connect(self, *, reconnect=True): self._reconnect = reconnect await self.launch_shards() while not self.is_closed(): item = await self.__queue.get() if item.type == EventType.close: await self.close() if isinstance(item.error, ConnectionClosed): if item.error.code != 1000: raise item.error if item.error.code == 4014: raise PrivilegedIntentsRequired(item.shard.id) from None return elif item.type in (EventType.identify, EventType.resume): await item.shard.reidentify(item.error) elif item.type == EventType.reconnect: await item.shard.reconnect() elif item.type == EventType.terminate: await self.close() raise item.error elif item.type == EventType.clean_close: return async def close(self): """|coro| Closes the connection to Discord. """ if self.is_closed(): return self._closed = True for vc in self.voice_clients: try: await vc.disconnect() except Exception: pass to_close = [asyncio.ensure_future(shard.close(), loop=self.loop) for shard in self.__shards.values()] if to_close: await asyncio.wait(to_close) await self.http.close() self.__queue.put_nowait(EventItem(EventType.clean_close, None, None)) async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None): """|coro| Changes the client's presence. Example: :: game = discord.Game("with the API") await client.change_presence(status=discord.Status.idle, activity=game) Parameters ---------- activity: Optional[:class:`BaseActivity`] The activity being done. ``None`` if no currently active activity is done. status: Optional[:class:`Status`] Indicates what status to change to. If ``None``, then :attr:`Status.online` is used. afk: :class:`bool` Indicates if you are going AFK. This allows the discord client to know how to handle push notifications better for you in case you are actually idle and not lying. shard_id: Optional[:class:`int`] The shard_id to change the presence to. If not specified or ``None``, then it will change the presence of every shard the bot can see. Raises ------ InvalidArgument If the ``activity`` parameter is not of proper type. """ if status is None: status = 'online' status_enum = Status.online elif status is Status.offline: status = 'invisible' status_enum = Status.offline else: status_enum = status status = str(status) if shard_id is None: for shard in self.__shards.values(): await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = self._connection.guilds else: shard = self.__shards[shard_id] await shard.ws.change_presence(activity=activity, status=status, afk=afk) guilds = [g for g in self._connection.guilds if g.shard_id == shard_id] activities = () if activity is None else (activity,) for guild in guilds: me = guild.me if me is None: continue me.activities = activities me.status = status_enum def is_ws_ratelimited(self): """:class:`bool`: Whether the websocket is currently rate limited. This can be useful to know when deciding whether you should query members using HTTP or via the gateway. This implementation checks if any of the shards are rate limited. For more granular control, consider :meth:`ShardInfo.is_ws_ratelimited`. .. versionadded:: 1.6 """ return any(shard.ws.is_ratelimited() for shard in self.__shards.values())
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/shard.py
shard.py
from .enums import UserFlags __all__ = ( 'SystemChannelFlags', 'MessageFlags', 'PublicUserFlags', 'Intents', 'MemberCacheFlags', ) class flag_value: def __init__(self, func): self.flag = func(None) self.__doc__ = func.__doc__ def __get__(self, instance, owner): if instance is None: return self return instance._has_flag(self.flag) def __set__(self, instance, value): instance._set_flag(self.flag, value) def __repr__(self): return '<flag_value flag={.flag!r}>'.format(self) class alias_flag_value(flag_value): pass def fill_with_flags(*, inverted=False): def decorator(cls): cls.VALID_FLAGS = { name: value.flag for name, value in cls.__dict__.items() if isinstance(value, flag_value) } if inverted: max_bits = max(cls.VALID_FLAGS.values()).bit_length() cls.DEFAULT_VALUE = -1 + (2 ** max_bits) else: cls.DEFAULT_VALUE = 0 return cls return decorator # n.b. flags must inherit from this and use the decorator above class BaseFlags: __slots__ = ('value',) def __init__(self, **kwargs): self.value = self.DEFAULT_VALUE for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError('%r is not a valid flag name.' % key) setattr(self, key, value) @classmethod def _from_value(cls, value): self = cls.__new__(cls) self.value = value return self def __eq__(self, other): return isinstance(other, self.__class__) and self.value == other.value def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.value) def __repr__(self): return '<%s value=%s>' % (self.__class__.__name__, self.value) def __iter__(self): for name, value in self.__class__.__dict__.items(): if isinstance(value, alias_flag_value): continue if isinstance(value, flag_value): yield (name, self._has_flag(value.flag)) def _has_flag(self, o): return (self.value & o) == o def _set_flag(self, o, toggle): if toggle is True: self.value |= o elif toggle is False: self.value &= ~o else: raise TypeError('Value to set for %s must be a bool.' % self.__class__.__name__) @fill_with_flags(inverted=True) class SystemChannelFlags(BaseFlags): r"""Wraps up a Discord system channel flag value. Similar to :class:`Permissions`\, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit the system flags easily. To construct an object you can pass keyword arguments denoting the flags to enable or disable. .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () # For some reason the flags for system channels are "inverted" # ergo, if they're set then it means "suppress" (off in the GUI toggle) # Since this is counter-intuitive from an API perspective and annoying # these will be inverted automatically def _has_flag(self, o): return (self.value & o) != o def _set_flag(self, o, toggle): if toggle is True: self.value &= ~o elif toggle is False: self.value |= o else: raise TypeError('Value to set for SystemChannelFlags must be a bool.') @flag_value def join_notifications(self): """:class:`bool`: Returns ``True`` if the system channel is used for member join notifications.""" return 1 @flag_value def premium_subscriptions(self): """:class:`bool`: Returns ``True`` if the system channel is used for Nitro boosting notifications.""" return 2 @fill_with_flags() class MessageFlags(BaseFlags): r"""Wraps up a Discord Message flag value. See :class:`SystemChannelFlags`. .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. .. versionadded:: 1.3 Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () @flag_value def crossposted(self): """:class:`bool`: Returns ``True`` if the message is the original crossposted message.""" return 1 @flag_value def is_crossposted(self): """:class:`bool`: Returns ``True`` if the message was crossposted from another channel.""" return 2 @flag_value def suppress_embeds(self): """:class:`bool`: Returns ``True`` if the message's embeds have been suppressed.""" return 4 @flag_value def source_message_deleted(self): """:class:`bool`: Returns ``True`` if the source message for this crosspost has been deleted.""" return 8 @flag_value def urgent(self): """:class:`bool`: Returns ``True`` if the source message is an urgent message. An urgent message is one sent by Discord Trust and Safety. """ return 16 @fill_with_flags() class PublicUserFlags(BaseFlags): r"""Wraps up the Discord User Public flags. .. container:: operations .. describe:: x == y Checks if two PublicUserFlags are equal. .. describe:: x != y Checks if two PublicUserFlags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown. .. versionadded:: 1.4 Attributes ----------- value: :class:`int` The raw value. This value is a bit array field of a 53-bit integer representing the currently available flags. You should query flags via the properties rather than using this raw value. """ __slots__ = () @flag_value def staff(self): """:class:`bool`: Returns ``True`` if the user is a Discord Employee.""" return UserFlags.staff.value @flag_value def partner(self): """:class:`bool`: Returns ``True`` if the user is a Discord Partner.""" return UserFlags.partner.value @flag_value def hypesquad(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Events member.""" return UserFlags.hypesquad.value @flag_value def bug_hunter(self): """:class:`bool`: Returns ``True`` if the user is a Bug Hunter""" return UserFlags.bug_hunter.value @flag_value def hypesquad_bravery(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Bravery member.""" return UserFlags.hypesquad_bravery.value @flag_value def hypesquad_brilliance(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Brilliance member.""" return UserFlags.hypesquad_brilliance.value @flag_value def hypesquad_balance(self): """:class:`bool`: Returns ``True`` if the user is a HypeSquad Balance member.""" return UserFlags.hypesquad_balance.value @flag_value def early_supporter(self): """:class:`bool`: Returns ``True`` if the user is an Early Supporter.""" return UserFlags.early_supporter.value @flag_value def team_user(self): """:class:`bool`: Returns ``True`` if the user is a Team User.""" return UserFlags.team_user.value @flag_value def system(self): """:class:`bool`: Returns ``True`` if the user is a system user (i.e. represents Discord officially).""" return UserFlags.system.value @flag_value def bug_hunter_level_2(self): """:class:`bool`: Returns ``True`` if the user is a Bug Hunter Level 2""" return UserFlags.bug_hunter_level_2.value @flag_value def verified_bot(self): """:class:`bool`: Returns ``True`` if the user is a Verified Bot.""" return UserFlags.verified_bot.value @flag_value def verified_bot_developer(self): """:class:`bool`: Returns ``True`` if the user is an Early Verified Bot Developer.""" return UserFlags.verified_bot_developer.value @alias_flag_value def early_verified_bot_developer(self): """:class:`bool`: An alias for :attr:`verified_bot_developer`. .. versionadded:: 1.5 """ return UserFlags.verified_bot_developer.value def all(self): """List[:class:`UserFlags`]: Returns all public flags the user has.""" return [public_flag for public_flag in UserFlags if self._has_flag(public_flag.value)] @fill_with_flags() class Intents(BaseFlags): r"""Wraps up a Discord gateway intent flag. Similar to :class:`Permissions`\, the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. To construct an object you can pass keyword arguments denoting the flags to enable or disable. This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the ``intents`` keyword argument of :class:`Client`. .. versionadded:: 1.5 .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ __slots__ = () def __init__(self, **kwargs): self.value = self.DEFAULT_VALUE for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError('%r is not a valid flag name.' % key) setattr(self, key, value) @classmethod def all(cls): """A factory method that creates a :class:`Intents` with everything enabled.""" bits = max(cls.VALID_FLAGS.values()).bit_length() value = (1 << bits) - 1 self = cls.__new__(cls) self.value = value return self @classmethod def none(cls): """A factory method that creates a :class:`Intents` with everything disabled.""" self = cls.__new__(cls) self.value = self.DEFAULT_VALUE return self @classmethod def default(cls): """A factory method that creates a :class:`Intents` with everything enabled except :attr:`presences` and :attr:`members`. """ self = cls.all() self.presences = False self.members = False return self @flag_value def guilds(self): """:class:`bool`: Whether guild related events are enabled. This corresponds to the following events: - :func:`on_guild_join` - :func:`on_guild_remove` - :func:`on_guild_available` - :func:`on_guild_unavailable` - :func:`on_guild_channel_update` - :func:`on_guild_channel_create` - :func:`on_guild_channel_delete` - :func:`on_guild_channel_pins_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`Client.guilds` - :class:`Guild` and all its attributes. - :meth:`Client.get_channel` - :meth:`Client.get_all_channels` It is highly advisable to leave this intent enabled for your bot to function. """ return 1 << 0 @flag_value def members(self): """:class:`bool`: Whether guild member related events are enabled. This corresponds to the following events: - :func:`on_member_join` - :func:`on_member_remove` - :func:`on_member_update` (nickname, roles) - :func:`on_user_update` This also corresponds to the following attributes and classes in terms of cache: - :meth:`Client.get_all_members` - :meth:`Guild.chunk` - :meth:`Guild.fetch_members` - :meth:`Guild.get_member` - :attr:`Guild.members` - :attr:`Member.roles` - :attr:`Member.nick` - :attr:`Member.premium_since` - :attr:`User.name` - :attr:`User.avatar` (:attr:`User.avatar_url` and :meth:`User.avatar_url_as`) - :attr:`User.discriminator` For more information go to the :ref:`member intent documentation <need_members_intent>`. .. note:: Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. """ return 1 << 1 @flag_value def bans(self): """:class:`bool`: Whether guild ban related events are enabled. This corresponds to the following events: - :func:`on_member_ban` - :func:`on_member_unban` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 2 @flag_value def emojis(self): """:class:`bool`: Whether guild emoji related events are enabled. This corresponds to the following events: - :func:`on_guild_emojis_update` This also corresponds to the following attributes and classes in terms of cache: - :class:`Emoji` - :meth:`Client.get_emoji` - :meth:`Client.emojis` - :attr:`Guild.emojis` """ return 1 << 3 @flag_value def integrations(self): """:class:`bool`: Whether guild integration related events are enabled. This corresponds to the following events: - :func:`on_guild_integrations_update` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 4 @flag_value def webhooks(self): """:class:`bool`: Whether guild webhook related events are enabled. This corresponds to the following events: - :func:`on_webhooks_update` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 5 @flag_value def invites(self): """:class:`bool`: Whether guild invite related events are enabled. This corresponds to the following events: - :func:`on_invite_create` - :func:`on_invite_delete` This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 6 @flag_value def voice_states(self): """:class:`bool`: Whether guild voice state related events are enabled. This corresponds to the following events: - :func:`on_voice_state_update` This also corresponds to the following attributes and classes in terms of cache: - :attr:`VoiceChannel.members` - :attr:`VoiceChannel.voice_states` - :attr:`Member.voice` """ return 1 << 7 @flag_value def presences(self): """:class:`bool`: Whether guild presence related events are enabled. This corresponds to the following events: - :func:`on_member_update` (activities, status) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Member.activities` - :attr:`Member.status` - :attr:`Member.raw_status` For more information go to the :ref:`presence intent documentation <need_presence_intent>`. .. note:: Currently, this requires opting in explicitly via the developer portal as well. Bots in over 100 guilds will need to apply to Discord for verification. """ return 1 << 8 @alias_flag_value def messages(self): """:class:`bool`: Whether guild and direct message related events are enabled. This is a shortcut to set or get both :attr:`guild_messages` and :attr:`dm_messages`. This corresponds to the following events: - :func:`on_message` (both guilds and DMs) - :func:`on_message_edit` (both guilds and DMs) - :func:`on_message_delete` (both guilds and DMs) - :func:`on_raw_message_delete` (both guilds and DMs) - :func:`on_raw_message_edit` (both guilds and DMs) - :func:`on_private_channel_create` This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (both guilds and DMs) - :func:`on_reaction_remove` (both guilds and DMs) - :func:`on_reaction_clear` (both guilds and DMs) """ return (1 << 9) | (1 << 12) @flag_value def guild_messages(self): """:class:`bool`: Whether guild message related events are enabled. See also :attr:`dm_messages` for DMs or :attr:`messages` for both. This corresponds to the following events: - :func:`on_message` (only for guilds) - :func:`on_message_edit` (only for guilds) - :func:`on_message_delete` (only for guilds) - :func:`on_raw_message_delete` (only for guilds) - :func:`on_raw_message_edit` (only for guilds) This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` (only for guilds) Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (only for guilds) - :func:`on_reaction_remove` (only for guilds) - :func:`on_reaction_clear` (only for guilds) """ return 1 << 9 @flag_value def dm_messages(self): """:class:`bool`: Whether direct message related events are enabled. See also :attr:`guild_messages` for guilds or :attr:`messages` for both. This corresponds to the following events: - :func:`on_message` (only for DMs) - :func:`on_message_edit` (only for DMs) - :func:`on_message_delete` (only for DMs) - :func:`on_raw_message_delete` (only for DMs) - :func:`on_raw_message_edit` (only for DMs) - :func:`on_private_channel_create` This also corresponds to the following attributes and classes in terms of cache: - :class:`Message` - :attr:`Client.cached_messages` (only for DMs) Note that due to an implicit relationship this also corresponds to the following events: - :func:`on_reaction_add` (only for DMs) - :func:`on_reaction_remove` (only for DMs) - :func:`on_reaction_clear` (only for DMs) """ return 1 << 12 @alias_flag_value def reactions(self): """:class:`bool`: Whether guild and direct message reaction related events are enabled. This is a shortcut to set or get both :attr:`guild_reactions` and :attr:`dm_reactions`. This corresponds to the following events: - :func:`on_reaction_add` (both guilds and DMs) - :func:`on_reaction_remove` (both guilds and DMs) - :func:`on_reaction_clear` (both guilds and DMs) - :func:`on_raw_reaction_add` (both guilds and DMs) - :func:`on_raw_reaction_remove` (both guilds and DMs) - :func:`on_raw_reaction_clear` (both guilds and DMs) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (both guild and DM messages) """ return (1 << 10) | (1 << 13) @flag_value def guild_reactions(self): """:class:`bool`: Whether guild message reaction related events are enabled. See also :attr:`dm_reactions` for DMs or :attr:`reactions` for both. This corresponds to the following events: - :func:`on_reaction_add` (only for guilds) - :func:`on_reaction_remove` (only for guilds) - :func:`on_reaction_clear` (only for guilds) - :func:`on_raw_reaction_add` (only for guilds) - :func:`on_raw_reaction_remove` (only for guilds) - :func:`on_raw_reaction_clear` (only for guilds) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (only for guild messages) """ return 1 << 10 @flag_value def dm_reactions(self): """:class:`bool`: Whether direct message reaction related events are enabled. See also :attr:`guild_reactions` for guilds or :attr:`reactions` for both. This corresponds to the following events: - :func:`on_reaction_add` (only for DMs) - :func:`on_reaction_remove` (only for DMs) - :func:`on_reaction_clear` (only for DMs) - :func:`on_raw_reaction_add` (only for DMs) - :func:`on_raw_reaction_remove` (only for DMs) - :func:`on_raw_reaction_clear` (only for DMs) This also corresponds to the following attributes and classes in terms of cache: - :attr:`Message.reactions` (only for DM messages) """ return 1 << 13 @alias_flag_value def typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. This is a shortcut to set or get both :attr:`guild_typing` and :attr:`dm_typing`. This corresponds to the following events: - :func:`on_typing` (both guilds and DMs) This does not correspond to any attributes or classes in the library in terms of cache. """ return (1 << 11) | (1 << 14) @flag_value def guild_typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. See also :attr:`dm_typing` for DMs or :attr:`typing` for both. This corresponds to the following events: - :func:`on_typing` (only for guilds) This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 11 @flag_value def dm_typing(self): """:class:`bool`: Whether guild and direct message typing related events are enabled. See also :attr:`guild_typing` for guilds or :attr:`typing` for both. This corresponds to the following events: - :func:`on_typing` (only for DMs) This does not correspond to any attributes or classes in the library in terms of cache. """ return 1 << 14 @fill_with_flags() class MemberCacheFlags(BaseFlags): """Controls the library's cache policy when it comes to members. This allows for finer grained control over what members are cached. Note that the bot's own member is always cached. This class is passed to the ``member_cache_flags`` parameter in :class:`Client`. Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have :attr:`Intents.members` enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself. To construct an object you can pass keyword arguments denoting the flags to enable or disable. The default value is all flags enabled. .. versionadded:: 1.5 .. container:: operations .. describe:: x == y Checks if two flags are equal. .. describe:: x != y Checks if two flags are not equal. .. describe:: hash(x) Return the flag's hash. .. describe:: iter(x) Returns an iterator of ``(name, value)`` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Attributes ----------- value: :class:`int` The raw value. You should query flags via the properties rather than using this raw value. """ __slots__ = () def __init__(self, **kwargs): bits = max(self.VALID_FLAGS.values()).bit_length() self.value = (1 << bits) - 1 for key, value in kwargs.items(): if key not in self.VALID_FLAGS: raise TypeError('%r is not a valid flag name.' % key) setattr(self, key, value) @classmethod def all(cls): """A factory method that creates a :class:`MemberCacheFlags` with everything enabled.""" bits = max(cls.VALID_FLAGS.values()).bit_length() value = (1 << bits) - 1 self = cls.__new__(cls) self.value = value return self @classmethod def none(cls): """A factory method that creates a :class:`MemberCacheFlags` with everything disabled.""" self = cls.__new__(cls) self.value = self.DEFAULT_VALUE return self @property def _empty(self): return self.value == self.DEFAULT_VALUE @flag_value def online(self): """:class:`bool`: Whether to cache members with a status. For example, members that are part of the initial ``GUILD_CREATE`` or become online at a later point. This requires :attr:`Intents.presences`. Members that go offline are no longer cached. """ return 1 @flag_value def voice(self): """:class:`bool`: Whether to cache members that are in voice. This requires :attr:`Intents.voice_states`. Members that leave voice are no longer cached. """ return 2 @flag_value def joined(self): """:class:`bool`: Whether to cache members that joined the guild or are chunked as part of the initial log in flow. This requires :attr:`Intents.members`. Members that leave the guild are no longer cached. """ return 4 @classmethod def from_intents(cls, intents): """A factory method that creates a :class:`MemberCacheFlags` based on the currently selected :class:`Intents`. Parameters ------------ intents: :class:`Intents` The intents to select from. Returns --------- :class:`MemberCacheFlags` The resulting member cache flags. """ self = cls.none() if intents.members: self.joined = True if intents.presences: self.online = True if intents.voice_states: self.voice = True if not self.joined and self.online and self.voice: self.voice = False return self def _verify_intents(self, intents): if self.online and not intents.presences: raise ValueError('MemberCacheFlags.online requires Intents.presences enabled') if self.voice and not intents.voice_states: raise ValueError('MemberCacheFlags.voice requires Intents.voice_states') if self.joined and not intents.members: raise ValueError('MemberCacheFlags.joined requires Intents.members') if not self.joined and self.voice and self.online: msg = 'Setting both MemberCacheFlags.voice and MemberCacheFlags.online requires MemberCacheFlags.joined ' \ 'to properly evict members from the cache.' raise ValueError(msg) @property def _voice_only(self): return self.value == 2 @property def _online_only(self): return self.value == 1
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/flags.py
flags.py
from .asset import Asset from . import utils class _EmojiTag: __slots__ = () class PartialEmoji(_EmojiTag): """Represents a "partial" emoji. This model will be given in two scenarios: - "Raw" data events such as :func:`on_raw_reaction_add` - Custom emoji that the bot cannot see from e.g. :attr:`Message.reactions` .. container:: operations .. describe:: x == y Checks if two emoji are the same. .. describe:: x != y Checks if two emoji are not the same. .. describe:: hash(x) Return the emoji's hash. .. describe:: str(x) Returns the emoji rendered for discord. Attributes ----------- name: Optional[:class:`str`] The custom emoji name, if applicable, or the unicode codepoint of the non-custom emoji. This can be ``None`` if the emoji got deleted (e.g. removing a reaction with a deleted emoji). animated: :class:`bool` Whether the emoji is animated or not. id: Optional[:class:`int`] The ID of the custom emoji, if applicable. """ __slots__ = ('animated', 'name', 'id', '_state') def __init__(self, *, name, animated=False, id=None): self.animated = animated self.name = name self.id = id self._state = None @classmethod def from_dict(cls, data): return cls( animated=data.get('animated', False), id=utils._get_as_snowflake(data, 'id'), name=data.get('name'), ) def to_dict(self): o = { 'name': self.name } if self.id: o['id'] = self.id if self.animated: o['animated'] = self.animated return o @classmethod def with_state(cls, state, *, name, animated=False, id=None): self = cls(name=name, animated=animated, id=id) self._state = state return self def __str__(self): if self.id is None: return self.name if self.animated: return '<a:%s:%s>' % (self.name, self.id) return '<:%s:%s>' % (self.name, self.id) def __repr__(self): return '<{0.__class__.__name__} animated={0.animated} name={0.name!r} id={0.id}>'.format(self) def __eq__(self, other): if self.is_unicode_emoji(): return isinstance(other, PartialEmoji) and self.name == other.name if isinstance(other, _EmojiTag): return self.id == other.id return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.id, self.name)) def is_custom_emoji(self): """:class:`bool`: Checks if this is a custom non-Unicode emoji.""" return self.id is not None def is_unicode_emoji(self): """:class:`bool`: Checks if this is a Unicode emoji.""" return self.id is None def _as_reaction(self): if self.id is None: return self.name return '%s:%s' % (self.name, self.id) @property def created_at(self): """Optional[:class:`datetime.datetime`]: Returns the emoji's creation time in UTC, or None if Unicode emoji. .. versionadded:: 1.6 """ if self.is_unicode_emoji(): return None return utils.snowflake_time(self.id) @property def url(self): """:class:`Asset`: Returns the asset of the emoji, if it is custom. This is equivalent to calling :meth:`url_as` with the default parameters (i.e. png/gif detection). """ return self.url_as(format=None) def url_as(self, *, format=None, static_format="png"): """Returns an :class:`Asset` for the emoji's url, if it is custom. The format must be one of 'webp', 'jpeg', 'jpg', 'png' or 'gif'. 'gif' is only valid for animated emojis. .. versionadded:: 1.7 Parameters ----------- format: Optional[:class:`str`] The format to attempt to convert the emojis to. If the format is ``None``, then it is automatically detected as either 'gif' or static_format, depending on whether the emoji is animated or not. static_format: Optional[:class:`str`] Format to attempt to convert only non-animated emoji's to. Defaults to 'png' Raises ------- InvalidArgument Bad image format passed to ``format`` or ``static_format``. Returns -------- :class:`Asset` The resulting CDN asset. """ if self.is_unicode_emoji(): return Asset(self._state) return Asset._from_emoji(self._state, self, format=format, static_format=static_format)
zidiscord.py
/zidiscord.py-1.7.3.3.tar.gz/zidiscord.py-1.7.3.3/discord/partial_emoji.py
partial_emoji.py