id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
180,010
import re from datetime import datetime, timedelta import cv2 import numpy as np from module.base.timer import Timer from module.base.utils import color_similarity_2d from module.exception import RequestHumanTakeover, ScriptError from module.logger import logger from module.ocr.ocr import Ocr from tasks.base.assets.assets_base_main_page import ROGUE_LEAVE_FOR_NOW from tasks.base.assets.assets_base_page import MAP_EXIT from tasks.base.page import page_guide, page_item, page_main, page_rogue from tasks.dungeon.keywords import DungeonList from tasks.dungeon.keywords.dungeon import Simulated_Universe_World_1 from tasks.dungeon.state import OcrSimUniPoint from tasks.dungeon.ui import DungeonUI from tasks.forgotten_hall.assets.assets_forgotten_hall_ui import TELEPORT from tasks.rogue.assets.assets_rogue_entry import ( LEVEL_CONFIRM, OCR_WEEKLY_POINT, OCR_WORLD, THEME_DLC, THEME_ROGUE, THEME_SWITCH, WORLD_ENTER, WORLD_NEXT, WORLD_PREV ) from tasks.rogue.assets.assets_rogue_path import CONFIRM_PATH from tasks.rogue.assets.assets_rogue_ui import ROGUE_LAUNCH from tasks.rogue.assets.assets_rogue_weekly import REWARD_CLOSE, REWARD_ENTER from tasks.rogue.entry.path import RoguePathHandler from tasks.rogue.entry.weekly import RogueRewardHandler from tasks.rogue.exception import RogueReachedWeeklyPointLimit from tasks.rogue.route.base import RouteBase def chinese_to_arabic(chinese_number: str) -> int: chinese_numerals = { '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '零': 0 } result = 0 current_number = 0 for char in chinese_number: if char in chinese_numerals: # If the character is a valid Chinese numeral, accumulate the value. current_number = chinese_numerals[char] else: # If it's not a valid Chinese numeral, assume it's a multiplier (e.g., 十 for 10). multiplier = 1 if char == '十': multiplier = 10 elif char == '百': multiplier = 100 elif char == '千': multiplier = 1000 elif char == '万': result += current_number * 10000 current_number = 0 continue result += current_number * multiplier current_number = 0 result += current_number # Add the last accumulated number. return result
null
180,011
import re from module.base.base import ModuleBase from module.base.utils import area_offset from module.ocr.ocr import OcrResultButton REGEX_PUNCTUATION = re.compile(r'[ ,.\'"“”,。::!!??·•—/()()「」『』【】《》]') def parse_name(n): n = REGEX_PUNCTUATION.sub('', str(n)).lower() return n
null
180,012
import re from module.base.base import ModuleBase from module.base.utils import area_offset from module.ocr.ocr import OcrResultButton def get_regex_from_keyword_name(keyword, attr_name): string = "" for instance in keyword.instances.values(): if hasattr(instance, attr_name): for name in instance.__getattribute__(attr_name): string += f"{name}|" # some pattern contain each other, make sure each pattern end with "-" or the end of string return f"(?:({string[:-1]})(?:-|$))?"
null
180,013
import re from module.base.base import ModuleBase from module.base.utils import area_offset from module.ocr.ocr import OcrResultButton class ModuleBase: config: AzurLaneConfig device: Device def __init__(self, config, device=None, task=None): """ Args: config (AzurLaneConfig, str): Name of the user config under ./config device (Device, str): To reuse a device. If None, create a new Device object. If str, create a new Device object and use the given device as serial. task (str): Bind a task only for dev purpose. Usually to be None for auto task scheduling. If None, use default configs. """ if isinstance(config, AzurLaneConfig): self.config = config elif isinstance(config, str): self.config = AzurLaneConfig(config, task=task) else: logger.warning('Alas ModuleBase received an unknown config, assume it is AzurLaneConfig') self.config = config if isinstance(device, Device): self.device = device elif device is None: self.device = Device(config=self.config) elif isinstance(device, str): self.config.override(Emulator_Serial=device) self.device = Device(config=self.config) else: logger.warning('Alas ModuleBase received an unknown device, assume it is Device') self.device = device self.interval_timer = {} def worker(self) -> ThreadPoolExecutor: """ A thread pool to run things at background """ logger.hr('Creating worker') pool = ThreadPoolExecutor(1) return pool def match_template(self, button, interval=0, similarity=0.85): """ Args: button (ButtonWrapper): interval (int, float): interval between two active events. similarity (int, float): 0 to 1. Returns: bool: Examples: Image detection: ``` self.device.screenshot() self.appear(Button(area=(...), color=(...), button=(...)) self.appear(Template(file='...') ``` """ self.device.stuck_record_add(button) if interval and not self.interval_is_reached(button, interval=interval): return False appear = button.match_template(self.device.image, similarity=similarity) if appear and interval: self.interval_reset(button, interval=interval) return appear def match_color(self, button, interval=0, threshold=10): """ Args: button (ButtonWrapper): interval (int, float): interval between two active events. threshold (int): 0 to 255, smaller means more similar Returns: bool: """ self.device.stuck_record_add(button) if interval and not self.interval_is_reached(button, interval=interval): return False appear = button.match_color(self.device.image, threshold=threshold) if appear and interval: self.interval_reset(button, interval=interval) return appear def match_template_color(self, button, interval=0, similarity=0.85, threshold=30): """ Args: button (ButtonWrapper): interval (int, float): interval between two active events. similarity (int, float): 0 to 1. threshold (int): 0 to 255, smaller means more similar Returns: bool: """ self.device.stuck_record_add(button) if interval and not self.interval_is_reached(button, interval=interval): return False appear = button.match_template_color(self.device.image, similarity=similarity, threshold=threshold) if appear and interval: self.interval_reset(button, interval=interval) return appear appear = match_template def appear_then_click(self, button, interval=5, similarity=0.85): appear = self.appear(button, interval=interval, similarity=similarity) if appear: self.device.click(button) return appear def wait_until_stable(self, button, timer=Timer(0.3, count=1), timeout=Timer(5, count=10)): """ A terrible method, don't rely too much on it. """ logger.info(f'Wait until stable: {button}') prev_image = self.image_crop(button) timer.reset() timeout.reset() while 1: self.device.screenshot() if timeout.reached(): logger.warning(f'wait_until_stable({button}) timeout') break image = self.image_crop(button) if match_template(image, prev_image): if timer.reached(): logger.info(f'{button} stabled') break else: prev_image = image timer.reset() def image_crop(self, button, copy=True): """Extract the area from image. Args: button(Button, tuple): Button instance or area tuple. copy: """ if isinstance(button, Button): return crop(self.device.image, button.area, copy=copy) elif isinstance(button, ButtonWrapper): return crop(self.device.image, button.area, copy=copy) elif hasattr(button, 'area'): return crop(self.device.image, button.area, copy=copy) else: return crop(self.device.image, button, copy=copy) def image_color_count(self, button, color, threshold=221, count=50): """ Args: button (Button, tuple): Button instance or area. color (tuple): RGB. threshold: 255 means colors are the same, the lower the worse. count (int): Pixels count. Returns: bool: """ if isinstance(button, np.ndarray): image = button else: image = self.image_crop(button, copy=False) mask = color_similarity_2d(image, color=color) cv2.inRange(mask, threshold, 255, dst=mask) sum_ = cv2.countNonZero(mask) return sum_ > count def image_color_button(self, area, color, color_threshold=250, encourage=5, name='COLOR_BUTTON'): """ Find an area with pure color on image, convert into a Button. Args: area (tuple[int]): Area to search from color (tuple[int]): Target color color_threshold (int): 0-255, 255 means exact match encourage (int): Radius of button name (str): Name of the button Returns: Button: Or None if nothing matched. """ image = color_similarity_2d(self.image_crop(area), color=color) points = np.array(np.where(image > color_threshold)).T[:, ::-1] if points.shape[0] < encourage ** 2: # Not having enough pixels to match return None point = fit_points(points, mod=image_size(image), encourage=encourage) point = ensure_int(point + area[:2]) button_area = area_offset((-encourage, -encourage, encourage, encourage), offset=point) return ClickButton(area=button_area, name=name) def get_interval_timer(self, button, interval=5, renew=False) -> Timer: if hasattr(button, 'name'): name = button.name elif callable(button): name = button.__name__ else: name = str(button) try: timer = self.interval_timer[name] if renew and timer.limit != interval: timer = Timer(interval) self.interval_timer[name] = timer return timer except KeyError: timer = Timer(interval) self.interval_timer[name] = timer return timer def interval_reset(self, button, interval=5): if isinstance(button, (list, tuple)): for b in button: self.interval_reset(b, interval) return if button is not None: self.get_interval_timer(button, interval=interval).reset() def interval_clear(self, button, interval=5): if isinstance(button, (list, tuple)): for b in button: self.interval_clear(b, interval) return if button is not None: self.get_interval_timer(button, interval=interval).clear() def interval_is_reached(self, button, interval=5): return self.get_interval_timer(button, interval=interval, renew=True).reached() _image_file = '' def image_file(self): return self._image_file def image_file(self, value): """ For development. Load image from local file system and set it to self.device.image Test an image without taking a screenshot from emulator. """ if isinstance(value, Image.Image): value = np.array(value) elif isinstance(value, str): value = load_image(value) self.device.image = value def set_lang(self, lang): """ For development. Change lang and affect globally, including assets and server specific methods. """ server_.set_lang(lang) logger.attr('Lang', self.config.LANG) def screenshot_tracking_add(self): """ Add a tracking image, image will be saved """ if not self.config.Error_SaveError: return logger.info('screenshot_tracking_add') data = self.device.screenshot_deque[-1] image = data['image'] now = data['time'] def image_encode(im, ti): import io from module.handler.sensitive_info import handle_sensitive_image output = io.BytesIO() im = handle_sensitive_image(im) Image.fromarray(im, mode='RGB').save(output, format='png') output.seek(0) self.device.screenshot_tracking.append({ 'time': ti, 'image': output }) ModuleBase.worker.submit(image_encode, image, now) class OcrResultButton: def __init__(self, boxed_result: BoxedResult, matched_keyword): """ Args: boxed_result: BoxedResult from ppocr-onnx matched_keyword: Keyword object or None """ self.area = boxed_result.box self.search = area_pad(self.area, pad=-20) # self.color = self.button = boxed_result.box if matched_keyword is not None: self.matched_keyword = matched_keyword self.name = str(matched_keyword) else: self.matched_keyword = None self.name = boxed_result.ocr_text self.text = boxed_result.ocr_text self.score = boxed_result.score def __str__(self): return self.name __repr__ = __str__ def __eq__(self, other): return str(self) == str(other) def __hash__(self): return hash(self.name) def __bool__(self): return True def is_keyword_matched(self) -> bool: return self.matched_keyword is not None The provided code snippet includes necessary dependencies for implementing the `is_card_selected` function. Write a Python function `def is_card_selected(main: ModuleBase, target: OcrResultButton, confirm_button)` to solve the following problem: There is a white border if a blessing is selected. For the enforce case, just check the confirm button turning to white Here is the function: def is_card_selected(main: ModuleBase, target: OcrResultButton, confirm_button): """ There is a white border if a blessing is selected. For the enforce case, just check the confirm button turning to white """ if not target: return main.image_color_count(confirm_button, (230, 230, 230)) top_border = area_offset(target.area, (0, -180)) return main.image_color_count(top_border, (255, 255, 255))
There is a white border if a blessing is selected. For the enforce case, just check the confirm button turning to white
180,014
import re from module.base.timer import Timer from module.base.utils import random_rectangle_vector_opted from module.logger import logger from tasks.base.ui import UI from tasks.combat.assets.assets_combat_team import * logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def button_to_index(button: ButtonWrapper) -> int: res = re.search(r'(\d)', button.name) if res: return int(res.group(1)) else: logger.warning(f'Cannot convert team button to index: {button}') return 1
null
180,015
import re from module.base.timer import Timer from module.base.utils import random_rectangle_vector_opted from module.logger import logger from tasks.base.ui import UI from tasks.combat.assets.assets_combat_team import * logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def index_to_button(index: int) -> ButtonWrapper: match index: case 1: return TEAM_1_CLICK case 2: return TEAM_2_CLICK case 3: return TEAM_3_CLICK case 4: return TEAM_4_CLICK case 5: return TEAM_5_CLICK case 6: return TEAM_6_CLICK case 7: return TEAM_7_CLICK case 8: return TEAM_8_CLICK case 9: return TEAM_9_CLICK case _: logger.warning(f'Invalid team index: {index}') return TEAM_1_CLICK
null
180,016
import cv2 import numpy as np from scipy import signal from module.base.button import ClickButton from module.base.timer import Timer from module.base.utils import area_offset, area_size, crop, load_image, rgb2luma from module.logger import logger from module.ui.scroll import Scroll from tasks.base.assets.assets_base_popup import POPUP_CANCEL from tasks.base.ui import UI from tasks.combat.assets.assets_combat_support import COMBAT_SUPPORT_ADD, COMBAT_SUPPORT_LIST, \ COMBAT_SUPPORT_LIST_GRID, COMBAT_SUPPORT_LIST_SCROLL, COMBAT_SUPPORT_SELECTED, SUPPORT_SELECTED from tasks.combat.assets.assets_combat_team import COMBAT_TEAM_DISMISSSUPPORT, COMBAT_TEAM_SUPPORT The provided code snippet includes necessary dependencies for implementing the `get_position_in_original_image` function. Write a Python function `def get_position_in_original_image(position_in_croped_image, crop_area)` to solve the following problem: Returns: tuple: (x, y) of position in original image Here is the function: def get_position_in_original_image(position_in_croped_image, crop_area): """ Returns: tuple: (x, y) of position in original image """ return ( position_in_croped_image[0] + crop_area[0], position_in_croped_image[1] + crop_area[1]) if position_in_croped_image else None
Returns: tuple: (x, y) of position in original image
180,017
import os import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `generate_ui_mask` function. Write a Python function `def generate_ui_mask()` to solve the following problem: code to generate ui mask Here is the function: def generate_ui_mask(): """ code to generate ui mask """ mask = np.ones([720, 1280]) * 255 mask[34:81, 21:61] = 0 mask[179:220, 21:51] = 0 mask[35:84, 183:218] = 0 mask[0:61, 780:1280] = 0 mask[145:435, 1153:1240] = 0 cv2.circle(mask, (907, 614), 55, 0, -1) cv2.circle(mask, (1033, 542), 67, 0, -1) cv2.imwrite("mask.png", mask)
code to generate ui mask
180,018
import importlib import os from module.base.decorator import del_cached_property from module.exception import GameStuckError, GameTooManyClickError, ScriptError from module.logger import logger from tasks.base.ui import UI from tasks.map.route.base import RouteBase from tasks.map.route.model import RouteModel def empty_function(*arg, **kwargs): return False
null
180,019
from tasks.map.control.control import MapControl from tasks.map.control.waypoint import Waypoint from tasks.map.keywords import MapPlane class RouteBase(MapControl): """ Base class of `Route` Every `Route` class must implement method `route()` """ # Module and func of current route, updated from RouteLoader route_module: str = '' route_func: str = '' registered_locked_position = None registered_locked_direction = None registered_locked_rotation = None def route_example(self): """ Pages: in: page_main out: page_main Doesn't matter if in/out are not page_main, just be clear what you're doing """ self.map_init( plane=..., floor=..., position=..., ) self.clear_enemy( Waypoint(...).run_2x(), Waypoint(...), ) def map_init( self, plane: MapPlane | str, floor: str = 'F1', position: tuple[int | float, int | float] = None ): """ Args: plane (MapPlane, str): Such as Jarilo_AdministrativeDistrict floor (str): position: Initialize the starter point of minimap tracking Leaving None will trigger brute-force starter point finding. """ try: if self.device.image is None: self.device.screenshot() except AttributeError: self.device.screenshot() self.minimap.set_plane(plane, floor=floor) if position is not None: self.minimap.init_position( position=position, locked=self.registered_locked_position is not None ) if self.registered_locked_direction is not None: self.minimap.lock_direction(self.registered_locked_direction) if self.registered_locked_rotation is not None: self.minimap.lock_rotation(self.registered_locked_rotation) self.registered_locked_position = None self.registered_locked_direction = None self.registered_locked_rotation = None def before_route(self): pass def after_route(self): pass The provided code snippet includes necessary dependencies for implementing the `locked_position` function. Write a Python function `def locked_position(function)` to solve the following problem: Examples: @locked_position def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Search area will be locked Here is the function: def locked_position(function): """ Examples: @locked_position def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Search area will be locked """ def wrapper(self: RouteBase, *args, **kwargs): self.registered_locked_position = True result = function(self, *args, **kwargs) return result return wrapper
Examples: @locked_position def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Search area will be locked
180,020
from tasks.map.control.control import MapControl from tasks.map.control.waypoint import Waypoint from tasks.map.keywords import MapPlane class RouteBase(MapControl): """ Base class of `Route` Every `Route` class must implement method `route()` """ # Module and func of current route, updated from RouteLoader route_module: str = '' route_func: str = '' registered_locked_position = None registered_locked_direction = None registered_locked_rotation = None def route_example(self): """ Pages: in: page_main out: page_main Doesn't matter if in/out are not page_main, just be clear what you're doing """ self.map_init( plane=..., floor=..., position=..., ) self.clear_enemy( Waypoint(...).run_2x(), Waypoint(...), ) def map_init( self, plane: MapPlane | str, floor: str = 'F1', position: tuple[int | float, int | float] = None ): """ Args: plane (MapPlane, str): Such as Jarilo_AdministrativeDistrict floor (str): position: Initialize the starter point of minimap tracking Leaving None will trigger brute-force starter point finding. """ try: if self.device.image is None: self.device.screenshot() except AttributeError: self.device.screenshot() self.minimap.set_plane(plane, floor=floor) if position is not None: self.minimap.init_position( position=position, locked=self.registered_locked_position is not None ) if self.registered_locked_direction is not None: self.minimap.lock_direction(self.registered_locked_direction) if self.registered_locked_rotation is not None: self.minimap.lock_rotation(self.registered_locked_rotation) self.registered_locked_position = None self.registered_locked_direction = None self.registered_locked_rotation = None def before_route(self): pass def after_route(self): pass The provided code snippet includes necessary dependencies for implementing the `locked_direction` function. Write a Python function `def locked_direction(degree: int | float)` to solve the following problem: Examples: @locked_direction(270) def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Direction will be locked to 270 Here is the function: def locked_direction(degree: int | float): """ Examples: @locked_direction(270) def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Direction will be locked to 270 """ def locker(function): def wrapper(self: RouteBase, *args, **kwargs): self.registered_locked_direction = degree result = function(self, *args, **kwargs) return result return wrapper return locker
Examples: @locked_direction(270) def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Direction will be locked to 270
180,021
from tasks.map.control.control import MapControl from tasks.map.control.waypoint import Waypoint from tasks.map.keywords import MapPlane class RouteBase(MapControl): """ Base class of `Route` Every `Route` class must implement method `route()` """ # Module and func of current route, updated from RouteLoader route_module: str = '' route_func: str = '' registered_locked_position = None registered_locked_direction = None registered_locked_rotation = None def route_example(self): """ Pages: in: page_main out: page_main Doesn't matter if in/out are not page_main, just be clear what you're doing """ self.map_init( plane=..., floor=..., position=..., ) self.clear_enemy( Waypoint(...).run_2x(), Waypoint(...), ) def map_init( self, plane: MapPlane | str, floor: str = 'F1', position: tuple[int | float, int | float] = None ): """ Args: plane (MapPlane, str): Such as Jarilo_AdministrativeDistrict floor (str): position: Initialize the starter point of minimap tracking Leaving None will trigger brute-force starter point finding. """ try: if self.device.image is None: self.device.screenshot() except AttributeError: self.device.screenshot() self.minimap.set_plane(plane, floor=floor) if position is not None: self.minimap.init_position( position=position, locked=self.registered_locked_position is not None ) if self.registered_locked_direction is not None: self.minimap.lock_direction(self.registered_locked_direction) if self.registered_locked_rotation is not None: self.minimap.lock_rotation(self.registered_locked_rotation) self.registered_locked_position = None self.registered_locked_direction = None self.registered_locked_rotation = None def before_route(self): pass def after_route(self): pass The provided code snippet includes necessary dependencies for implementing the `locked_rotation` function. Write a Python function `def locked_rotation(degree: int | float)` to solve the following problem: Examples: @locked_rotation(270) def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Rotation will be locked to 270 Here is the function: def locked_rotation(degree: int | float): """ Examples: @locked_rotation(270) def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Rotation will be locked to 270 """ def locker(function): def wrapper(self: RouteBase, *args, **kwargs): self.registered_locked_rotation = degree result = function(self, *args, **kwargs) return result return wrapper return locker
Examples: @locked_rotation(270) def Luofu_ScalegorgeWaterscape_F1_X619Y387(self): pass # Rotation will be locked to 270
180,022
import cv2 import numpy as np from module.base.decorator import cached_property, del_cached_property from module.base.utils import Points, image_size, load_image from module.config.utils import dict_to_kv from module.logger import logger from tasks.base.ui import UI The provided code snippet includes necessary dependencies for implementing the `inrange` function. Write a Python function `def inrange(image, lower=0, upper=255)` to solve the following problem: Get the coordinates of pixels in range. Equivalent to `np.array(np.where(lower <= image <= upper))` but faster. Note that this method will change `image`. `cv2.findNonZero()` is faster than `np.where` points = np.array(np.where(y > 24)).T[:, ::-1] points = np.array(cv2.findNonZero((y > 24).astype(np.uint8)))[:, 0, :] `cv2.inRange(y, 24)` is faster than `y > 24` cv2.inRange(y, 24, 255, dst=y) y = y > 24 Returns: np.ndarray: Shape (N, 2) E.g. [[x1, y1], [x2, y2], ...] Here is the function: def inrange(image, lower=0, upper=255): """ Get the coordinates of pixels in range. Equivalent to `np.array(np.where(lower <= image <= upper))` but faster. Note that this method will change `image`. `cv2.findNonZero()` is faster than `np.where` points = np.array(np.where(y > 24)).T[:, ::-1] points = np.array(cv2.findNonZero((y > 24).astype(np.uint8)))[:, 0, :] `cv2.inRange(y, 24)` is faster than `y > 24` cv2.inRange(y, 24, 255, dst=y) y = y > 24 Returns: np.ndarray: Shape (N, 2) E.g. [[x1, y1], [x2, y2], ...] """ cv2.inRange(image, lower, upper, dst=image) try: return np.array(cv2.findNonZero(image))[:, 0, :] except IndexError: # Empty result # IndexError: too many indices for array: array is 0-dimensional, but 3 were indexed return np.array([])
Get the coordinates of pixels in range. Equivalent to `np.array(np.where(lower <= image <= upper))` but faster. Note that this method will change `image`. `cv2.findNonZero()` is faster than `np.where` points = np.array(np.where(y > 24)).T[:, ::-1] points = np.array(cv2.findNonZero((y > 24).astype(np.uint8)))[:, 0, :] `cv2.inRange(y, 24)` is faster than `y > 24` cv2.inRange(y, 24, 255, dst=y) y = y > 24 Returns: np.ndarray: Shape (N, 2) E.g. [[x1, y1], [x2, y2], ...]
180,023
import cv2 import numpy as np from module.base.decorator import cached_property, del_cached_property from module.base.utils import Points, image_size, load_image from module.config.utils import dict_to_kv from module.logger import logger from tasks.base.ui import UI The provided code snippet includes necessary dependencies for implementing the `subtract_blur` function. Write a Python function `def subtract_blur(image, radius=3, negative=False)` to solve the following problem: If you care performance more than quality: - radius=3, use medianBlur - radius=5,7,9,11, use GaussianBlur - radius>11, use stackBlur (requires opencv >= 4.7.0) Args: image: radius: negative: Returns: np.ndarray: Here is the function: def subtract_blur(image, radius=3, negative=False): """ If you care performance more than quality: - radius=3, use medianBlur - radius=5,7,9,11, use GaussianBlur - radius>11, use stackBlur (requires opencv >= 4.7.0) Args: image: radius: negative: Returns: np.ndarray: """ if radius <= 3: blur = cv2.medianBlur(image, radius) elif radius <= 11: blur = cv2.GaussianBlur(image, (radius, radius), 0) else: blur = cv2.stackBlur(image, (radius, radius), 0) if negative: cv2.subtract(blur, image, dst=blur) else: cv2.subtract(image, blur, dst=blur) return blur
If you care performance more than quality: - radius=3, use medianBlur - radius=5,7,9,11, use GaussianBlur - radius>11, use stackBlur (requires opencv >= 4.7.0) Args: image: radius: negative: Returns: np.ndarray:
180,024
import cv2 import numpy as np from module.base.decorator import cached_property, del_cached_property from module.base.utils import Points, image_size, load_image from module.config.utils import dict_to_kv from module.logger import logger from tasks.base.ui import UI The provided code snippet includes necessary dependencies for implementing the `remove_border` function. Write a Python function `def remove_border(image, radius)` to solve the following problem: Paint edge pixels black. No returns, changes are written to `image` Args: image: radius: Here is the function: def remove_border(image, radius): """ Paint edge pixels black. No returns, changes are written to `image` Args: image: radius: """ width, height = image_size(image) image[:, :radius + 1] = 0 image[:, width - radius:] = 0 image[:radius + 1, :] = 0 image[height - radius:, :] = 0
Paint edge pixels black. No returns, changes are written to `image` Args: image: radius:
180,025
import cv2 import numpy as np from module.base.decorator import cached_property, del_cached_property from module.base.utils import Points, image_size, load_image from module.config.utils import dict_to_kv from module.logger import logger from tasks.base.ui import UI The provided code snippet includes necessary dependencies for implementing the `create_circle` function. Write a Python function `def create_circle(min_radius, max_radius)` to solve the following problem: Create a circle with min_radius <= R <= max_radius. 1 represents circle, 0 represents background Args: min_radius: max_radius: Returns: np.ndarray: Here is the function: def create_circle(min_radius, max_radius): """ Create a circle with min_radius <= R <= max_radius. 1 represents circle, 0 represents background Args: min_radius: max_radius: Returns: np.ndarray: """ circle = np.ones((max_radius * 2 + 1, max_radius * 2 + 1), dtype=np.uint8) center = np.array((max_radius, max_radius)) points = np.array(np.meshgrid(np.arange(circle.shape[0]), np.arange(circle.shape[1]))).T distance = np.linalg.norm(points - center, axis=2) circle[distance < min_radius] = 0 circle[distance > max_radius] = 0 return circle
Create a circle with min_radius <= R <= max_radius. 1 represents circle, 0 represents background Args: min_radius: max_radius: Returns: np.ndarray:
180,026
import cv2 import numpy as np from module.base.decorator import cached_property, del_cached_property from module.base.utils import Points, image_size, load_image from module.config.utils import dict_to_kv from module.logger import logger from tasks.base.ui import UI The provided code snippet includes necessary dependencies for implementing the `draw_circle` function. Write a Python function `def draw_circle(image, circle, points)` to solve the following problem: Add a circle onto image. No returns, changes are written to `image` Args: image: circle: Created from create_circle() points: (x, y), center of the circle to draw Here is the function: def draw_circle(image, circle, points): """ Add a circle onto image. No returns, changes are written to `image` Args: image: circle: Created from create_circle() points: (x, y), center of the circle to draw """ width, height = image_size(circle) x1 = -int(width // 2) y1 = -int(height // 2) x2 = width + x1 y2 = height + y1 for point in points: x, y = point # Fancy index is faster index = image[y + y1:y + y2, x + x1:x + x2] # print(index.shape) cv2.add(index, circle, dst=index)
Add a circle onto image. No returns, changes are written to `image` Args: image: circle: Created from create_circle() points: (x, y), center of the circle to draw
180,027
import re from typing import Optional from module.base.base import ModuleBase from module.base.timer import Timer from module.exception import ScriptError from module.logger import logger from module.ocr.ocr import Ocr, OcrResultButton from module.ui.draggable_list import DraggableList from module.ui.scroll import Scroll from tasks.base.page import page_map, page_world from tasks.base.ui import UI from tasks.map.assets.assets_map_bigmap import * from tasks.map.keywords import KEYWORDS_MAP_PLANE, MapPlane class ScriptError(Exception): # This is likely to be a mistake of developers, but sometimes a random issue pass def world_entrance(plane: MapPlane) -> ButtonWrapper: if plane.world.is_Herta: return WORLD_HERTA if plane.world.is_Jarilo: return WORLD_JARILO if plane.world.is_Luofu: return WORLD_LUOFU raise ScriptError(f'world_entrance() got unknown plane: {plane}')
null
180,028
import os from functools import cached_property import cv2 import numpy as np from module.base.utils import ( color_similarity_2d, crop, get_bbox, get_bbox_reversed, image_paste, image_size ) from module.config.utils import iter_folder from tasks.map.minimap.utils import map_image_preprocess, rotate_bound from tasks.map.resource.const import ResourceConst def register_output(output): def register_wrapper(func): def wrapper(self, *args, **kwargs): image = func(self, *args, **kwargs) self.DICT_GENERATE[output] = image return image return wrapper return register_wrapper
null
180,029
import os import numpy as np from PIL import Image from module.base.utils import load_image The provided code snippet includes necessary dependencies for implementing the `diff_to_180_180` function. Write a Python function `def diff_to_180_180(diff)` to solve the following problem: Args: diff: Degree diff Returns: float: Degree diff (-180~180) Here is the function: def diff_to_180_180(diff): """ Args: diff: Degree diff Returns: float: Degree diff (-180~180) """ diff = diff % 360 if diff > 180: diff -= 360 return round(diff, 3)
Args: diff: Degree diff Returns: float: Degree diff (-180~180)
180,030
import os import numpy as np from PIL import Image from module.base.utils import load_image The provided code snippet includes necessary dependencies for implementing the `diff_to_0_360` function. Write a Python function `def diff_to_0_360(diff)` to solve the following problem: Args: diff: Degree diff Returns: float: Degree diff (0~360) Here is the function: def diff_to_0_360(diff): """ Args: diff: Degree diff Returns: float: Degree diff (0~360) """ return round(diff % 360, 3)
Args: diff: Degree diff Returns: float: Degree diff (0~360)
180,031
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `map_image_preprocess` function. Write a Python function `def map_image_preprocess(image)` to solve the following problem: A shared preprocess method used in ResourceGenerate and _predict_position() Args: image (np.ndarray): Screenshot in RGB Returns: np.ndarray: Here is the function: def map_image_preprocess(image): """ A shared preprocess method used in ResourceGenerate and _predict_position() Args: image (np.ndarray): Screenshot in RGB Returns: np.ndarray: """ # image = rgb2luma(image) image = cv2.GaussianBlur(image, (5, 5), 0) image = cv2.Canny(image, 15, 50) return image
A shared preprocess method used in ResourceGenerate and _predict_position() Args: image (np.ndarray): Screenshot in RGB Returns: np.ndarray:
180,032
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size def create_circular_mask(h, w, center=None, radius=None): # https://stackoverflow.com/questions/44865023/how-can-i-create-a-circular-mask-for-a-numpy-array if center is None: # use the middle of the image center = (int(w / 2), int(h / 2)) if radius is None: # use the smallest distance between the center and image walls radius = min(center[0], center[1], w - center[0], h - center[1]) y, x = np.ogrid[:h, :w] dist_from_center = np.sqrt((x - center[0]) ** 2 + (y - center[1]) ** 2) mask = dist_from_center <= radius return mask
null
180,033
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `rotate_bound` function. Write a Python function `def rotate_bound(image, angle)` to solve the following problem: Rotate an image with outbound https://blog.csdn.net/qq_37674858/article/details/80708393 Args: image (np.ndarray): angle (int, float): Returns: np.ndarray: Here is the function: def rotate_bound(image, angle): """ Rotate an image with outbound https://blog.csdn.net/qq_37674858/article/details/80708393 Args: image (np.ndarray): angle (int, float): Returns: np.ndarray: """ # grab the dimensions of the image and then determine the # center (h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) # grab the rotation matrix (applying the negative of the # angle to rotate clockwise), then grab the sine and cosine # (i.e., the rotation components of the matrix) M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) # compute the new bounding dimensions of the image nW = int((h * sin) + (w * cos)) nH = int((h * cos) + (w * sin)) # adjust the rotation matrix to take into account translation M[0, 2] += (nW / 2) - cX M[1, 2] += (nH / 2) - cY # perform the actual rotation and return the image return cv2.warpAffine(image, M, (nW, nH))
Rotate an image with outbound https://blog.csdn.net/qq_37674858/article/details/80708393 Args: image (np.ndarray): angle (int, float): Returns: np.ndarray:
180,034
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `cubic_find_maximum` function. Write a Python function `def cubic_find_maximum(image, precision=0.05)` to solve the following problem: Using CUBIC resize algorithm to fit a curved surface, find the maximum value and location. Args: image (np.ndarray): precision (int, float): Returns: float: Maximum value on curved surface np.ndarray[float, float]: Location of maximum value Here is the function: def cubic_find_maximum(image, precision=0.05): """ Using CUBIC resize algorithm to fit a curved surface, find the maximum value and location. Args: image (np.ndarray): precision (int, float): Returns: float: Maximum value on curved surface np.ndarray[float, float]: Location of maximum value """ image = cv2.resize(image, None, fx=1 / precision, fy=1 / precision, interpolation=cv2.INTER_CUBIC) _, sim, _, loca = cv2.minMaxLoc(image) loca = np.array(loca, dtype=float) * precision return sim, loca
Using CUBIC resize algorithm to fit a curved surface, find the maximum value and location. Args: image (np.ndarray): precision (int, float): Returns: float: Maximum value on curved surface np.ndarray[float, float]: Location of maximum value
180,035
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `image_center_pad` function. Write a Python function `def image_center_pad(image, size, value=(0, 0, 0))` to solve the following problem: Create a new image with given `size`, placing given `image` in the middle. Args: image (np.ndarray): size: (width, height) value: Color of the background. Returns: np.ndarray: Here is the function: def image_center_pad(image, size, value=(0, 0, 0)): """ Create a new image with given `size`, placing given `image` in the middle. Args: image (np.ndarray): size: (width, height) value: Color of the background. Returns: np.ndarray: """ diff = np.array(size) - image_size(image) left, top = int(diff[0] / 2), int(diff[1] / 2) right, bottom = diff[0] - left, diff[1] - top image = cv2.copyMakeBorder(image, top, bottom, left, right, borderType=cv2.BORDER_CONSTANT, value=value) return image
Create a new image with given `size`, placing given `image` in the middle. Args: image (np.ndarray): size: (width, height) value: Color of the background. Returns: np.ndarray:
180,036
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `image_center_crop` function. Write a Python function `def image_center_crop(image, size)` to solve the following problem: Center crop the given image. Args: image (np.ndarray): size: Output image shape, (width, height) Returns: np.ndarray: Here is the function: def image_center_crop(image, size): """ Center crop the given image. Args: image (np.ndarray): size: Output image shape, (width, height) Returns: np.ndarray: """ diff = image_size(image) - np.array(size) left, top = int(diff[0] / 2), int(diff[1] / 2) right, bottom = diff[0] - left, diff[1] - top image = image[top:-bottom, left:-right] return image
Center crop the given image. Args: image (np.ndarray): size: Output image shape, (width, height) Returns: np.ndarray:
180,037
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `area2corner` function. Write a Python function `def area2corner(area)` to solve the following problem: Args: area: (x1, y1, x2, y2) Returns: np.ndarray: [upper-left, upper-right, bottom-left, bottom-right] Here is the function: def area2corner(area): """ Args: area: (x1, y1, x2, y2) Returns: np.ndarray: [upper-left, upper-right, bottom-left, bottom-right] """ return np.array([[area[0], area[1]], [area[2], area[1]], [area[0], area[3]], [area[2], area[3]]])
Args: area: (x1, y1, x2, y2) Returns: np.ndarray: [upper-left, upper-right, bottom-left, bottom-right]
180,038
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `convolve` function. Write a Python function `def convolve(arr, kernel=3)` to solve the following problem: Args: arr (np.ndarray): Shape (N,) kernel (int): Returns: np.ndarray: Here is the function: def convolve(arr, kernel=3): """ Args: arr (np.ndarray): Shape (N,) kernel (int): Returns: np.ndarray: """ return sum(np.roll(arr, i) * (kernel - abs(i)) // kernel for i in range(-kernel + 1, kernel))
Args: arr (np.ndarray): Shape (N,) kernel (int): Returns: np.ndarray:
180,039
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `convolve_plain` function. Write a Python function `def convolve_plain(arr, kernel=3)` to solve the following problem: Args: arr (np.ndarray): Shape (N,) kernel (int): Returns: np.ndarray: Here is the function: def convolve_plain(arr, kernel=3): """ Args: arr (np.ndarray): Shape (N,) kernel (int): Returns: np.ndarray: """ return sum(np.roll(arr, i) for i in range(-kernel + 1, kernel))
Args: arr (np.ndarray): Shape (N,) kernel (int): Returns: np.ndarray:
180,040
import cv2 import numpy as np from scipy import signal from module.base.utils import image_size The provided code snippet includes necessary dependencies for implementing the `peak_confidence` function. Write a Python function `def peak_confidence(arr, **kwargs)` to solve the following problem: Evaluate the prominence of the highest peak Args: arr (np.ndarray): Shape (N,) **kwargs: Additional kwargs for signal.find_peaks Returns: float: 0-1 Here is the function: def peak_confidence(arr, **kwargs): """ Evaluate the prominence of the highest peak Args: arr (np.ndarray): Shape (N,) **kwargs: Additional kwargs for signal.find_peaks Returns: float: 0-1 """ para = { 'height': 0, 'prominence': 10, } para.update(kwargs) length = len(arr) peaks, properties = signal.find_peaks(np.concatenate((arr, arr, arr)), **para) peaks = [h for p, h in zip(peaks, properties['peak_heights']) if length <= p < length * 2] peaks = sorted(peaks, reverse=True) count = len(peaks) if count > 1: highest, second = peaks[0], peaks[1] elif count == 1: highest, second = 1, 0 else: highest, second = 1, 0 confidence = (highest - second) / highest return confidence
Evaluate the prominence of the highest peak Args: arr (np.ndarray): Shape (N,) **kwargs: Additional kwargs for signal.find_peaks Returns: float: 0-1
180,041
from dataclasses import dataclass, field from module.base.timer import Timer class Waypoint: def __bool__(self): def run_2x(self) -> "Waypoint": def straight_run(self) -> "Waypoint": def run(self) -> "Waypoint": def walk(self) -> "Waypoint": def set_threshold(self, threshold) -> "Waypoint": def get_threshold(self, end): def expected_to_str(results: list) -> list[str]: def match_results(self, results) -> list[str]: def ensure_waypoint(point) -> Waypoint: def ensure_waypoints(points) -> list[Waypoint]: if not isinstance(points, (list, tuple)): points = [points] return [ensure_waypoint(point) for point in points]
null
180,042
import threading from multiprocessing import Event, Process from module.logger import logger from module.webui.setting import State logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) console_hdlr = RichHandler( show_path=False, show_time=False, rich_tracebacks=True, tracebacks_show_locals=True, tracebacks_extra_lines=3, ) console_hdlr.setFormatter(console_formatter) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) class State: """ Shared settings """ _init = False _clearup = False restart_event: threading.Event = None manager: SyncManager = None electron: bool = False theme: str = "default" def init(cls): cls.manager = multiprocessing.Manager() cls._init = True def clearup(cls): cls.manager.shutdown() cls._clearup = True def deploy_config(self) -> "DeployConfig": """ Returns: DeployConfig: """ from module.webui.config import DeployConfig return DeployConfig() def config_updater(self) -> "ConfigUpdater": """ Returns: ConfigUpdater: """ from module.config.config_updater import ConfigUpdater return ConfigUpdater() def func(ev: threading.Event): import argparse import asyncio import sys import uvicorn if sys.platform.startswith("win"): asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) State.restart_event = ev parser = argparse.ArgumentParser(description="Alas web service") parser.add_argument( "--host", type=str, help="Host to listen. Default to WebuiHost in deploy setting", ) parser.add_argument( "-p", "--port", type=int, help="Port to listen. Default to WebuiPort in deploy setting", ) parser.add_argument( "-k", "--key", type=str, help="Password of alas. No password by default" ) parser.add_argument( "--cdn", action="store_true", help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.", ) parser.add_argument( "--electron", action="store_true", help="Runs by electron client." ) parser.add_argument( "--run", nargs="+", type=str, help="Run alas by config names on startup", ) args, _ = parser.parse_known_args() host = args.host or State.deploy_config.WebuiHost or "0.0.0.0" port = args.port or int(State.deploy_config.WebuiPort) or 22367 State.electron = args.electron logger.hr("Launcher config") logger.attr("Host", host) logger.attr("Port", port) logger.attr("Electron", args.electron) logger.attr("Reload", ev is not None) if State.electron: # https://github.com/LmeSzinc/AzurLaneAutoScript/issues/2051 logger.info("Electron detected, remove log output to stdout") from module.logger.logger import console_hdlr logger.removeHandler(console_hdlr) uvicorn.run("module.webui.app:app", host=host, port=port, factory=True)
null
180,043
import os import re import typing as t from dataclasses import dataclass import numpy as np from tqdm import tqdm from module.base.code_generator import CodeGenerator from module.base.utils import SelectedGrids, area_limit, area_pad, get_bbox, get_color, image_size, load_image from module.config.config_manual import ManualConfig as AzurLaneConfig from module.config.server import VALID_LANG from module.config.utils import deep_get, deep_iter, deep_set, iter_folder from module.logger import logger SHARE_SERVER = 'share' def iter_assets(): class CodeGenerator: def __init__(self): def add(self, line, comment=False, newline=True): def generate(self): def print(self): def write(self, file: str = None): def _line_with_tabs(self, line, comment=False, newline=True): def _repr(self, obj): def tab(self): def Empty(self): def Pass(self): def Import(self, text, empty=2): def Variable(self, name): def Value(self, key=None, value=None, type_=None, **kwargs): def Comment(self, text): def CommentAutoGenerage(self, file): def List(self, key=None): def ListItem(self, value): def Dict(self, key=None): def DictItem(self, key=None, value=None): def Object(self, object_class, key=None): def ObjectAttr(self, key=None, value=None): def Class(self, name, inherit=None): def Def(self, name, args=''): VALID_LANG = ['cn', 'en'] def iter_folder(folder, is_dir=False, ext=None): def generate_code(): all_assets = iter_assets() for module, module_data in all_assets.items(): path = os.path.join(AzurLaneConfig.ASSETS_MODULE, module.split('/', maxsplit=1)[0]) output = os.path.join(path, 'assets.py') if os.path.exists(output): os.remove(output) output = os.path.join(path, 'assets') os.makedirs(output, exist_ok=True) for prev in iter_folder(output, ext='.py'): if os.path.basename(prev) == '__init__.py': continue os.remove(prev) for module, module_data in all_assets.items(): path = os.path.join(AzurLaneConfig.ASSETS_MODULE, module.split('/', maxsplit=1)[0]) output = os.path.join(path, 'assets') gen = CodeGenerator() gen.Import(""" from module.base.button import Button, ButtonWrapper """) gen.CommentAutoGenerage('dev_tools.button_extract') for assets, assets_data in module_data.items(): has_share = SHARE_SERVER in assets_data with gen.Object(key=assets, object_class='ButtonWrapper'): gen.ObjectAttr(key='name', value=assets) if has_share: servers = assets_data.keys() else: servers = VALID_LANG for server in servers: frames = list(assets_data.get(server, {}).values()) if len(frames) > 1: with gen.ObjectAttr(key=server, value=gen.List()): for index, frame in enumerate(frames): with gen.ListItem(gen.Object(object_class='Button')): gen.ObjectAttr(key='file', value=frame.file) gen.ObjectAttr(key='area', value=frame.area) gen.ObjectAttr(key='search', value=frame.search) gen.ObjectAttr(key='color', value=frame.color) gen.ObjectAttr(key='button', value=frame.button) elif len(frames) == 1: frame = frames[0] with gen.ObjectAttr(key=server, value=gen.Object(object_class='Button')): gen.ObjectAttr(key='file', value=frame.file) gen.ObjectAttr(key='area', value=frame.area) gen.ObjectAttr(key='search', value=frame.search) gen.ObjectAttr(key='color', value=frame.color) gen.ObjectAttr(key='button', value=frame.button) else: gen.ObjectAttr(key=server, value=None) gen.write(os.path.join(output, f'assets_{module.replace("/", "_")}.py'))
null
180,044
import itertools import os import re from collections import defaultdict from functools import cache from hashlib import md5 from dev_tools.keywords.base import TextMap, UI_LANGUAGES, replace_templates, text_to_variable from module.base.code_generator import CodeGenerator from module.config.utils import deep_get, read_file from module.exception import ScriptError from module.logger import logger def text_to_variable(text): text = re.sub("'s |s' ", '_', text) text = re.sub(r'[ \-—:\'/•.]+', '_', text) text = re.sub(r'[(),#"?!&%*]|</?\w+>', '', text) # text = re.sub(r'[#_]?\d+(_times?)?', '', text) text = re.sub(r'<color=#?\w+>', '', text) text = text.replace('é', 'e') return text.strip('_') def blessing_name(name: str) -> str: name = text_to_variable(name) name = re.sub(r'^\d', lambda match: f"_{match.group(0)}", name) return name
null
180,045
import itertools import os import re from collections import defaultdict from functools import cache from hashlib import md5 from dev_tools.keywords.base import TextMap, UI_LANGUAGES, replace_templates, text_to_variable from module.base.code_generator import CodeGenerator from module.config.utils import deep_get, read_file from module.exception import ScriptError from module.logger import logger def text_to_variable(text): text = re.sub("'s |s' ", '_', text) text = re.sub(r'[ \-—:\'/•.]+', '_', text) text = re.sub(r'[(),#"?!&%*]|</?\w+>', '', text) # text = re.sub(r'[#_]?\d+(_times?)?', '', text) text = re.sub(r'<color=#?\w+>', '', text) text = text.replace('é', 'e') return text.strip('_') def character_name(name: str) -> str: name = text_to_variable(name) name = re.sub('_', '', name) return name
null
180,046
import itertools import os import re from collections import defaultdict from functools import cache from hashlib import md5 from dev_tools.keywords.base import TextMap, UI_LANGUAGES, replace_templates, text_to_variable from module.base.code_generator import CodeGenerator from module.config.utils import deep_get, read_file from module.exception import ScriptError from module.logger import logger def convert_inner_character_to_keyword(name): convert_dict = { 'Silwolf': 'SilverWolf', 'Klara': 'Clara', 'Mar_7th': 'March7th', 'PlayerGirl': 'TrailblazerFemale', 'PlayerBoy': 'TrailblazerMale', 'Ren': 'Blade', } return convert_dict.get(name, name)
null
180,047
import os import re from typing import Iterator import numpy as np from tqdm import tqdm from module.base.code_generator import CodeGenerator, MarkdownGenerator from module.base.decorator import cached_property from module.base.utils import SelectedGrids, load_image from module.config.utils import iter_folder from tasks.map.route.model import RouteModel from tasks.rogue.route.model import RogueRouteListModel, RogueRouteModel, RogueWaypointListModel, RogueWaypointModel regex_posi = re.compile(r'_?X(\d+)Y(\d+)') def get_position_from_name(name): res = regex_posi.search(name) if res: position = int(res.group(1)), int(res.group(2)) else: position = (0, 0) return position
null
180,048
import os import re from typing import Iterator import numpy as np from tqdm import tqdm from module.base.code_generator import CodeGenerator, MarkdownGenerator from module.base.decorator import cached_property from module.base.utils import SelectedGrids, load_image from module.config.utils import iter_folder from tasks.map.route.model import RouteModel from tasks.rogue.route.model import RogueRouteListModel, RogueRouteModel, RogueWaypointListModel, RogueWaypointModel def position2direction(target, origin): """ Args: target: Target position (x, y) origin: Origin position (x, y) Returns: float: Direction from current position to target position (0~360) """ diff = np.subtract(target, origin) distance = np.linalg.norm(diff) if distance < 0.05: return 0 theta = np.rad2deg(np.arccos(-diff[1] / distance)) if diff[0] < 0: theta = 360 - theta theta = round(theta, 3) return theta def swap_exit(exit_, exit1, exit2): diff = position2direction(exit1.position, exit_.position) - position2direction(exit2.position, exit_.position) diff = diff % 360 if diff > 180: diff -= 360 if diff < 0: return exit1, exit2 else: return exit2, exit1
null
180,049
import os import re from typing import Iterator import numpy as np from tqdm import tqdm from module.base.code_generator import CodeGenerator, MarkdownGenerator from module.base.decorator import cached_property from module.base.utils import SelectedGrids, load_image from module.config.utils import iter_folder from tasks.map.route.model import RouteModel from tasks.rogue.route.model import RogueRouteListModel, RogueRouteModel, RogueWaypointListModel, RogueWaypointModel class RouteExtract: def __init__(self, folder): self.folder = folder def iter_files(self) -> Iterator[str]: for path, folders, files in os.walk(self.folder): path = path.replace('\\', '/') for file in files: if file.endswith('.py'): yield f'{path}/{file}' def extract_route(self, file) -> Iterator[RouteModel]: print(f'Extract {file}') with open(file, 'r', encoding='utf-8') as f: content = f.read() """ def route_item_enemy(self): self.enter_himeko_trial() self.map_init(plane=Jarilo_BackwaterPass, position=(519.9, 361.5)) """ regex = re.compile( r'def (?P<func>[a-zA-Z0-9_]*?)\(self\):.*?' r'self\.map_init\((.*?)\)', re.DOTALL) file = file.replace(self.folder, '').replace('.py', '').replace('/', '_').strip('_') module = f"{self.folder.strip('./').replace('/', '.')}.{file}" for result in regex.findall(content): func, data = result res = re.search(r'plane=([a-zA-Z_]*)', data) if res: plane = res.group(1) else: # Must contain plane continue res = re.search(r'floor=([\'"a-zA-Z0-9_]*)', data) if res: floor = res.group(1).strip('"\'') else: floor = 'F1' res = re.search(r'position=\(([0-9.]*)[, ]+([0-9.]*)', data) if res: position = (float(res.group(1)), float(res.group(2))) else: position = None name = f'{file}__{func}' yield RouteModel( name=name, route=f'{module}:{func}', plane=plane, floor=floor, position=position, ) def iter_route(self): """ Yields: RouteData """ for f in self.iter_files(): for row in self.extract_route(f): yield row def write(self, file): gen = CodeGenerator() gen.Import(""" from tasks.map.route.model import RouteModel """) gen.CommentAutoGenerage('dev_tools.route_extract') for row in self.iter_route(): with gen.Object(key=row.name, object_class='RouteModel'): for key, value in row.__iter__(): gen.ObjectAttr(key, value) gen.write(file) def model_to_json(model, file): content = model.model_dump_json(indent=2) with open(file, 'w', encoding='utf-8', newline='') as f: f.write(content) class RogueRouteModel(RouteModel): """ { "name": "Boss_Luofu_ArtisanshipCommission_F1_X506Y495", "domain": "Boss", "route": "route.rogue.Boss.Luofu_ArtisanshipCommission_F1:Luofu_ArtisanshipCommission_F1_X506Y495", "plane": "Luofu_ArtisanshipCommission", "floor": "F1", "position": [ 506.0, 495.4 ] }, """ domain: str def plane_floor(self): return f'{self.plane}_{self.floor}' def is_DomainBoss(self): return self.domain == 'Boss' def is_DomainCombat(self): return self.domain == 'Combat' def is_DomainElite(self): return self.domain == 'Elite' def is_DomainEncounter(self): return self.domain == 'Encounter' def is_DomainOccurrence(self): return self.domain == 'Occurrence' def is_DomainRespite(self): return self.domain == 'Respite' def is_DomainTransaction(self): return self.domain == 'Transaction' RogueRouteListModel = RootModel[list[RogueRouteModel]] def rogue_extract(folder): print('rogue_extract') def iter_route(): for row in RouteExtract(f'{folder}').iter_route(): domain = row.name.split('_', maxsplit=1)[0] row = RogueRouteModel(domain=domain, **row.model_dump()) row.name = f'{row.domain}_{row.route.split(":")[1]}' row.route = row.route.replace('_', '.', 1) yield row routes = RogueRouteListModel(list(iter_route())) model_to_json(routes, f'{folder}/route.json')
null
180,050
import os from datetime import datetime from PIL import Image from pynput import keyboard from module.config.config import AzurLaneConfig from module.config.utils import alas_instance from module.device.connection import Connection, ConnectionAttr from module.device.device import Device from module.logger import logger nshot(): print(f'截图中...') image = device.screenshot() now = datetime.strftime(datetime.now(), '%Y-%m-%d_%H-%M-%S-%f') file = f'{output}/{now}.png' image = handle_sensitive_info(image) print(f'截图中...') Image.fromarray(image).save(file) print(f'截图已保存到: {file}') GLOBAL_KEY = 'F3' def on_press(key): if str(key) == f'Key.{GLOBAL_KEY.lower()}': screenshot()
null
180,051
from functools import cache from typing import Iterable from dev_tools.keywords.base import UI_LANGUAGES, GenerateKeyword from module.config.utils import deep_get class GenerateKeyword: text_map: dict[str, TextMap] = {lang: TextMap(lang) for lang in UI_LANGUAGES} text_map['cn'] = TextMap('chs') def read_file(file: str) -> dict: """ Args: file: ./ExcelOutput/GameplayGuideData.json Returns: dict: """ file = os.path.join(TextMap.DATA_FOLDER, file) return read_file(file) def find_keyword(cls, keyword, lang) -> tuple[int, str]: """ Args: keyword: text string or text id lang: Language to find Returns: text id (hash in TextMap) text """ text_map = cls.text_map[lang] return text_map.find(keyword) output_file = '' def __init__(self): self.gen = CodeGenerator() self.keyword_class = self.__class__.__name__.removeprefix('Generate') self.keyword_index = 0 self.keyword_format = { 'id': 0, 'name': 'Unnamed_Keyword' } for lang in UI_LANGUAGES: self.keyword_format[lang] = '' def gen_import(self): self.gen.Import( f""" from .classes import {self.keyword_class} """ ) def iter_keywords(self) -> t.Iterable[dict]: """ Yields dict: {'text_id': 123456, 'any_attr': 1} """ pass def convert_name(self, text: str, keyword: dict) -> str: return text_to_variable(replace_templates(text)) def convert_keyword(self, text: str, lang: str) -> str: return replace_templates(text) def iter_rows(self) -> t.Iterable[dict]: for keyword in self.iter_keywords(): keyword = self.format_keywords(keyword) yield keyword def format_keywords(self, keyword: dict) -> dict | None: base = self.keyword_format.copy() text_id = keyword.pop('text_id') if text_id is None: return # id self.keyword_index += 1 base['id'] = self.keyword_index # Attrs base.update(keyword) # Name _, name = self.find_keyword(text_id, lang='en') name = self.convert_name(name, keyword=base) base['name'] = name # Translations for lang in UI_LANGUAGES: value = self.find_keyword(text_id, lang=lang)[1] value = self.convert_keyword(value, lang=lang) base[lang] = value return base def generate(self): self.gen_import() self.gen.CommentAutoGenerage('dev_tools.keyword_extract') for keyword in self.iter_rows(): with self.gen.Object(key=keyword['name'], object_class=self.keyword_class): for key, value in keyword.items(): self.gen.ObjectAttr(key, value) if self.output_file: print(f'Write {self.output_file}') self.gen.write(self.output_file) def __call__(self, *args, **kwargs): self.generate() def deep_get(d, keys, default=None): """ Get values in dictionary safely. https://stackoverflow.com/questions/25833613/safe-method-to-get-value-of-nested-dictionary Args: d (dict): keys (str, list): Such as `Scheduler.NextRun.value` default: Default return if key not found. Returns: """ if isinstance(keys, str): keys = keys.split('.') assert type(keys) is list if d is None: return default if not keys: return d return deep_get(d.get(keys[0]), keys[1:], default) The provided code snippet includes necessary dependencies for implementing the `get_assignment_entry_data` function. Write a Python function `def get_assignment_entry_data()` to solve the following problem: Returns: dict: key - assignment text_id value - text_id of reward items Here is the function: def get_assignment_entry_data(): """ Returns: dict: key - assignment text_id value - text_id of reward items """ expedition_namehash_to_id = { deep_get(expedition, 'Name.Hash'): deep_get(expedition, 'ExpeditionID') for expedition in GenerateKeyword.read_file('./ExcelOutput/ExpeditionData.json').values() } expedition_id_to_reward_id = { deep_get(expedition, '4.2.ExpeditionID'): deep_get(expedition, '4.2.RewardID') for expedition in GenerateKeyword.read_file('./ExcelOutput/ExpeditionReward.json').values() } reward_id_to_item_ids = { deep_get(reward, 'RewardID'): [ v for k, v in reward.items() if k.startswith('ItemID') ] for reward in GenerateKeyword.read_file('./ExcelOutput/RewardData.json').values() } item_id_to_namehash = { deep_get(item, 'ID'): deep_get(item, 'ItemName.Hash') for item in GenerateKeyword.read_file('./ExcelOutput/ItemConfig.json').values() } item_name_remap = { '旅情见闻': '角色经验材料', '稀薄以太': '光锥经验材料' } ret = dict() for expedition_namehash, expedition_id in expedition_namehash_to_id.items(): reward_id = expedition_id_to_reward_id[expedition_id] item_ids = reward_id_to_item_ids[reward_id] item_names = [item_id_to_namehash[x] for x in item_ids] if len(item_names) == 1: item = GenerateKeyword.find_keyword(item_names[0], lang='cn')[1] if item in item_name_remap: item_names = [GenerateKeyword.find_keyword( item_name_remap[item], lang='cn')[0]] ret[expedition_namehash] = item_names return ret
Returns: dict: key - assignment text_id value - text_id of reward items
180,052
import os import re import typing as t from functools import cached_property from module.base.code_generator import CodeGenerator from module.config.utils import read_file from module.logger import logger The provided code snippet includes necessary dependencies for implementing the `replace_templates` function. Write a Python function `def replace_templates(text: str) -> str` to solve the following problem: Replace templates in data to make sure it equals to what is shown in game Examples: replace_templates("Complete Echo of War #4 time(s)") == "Complete Echo of War 1 time(s)" Here is the function: def replace_templates(text: str) -> str: """ Replace templates in data to make sure it equals to what is shown in game Examples: replace_templates("Complete Echo of War #4 time(s)") == "Complete Echo of War 1 time(s)" """ text = re.sub(r'#4', '1', text) text = re.sub(r'</?\w+>', '', text) text = re.sub(r'<color=#?\w+>', '', text) text = re.sub(r'{.*?}', '', text) return text
Replace templates in data to make sure it equals to what is shown in game Examples: replace_templates("Complete Echo of War #4 time(s)") == "Complete Echo of War 1 time(s)"
180,053
import re import typing as t from dev_tools.keywords.base import GenerateKeyword, text_to_variable from module.base.decorator import cached_property from module.config.utils import deep_get def text_to_variable(text): text = re.sub("'s |s' ", '_', text) text = re.sub(r'[ \-—:\'/•.]+', '_', text) text = re.sub(r'[(),#"?!&%*]|</?\w+>', '', text) # text = re.sub(r'[#_]?\d+(_times?)?', '', text) text = re.sub(r'<color=#?\w+>', '', text) text = text.replace('é', 'e') return text.strip('_') def dungeon_name(name: str) -> str: name = text_to_variable(name) name = re.sub('Bud_of_(Memories|Aether|Treasures)', r'Calyx_Golden_\1', name) name = re.sub('Bud_of_(.*)', r'Calyx_Crimson_\1', name).replace('Calyx_Crimson_Calyx_Crimson_', 'Calyx_Crimson_') name = re.sub('Shape_of_(.*)', r'Stagnant_Shadow_\1', name) name = re.sub('Path_of_(.*)', r'Cavern_of_Corrosion_Path_of_\1', name) if name in ['Destruction_Beginning', 'End_of_the_Eternal_Freeze', 'Divine_Seed', 'Borehole_Planet_Old_Crater']: name = f'Echo_of_War_{name}' if name in ['The_Swarm_Disaster', 'Gold_and_Gears']: name = f'Simulated_Universe_{name}' return name
null
180,054
import argparse import sys import typing as t def run(): Progress.Start() installer = Installer() Progress.ShowDeployConfig() installer.install() logger.info('Finish') Progress.Finish() def run(): for row in output.split('\n'): time.sleep(0.05) if row: logger.info(row) def run_install(): from deploy.installer import run run()
null
180,055
import argparse import sys import typing as t def run(): Progress.Start() installer = Installer() Progress.ShowDeployConfig() installer.install() logger.info('Finish') Progress.Finish() def run(): for row in output.split('\n'): time.sleep(0.05) if row: logger.info(row) def run_print_test(): from deploy.Windows.installer_test import run run()
null
180,056
import argparse import sys import typing as t def config_set(modify: t.Dict[str, str], output='./config/deploy.yaml') -> t.Dict[str, str]: """ Args: modify: A dict of key-value in deploy.yaml output: Returns: The updated key-value in deploy.yaml """ data = poor_yaml_read(DEPLOY_TEMPLATE) data.update(poor_yaml_read(output)) for k, v in modify.items(): if k in data: print(f'Key "{k}" set') data[k] = v else: print(f'Key "{k}" not exist') poor_yaml_write(data, file=output) return data def run_set(modify=t.List[str]) -> t.Dict[str, str]: data = {} for kv in modify: if "=" in kv: key, value = kv.split('=', maxsplit=1) data[key] = value from deploy.set import config_set return config_set(data)
null
180,057
import configparser import os import subprocess from time import sleep from typing import List, Dict import newrelic.agent from app.db import Session from app.log import LOG from monitor.metric_exporter import MetricExporter _NR_CONFIG_FILE_LOCATION_VAR = "NEW_RELIC_CONFIG_FILE" def get_newrelic_license() -> str: nr_file = os.environ.get(_NR_CONFIG_FILE_LOCATION_VAR, None) if nr_file is None: raise Exception(f"{_NR_CONFIG_FILE_LOCATION_VAR} not defined") config = configparser.ConfigParser() config.read(nr_file) return config["newrelic"]["license_key"]
null
180,058
import configparser import os import subprocess from time import sleep from typing import List, Dict import newrelic.agent from app.db import Session from app.log import LOG from monitor.metric_exporter import MetricExporter def nb_files(directory) -> int: """return the number of files in directory and its subdirectories""" return sum(len(files) for _, _, files in os.walk(directory)) def get_num_procs(proc_names: List[str]) -> Dict[str, int]: data = ( subprocess.Popen(["ps", "ax"], stdout=subprocess.PIPE) .communicate()[0] .decode("utf-8") ) return _process_ps_output(proc_names, data) LOG = _get_logger("SL") The provided code snippet includes necessary dependencies for implementing the `log_postfix_metrics` function. Write a Python function `def log_postfix_metrics()` to solve the following problem: Look at different metrics and alert appropriately Here is the function: def log_postfix_metrics(): """Look at different metrics and alert appropriately""" incoming_queue = nb_files("/var/spool/postfix/incoming") active_queue = nb_files("/var/spool/postfix/active") deferred_queue = nb_files("/var/spool/postfix/deferred") LOG.d("postfix queue sizes %s %s %s", incoming_queue, active_queue, deferred_queue) newrelic.agent.record_custom_metric("Custom/postfix_incoming_queue", incoming_queue) newrelic.agent.record_custom_metric("Custom/postfix_active_queue", active_queue) newrelic.agent.record_custom_metric("Custom/postfix_deferred_queue", deferred_queue) proc_counts = get_num_procs(["smtp", "smtpd", "bounce", "cleanup"]) for proc_name in proc_counts: LOG.d(f"Process count {proc_counts}") newrelic.agent.record_custom_metric( f"Custom/process_{proc_name}_count", proc_counts[proc_name] )
Look at different metrics and alert appropriately
180,059
import configparser import os import subprocess from time import sleep from typing import List, Dict import newrelic.agent from app.db import Session from app.log import LOG from monitor.metric_exporter import MetricExporter Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") def log_nb_db_connection(): # get the number of connections to the DB r = Session.execute("select count(*) from pg_stat_activity;") nb_connection = list(r)[0][0] LOG.d("number of db connections %s", nb_connection) newrelic.agent.record_custom_metric("Custom/nb_db_connections", nb_connection)
null
180,060
import argparse import email import time import uuid from email import encoders from email.encoders import encode_noop from email.message import Message from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.utils import make_msgid, formatdate, getaddresses from io import BytesIO from smtplib import SMTPRecipientsRefused, SMTPServerDisconnected from typing import List, Tuple, Optional import newrelic.agent from aiosmtpd.controller import Controller from aiosmtpd.smtp import Envelope from email_validator import validate_email, EmailNotValidError from flanker.addresslib import address from flanker.addresslib.address import EmailAddress from sqlalchemy.exc import IntegrityError from app import pgp_utils, s3, config from app.alias_utils import try_auto_create from app.config import ( EMAIL_DOMAIN, URL, UNSUBSCRIBER, LOAD_PGP_EMAIL_HANDLER, ENFORCE_SPF, ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX, ALERT_BOUNCE_EMAIL, ALERT_SPAM_EMAIL, SPAMASSASSIN_HOST, MAX_SPAM_SCORE, MAX_REPLY_PHASE_SPAM_SCORE, ALERT_SEND_EMAIL_CYCLE, ALERT_MAILBOX_IS_ALIAS, PGP_SENDER_PRIVATE_KEY, ALERT_BOUNCE_EMAIL_REPLY_PHASE, NOREPLY, BOUNCE_PREFIX, BOUNCE_SUFFIX, TRANSACTIONAL_BOUNCE_PREFIX, TRANSACTIONAL_BOUNCE_SUFFIX, ENABLE_SPAM_ASSASSIN, BOUNCE_PREFIX_FOR_REPLY_PHASE, POSTMASTER, OLD_UNSUBSCRIBER, ALERT_FROM_ADDRESS_IS_REVERSE_ALIAS, ALERT_TO_NOREPLY, ) from app.db import Session from app.email import status, headers from app.email.rate_limit import rate_limited from app.email.spam import get_spam_score from app.email_utils import ( send_email, add_dkim_signature, add_or_replace_header, delete_header, render, get_orig_message_from_bounce, delete_all_headers_except, get_spam_info, get_orig_message_from_spamassassin_report, send_email_with_rate_control, get_email_domain_part, copy, send_email_at_most_times, is_valid_alias_address_domain, should_add_dkim_signature, add_header, get_header_unicode, generate_reply_email, is_reverse_alias, replace, should_disable, parse_id_from_bounce, spf_pass, sanitize_header, get_queue_id, should_ignore_bounce, parse_full_address, get_mailbox_bounce_info, save_email_for_debugging, save_envelope_for_debugging, get_verp_info_from_email, generate_verp_email, sl_formataddr, ) from app.email_validation import is_valid_email, normalize_reply_email from app.errors import ( NonReverseAliasInReplyPhase, VERPTransactional, VERPForward, VERPReply, CannotCreateContactForReverseAlias, ) from app.handler.dmarc import ( apply_dmarc_policy_for_reply_phase, apply_dmarc_policy_for_forward_phase, ) from app.handler.provider_complaint import ( handle_hotmail_complaint, handle_yahoo_complaint, ) from app.handler.spamd_result import ( SpamdResult, SPFCheckResult, ) from app.handler.unsubscribe_generator import UnsubscribeGenerator from app.handler.unsubscribe_handler import UnsubscribeHandler from app.log import LOG, set_message_id from app.mail_sender import sl_sendmail from app.message_utils import message_to_bytes from app.models import ( Alias, Contact, BlockBehaviourEnum, EmailLog, User, RefusedEmail, Mailbox, Bounce, TransactionalEmail, IgnoredEmail, MessageIDMatching, Notification, VerpType, SLDomain, ) from app.pgp_utils import ( PGPException, sign_data_with_pgpy, sign_data, load_public_key_and_check, ) from app.utils import sanitize_email, canonicalize_email from init_app import load_pgp_public_keys from server import create_light_app def handle_forward(envelope, msg: Message, rcpt_to: str) -> List[Tuple[bool, str]]: """return an array of SMTP status (is_success, smtp_status) is_success indicates whether an email has been delivered and smtp_status is the SMTP Status ("250 Message accepted", "550 Non-existent email address", etc.) """ alias_address = rcpt_to # alias@SL alias = Alias.get_by(email=alias_address) if not alias: LOG.d( "alias %s not exist. Try to see if it can be created on the fly", alias_address, ) alias = try_auto_create(alias_address) if not alias: LOG.d("alias %s cannot be created on-the-fly, return 550", alias_address) if should_ignore_bounce(envelope.mail_from): return [(True, status.E207)] else: return [(False, status.E515)] user = alias.user if not user.is_active(): LOG.w(f"User {user} has been soft deleted") return False, status.E502 if not user.can_send_or_receive(): LOG.i(f"User {user} cannot receive emails") if should_ignore_bounce(envelope.mail_from): return [(True, status.E207)] else: return [(False, status.E504)] # check if email is sent from alias's owning mailbox(es) mail_from = envelope.mail_from for addr in alias.authorized_addresses(): # email sent from a mailbox to its alias if addr == mail_from: LOG.i("cycle email sent from %s to %s", addr, alias) handle_email_sent_to_ourself(alias, addr, msg, user) return [(True, status.E209)] from_header = get_header_unicode(msg[headers.FROM]) LOG.d("Create or get contact for from_header:%s", from_header) contact = get_or_create_contact(from_header, envelope.mail_from, alias) reply_to_contact = None if msg[headers.REPLY_TO]: reply_to = get_header_unicode(msg[headers.REPLY_TO]) LOG.d("Create or get contact for reply_to_header:%s", reply_to) # ignore when reply-to = alias if reply_to == alias.email: LOG.i("Reply-to same as alias %s", alias) else: reply_to_contact = get_or_create_reply_to_contact(reply_to, alias, msg) if not alias.enabled or contact.block_forward: LOG.d("%s is disabled, do not forward", alias) EmailLog.create( contact_id=contact.id, user_id=contact.user_id, blocked=True, alias_id=contact.alias_id, commit=True, ) # by default return 2** instead of 5** to allow user to receive emails again # when alias is enabled or contact is unblocked res_status = status.E200 if user.block_behaviour == BlockBehaviourEnum.return_5xx: res_status = status.E502 return [(True, res_status)] # Check if we need to reject or quarantine based on dmarc msg, dmarc_delivery_status = apply_dmarc_policy_for_forward_phase( alias, contact, envelope, msg ) if dmarc_delivery_status is not None: return [(False, dmarc_delivery_status)] ret = [] mailboxes = alias.mailboxes # no valid mailbox if not mailboxes: LOG.w("no valid mailboxes for %s", alias) if should_ignore_bounce(envelope.mail_from): return [(True, status.E207)] else: return [(False, status.E516)] for mailbox in mailboxes: if not mailbox.verified: LOG.d("%s unverified, do not forward", mailbox) ret.append((False, status.E517)) else: # Check if the mailbox is also an alias and stop the loop mailbox_as_alias = Alias.get_by(email=mailbox.email) if mailbox_as_alias is not None: LOG.info( f"Mailbox {mailbox.id} has email {mailbox.email} that is also alias {alias.id}. Stopping loop" ) mailbox.verified = False Session.commit() mailbox_url = f"{URL}/dashboard/mailbox/{mailbox.id}/" send_email_with_rate_control( user, ALERT_MAILBOX_IS_ALIAS, user.email, f"Your mailbox {mailbox.email} is an alias", render( "transactional/mailbox-invalid.txt.jinja2", mailbox=mailbox, mailbox_url=mailbox_url, alias=alias, ), render( "transactional/mailbox-invalid.html", mailbox=mailbox, mailbox_url=mailbox_url, alias=alias, ), max_nb_alert=1, ) ret.append((False, status.E525)) continue # create a copy of message for each forward ret.append( forward_email_to_mailbox( alias, copy(msg), contact, envelope, mailbox, user, reply_to_contact ) ) return ret def handle_reply(envelope, msg: Message, rcpt_to: str) -> (bool, str): """ Return whether an email has been delivered and the smtp status ("250 Message accepted", "550 Non-existent email address", etc) """ reply_email = rcpt_to reply_domain = get_email_domain_part(reply_email) # reply_email must end with EMAIL_DOMAIN or a domain that can be used as reverse alias domain if not reply_email.endswith(EMAIL_DOMAIN): sl_domain: SLDomain = SLDomain.get_by(domain=reply_domain) if sl_domain is None: LOG.w(f"Reply email {reply_email} has wrong domain") return False, status.E501 # handle case where reply email is generated with non-allowed char reply_email = normalize_reply_email(reply_email) contact = Contact.get_by(reply_email=reply_email) if not contact: LOG.w(f"No contact with {reply_email} as reverse alias") return False, status.E502 if not contact.user.is_active(): LOG.w(f"User {contact.user} has been soft deleted") return False, status.E502 alias = contact.alias alias_address: str = contact.alias.email alias_domain = get_email_domain_part(alias_address) # Sanity check: verify alias domain is managed by SimpleLogin # scenario: a user have removed a domain but due to a bug, the aliases are still there if not is_valid_alias_address_domain(alias.email): LOG.e("%s domain isn't known", alias) return False, status.E503 user = alias.user mail_from = envelope.mail_from if not user.can_send_or_receive(): LOG.i(f"User {user} cannot send emails") return False, status.E504 # Check if we need to reject or quarantine based on dmarc dmarc_delivery_status = apply_dmarc_policy_for_reply_phase( alias, contact, envelope, msg ) if dmarc_delivery_status is not None: return False, dmarc_delivery_status # Anti-spoofing mailbox = get_mailbox_from_mail_from(mail_from, alias) if not mailbox: if alias.disable_email_spoofing_check: # ignore this error, use default alias mailbox LOG.w( "ignore unknown sender to reverse-alias %s: %s -> %s", mail_from, alias, contact, ) mailbox = alias.mailbox else: # only mailbox can send email to the reply-email handle_unknown_mailbox(envelope, msg, reply_email, user, alias, contact) # return 2** to avoid Postfix sending out bounces and avoid backscatter issue return False, status.E214 if ENFORCE_SPF and mailbox.force_spf and not alias.disable_email_spoofing_check: if not spf_pass(envelope, mailbox, user, alias, contact.website_email, msg): # cannot use 4** here as sender will retry. # cannot use 5** because that generates bounce report return True, status.E201 email_log = EmailLog.create( contact_id=contact.id, alias_id=contact.alias_id, is_reply=True, user_id=contact.user_id, mailbox_id=mailbox.id, message_id=msg[headers.MESSAGE_ID], commit=True, ) LOG.d("Create %s for %s, %s, %s", email_log, contact, user, mailbox) # Spam check if ENABLE_SPAM_ASSASSIN: spam_status = "" is_spam = False # do not use user.max_spam_score here if SPAMASSASSIN_HOST: start = time.time() spam_score, spam_report = get_spam_score(msg, email_log) LOG.d( "%s -> %s - spam score %s in %s seconds. Spam report %s", alias, contact, spam_score, time.time() - start, spam_report, ) email_log.spam_score = spam_score if spam_score > MAX_REPLY_PHASE_SPAM_SCORE: is_spam = True # only set the spam report for spam email_log.spam_report = spam_report else: is_spam, spam_status = get_spam_info( msg, max_score=MAX_REPLY_PHASE_SPAM_SCORE ) if is_spam: LOG.w( "Email detected as spam. Reply phase. %s -> %s. Spam Score: %s, Spam Report: %s", alias, contact, email_log.spam_score, email_log.spam_report, ) email_log.is_spam = True email_log.spam_status = spam_status Session.commit() handle_spam(contact, alias, msg, user, mailbox, email_log, is_reply=True) return False, status.E506 delete_all_headers_except( msg, [ headers.FROM, headers.TO, headers.CC, headers.SUBJECT, headers.DATE, # do not delete original message id headers.MESSAGE_ID, # References and In-Reply-To are used for keeping the email thread headers.REFERENCES, headers.IN_REPLY_TO, ] + headers.MIME_HEADERS, ) orig_to = msg[headers.TO] orig_cc = msg[headers.CC] # replace the reverse-alias by the contact email in the email body # as this is usually included when replying if user.replace_reverse_alias: LOG.d("Replace reverse-alias %s by contact email %s", reply_email, contact) msg = replace(msg, reply_email, contact.website_email) LOG.d("Replace mailbox %s by alias email %s", mailbox.email, alias.email) msg = replace(msg, mailbox.email, alias.email) if config.ENABLE_ALL_REVERSE_ALIAS_REPLACEMENT: start = time.time() # MAX_NB_REVERSE_ALIAS_REPLACEMENT is there to limit potential attack contact_query = ( Contact.query() .filter(Contact.alias_id == alias.id) .limit(config.MAX_NB_REVERSE_ALIAS_REPLACEMENT) ) # replace reverse alias by real address for all contacts for reply_email, website_email in contact_query.values( Contact.reply_email, Contact.website_email ): msg = replace(msg, reply_email, website_email) elapsed = time.time() - start LOG.d( "Replace reverse alias by real address for %s contacts takes %s seconds", contact_query.count(), elapsed, ) newrelic.agent.record_custom_metric( "Custom/reverse_alias_replacement_time", elapsed ) # create PGP email if needed if contact.pgp_finger_print and user.is_premium(): LOG.d("Encrypt message for contact %s", contact) try: msg = prepare_pgp_message( msg, contact.pgp_finger_print, contact.pgp_public_key ) except PGPException: LOG.e( "Cannot encrypt message %s -> %s. %s %s", alias, contact, mailbox, user ) # programming error, user shouldn't see a new email log EmailLog.delete(email_log.id, commit=True) # return 421 so the client can retry later return False, status.E402 Session.commit() # make the email comes from alias from_header = alias.email # add alias name from alias if alias.name: LOG.d("Put alias name %s in from header", alias.name) from_header = sl_formataddr((alias.name, alias.email)) elif alias.custom_domain: # add alias name from domain if alias.custom_domain.name: LOG.d( "Put domain default alias name %s in from header", alias.custom_domain.name, ) from_header = sl_formataddr((alias.custom_domain.name, alias.email)) LOG.d("From header is %s", from_header) add_or_replace_header(msg, headers.FROM, from_header) try: if str(msg[headers.TO]).lower() == "undisclosed-recipients:;": # no need to replace TO header LOG.d("email is sent in BCC mode") else: replace_header_when_reply(msg, alias, headers.TO) replace_header_when_reply(msg, alias, headers.CC) except NonReverseAliasInReplyPhase as e: LOG.w("non reverse-alias in reply %s %s %s", e, contact, alias) # the email is ignored, delete the email log EmailLog.delete(email_log.id, commit=True) send_email( mailbox.email, f"Email sent to {contact.email} contains non reverse-alias addresses", render( "transactional/non-reverse-alias-reply-phase.txt.jinja2", destination=contact.email, alias=alias.email, subject=msg[headers.SUBJECT], ), ) # user is informed and will retry return True, status.E200 replace_original_message_id(alias, email_log, msg) if not msg[headers.DATE]: date_header = formatdate() LOG.w("missing date header, add one") msg[headers.DATE] = date_header msg[headers.SL_DIRECTION] = "Reply" msg[headers.SL_EMAIL_LOG_ID] = str(email_log.id) LOG.d( "send email from %s to %s, mail_options:%s,rcpt_options:%s", alias.email, contact.website_email, envelope.mail_options, envelope.rcpt_options, ) if should_add_dkim_signature(alias_domain): add_dkim_signature(msg, alias_domain) try: sl_sendmail( generate_verp_email(VerpType.bounce_reply, email_log.id, alias_domain), contact.website_email, msg, envelope.mail_options, envelope.rcpt_options, is_forward=False, ) # if alias belongs to several mailboxes, notify other mailboxes about this email other_mailboxes = [mb for mb in alias.mailboxes if mb.email != mailbox.email] for mb in other_mailboxes: notify_mailbox(alias, mailbox, mb, msg, orig_to, orig_cc, alias_domain) except Exception: LOG.w("Cannot send email from %s to %s", alias, contact) EmailLog.delete(email_log.id, commit=True) send_email( mailbox.email, f"Email cannot be sent to {contact.email} from {alias.email}", render( "transactional/reply-error.txt.jinja2", user=user, alias=alias, contact=contact, contact_domain=get_email_domain_part(contact.email), ), render( "transactional/reply-error.html", user=user, alias=alias, contact=contact, contact_domain=get_email_domain_part(contact.email), ), ) # return 250 even if error as user is already informed of the incident and can retry sending the email return True, status.E200 def is_automatic_out_of_office(msg: Message) -> bool: """ Return whether an email is out-of-office For info, out-of-office is sent to the envelope mail_from and not the From: header More info on https://datatracker.ietf.org/doc/html/rfc3834#section-4 and https://support.google.com/mail/thread/21246740/my-auto-reply-filter-isn-t-replying-to-original-sender-address?hl=en&msgid=21261237 """ if msg[headers.AUTO_SUBMITTED] is None: return False if msg[headers.AUTO_SUBMITTED].lower() in ("auto-replied", "auto-generated"): LOG.d( "out-of-office email %s:%s", headers.AUTO_SUBMITTED, msg[headers.AUTO_SUBMITTED], ) return True return False def is_bounce(envelope: Envelope, msg: Message): """Detect whether an email is a Delivery Status Notification""" return ( envelope.mail_from == "<>" and msg.get_content_type().lower() == "multipart/report" ) def handle_transactional_bounce( envelope: Envelope, msg, rcpt_to, transactional_id=None ): LOG.d("handle transactional bounce sent to %s", rcpt_to) if transactional_id is None: LOG.i( f"No transactional record for {envelope.mail_from} -> {envelope.rcpt_tos}" ) return transactional = TransactionalEmail.get(transactional_id) # a transaction might have been deleted in delete_logs() if not transactional: LOG.i( f"No transactional record for {envelope.mail_from} -> {envelope.rcpt_tos}" ) return LOG.i("Create bounce for %s", transactional.email) bounce_info = get_mailbox_bounce_info(msg) if bounce_info: Bounce.create( email=transactional.email, info=bounce_info.as_bytes().decode(), commit=True, ) else: LOG.w("cannot get bounce info, debug at %s", save_email_for_debugging(msg)) Bounce.create(email=transactional.email, commit=True) def handle_bounce(envelope, email_log: EmailLog, msg: Message) -> str: """ Return SMTP status, e.g. "500 Error" """ if not email_log: LOG.w("No such email log") return status.E512 contact: Contact = email_log.contact alias = contact.alias LOG.d( "handle bounce for %s, phase=%s, contact=%s, alias=%s", email_log, email_log.get_phase(), contact, alias, ) if not email_log.user.is_active(): LOG.d(f"User {email_log.user} is not active") return status.E510 if email_log.is_reply: content_type = msg.get_content_type().lower() if content_type != "multipart/report" or envelope.mail_from != "<>": # forward the email again to the alias LOG.i( "Handle auto reply %s %s", content_type, envelope.mail_from, ) contact: Contact = email_log.contact alias = contact.alias email_log.auto_replied = True Session.commit() # replace the BOUNCE_EMAIL by alias in To field add_or_replace_header(msg, "To", alias.email) envelope.rcpt_tos = [alias.email] # same as handle() # result of all deliveries # each element is a couple of whether the delivery is successful and the smtp status res: [(bool, str)] = [] for is_delivered, smtp_status in handle_forward(envelope, msg, alias.email): res.append((is_delivered, smtp_status)) for is_success, smtp_status in res: # Consider all deliveries successful if 1 delivery is successful if is_success: return smtp_status # Failed delivery for all, return the first failure return res[0][1] handle_bounce_reply_phase(envelope, msg, email_log) return status.E212 else: # forward phase handle_bounce_forward_phase(msg, email_log) return status.E211 def should_ignore(mail_from: str, rcpt_tos: List[str]) -> bool: if len(rcpt_tos) != 1: return False rcpt_to = rcpt_tos[0] if IgnoredEmail.get_by(mail_from=mail_from, rcpt_to=rcpt_to): return True return False def send_no_reply_response(mail_from: str, msg: Message): mailbox = Mailbox.get_by(email=mail_from) if not mailbox: LOG.d("Unknown sender. Skipping reply from {}".format(NOREPLY)) return if not mailbox.user.is_active(): LOG.d(f"User {mailbox.user} is soft-deleted. Skipping sending reply response") return send_email_at_most_times( mailbox.user, ALERT_TO_NOREPLY, mailbox.user.email, "Auto: {}".format(msg[headers.SUBJECT] or "No subject"), render("transactional/noreply.text.jinja2"), ) def handle_out_of_office_reply_phase(email_log, envelope, msg, rcpt_tos): """convert the email into a normal email sent to the alias, so it can be forwarded to mailbox""" LOG.d( "send the out-of-office email to the alias %s, old to_header:%s rcpt_tos:%s, %s", email_log.alias, msg[headers.TO], rcpt_tos, email_log, ) alias_address = email_log.alias.email rcpt_tos[0] = alias_address envelope.rcpt_tos = [alias_address] add_or_replace_header(msg, headers.TO, alias_address) # delete reply-to header that can affect email delivery delete_header(msg, headers.REPLY_TO) LOG.d( "after out-of-office transformation to_header:%s reply_to:%s rcpt_tos:%s", msg.get_all(headers.TO), msg.get_all(headers.REPLY_TO), rcpt_tos, ) def handle_out_of_office_forward_phase(email_log, envelope, msg, rcpt_tos): """convert the email into a normal email sent to the reverse alias, so it can be forwarded to contact""" LOG.d( "send the out-of-office email to the contact %s, old to_header:%s rcpt_tos:%s %s", email_log.contact, msg[headers.TO], rcpt_tos, email_log, ) reverse_alias = email_log.contact.reply_email rcpt_tos[0] = reverse_alias envelope.rcpt_tos = [reverse_alias] add_or_replace_header(msg, headers.TO, reverse_alias) # delete reply-to header that can affect email delivery delete_header(msg, headers.REPLY_TO) LOG.d( "after out-of-office transformation to_header:%s reply_to:%s rcpt_tos:%s", msg.get_all(headers.TO), msg.get_all(headers.REPLY_TO), rcpt_tos, ) BOUNCE_PREFIX = os.environ.get("BOUNCE_PREFIX") or "bounce+" BOUNCE_SUFFIX = os.environ.get("BOUNCE_SUFFIX") or f"+@{EMAIL_DOMAIN}" BOUNCE_PREFIX_FOR_REPLY_PHASE = ( os.environ.get("BOUNCE_PREFIX_FOR_REPLY_PHASE") or "bounce_reply" ) TRANSACTIONAL_BOUNCE_PREFIX = ( os.environ.get("TRANSACTIONAL_BOUNCE_PREFIX") or "transactional+" ) TRANSACTIONAL_BOUNCE_SUFFIX = ( os.environ.get("TRANSACTIONAL_BOUNCE_SUFFIX") or f"+@{EMAIL_DOMAIN}" ) UNSUBSCRIBER = os.environ.get("UNSUBSCRIBER") OLD_UNSUBSCRIBER = os.environ.get("OLD_UNSUBSCRIBER") ALERT_FROM_ADDRESS_IS_REVERSE_ALIAS = "from_address_is_reverse_alias" NOREPLY = os.environ.get("NOREPLY", f"noreply@{EMAIL_DOMAIN}") POSTMASTER = os.environ.get("POSTMASTER") def rate_limited(mail_from: str, rcpt_tos: [str]) -> bool: # todo: re-enable rate limiting return False for rcpt_to in rcpt_tos: if is_reverse_alias(rcpt_to): if rate_limited_reply_phase(rcpt_to): return True else: # Forward phase address = rcpt_to # alias@SL if rate_limited_forward_phase(address): return True return False from copy import deepcopy def render(template_name, **kwargs) -> str: templates_dir = os.path.join(config.ROOT_DIR, "templates", "emails") env = Environment(loader=FileSystemLoader(templates_dir)) template = env.get_template(template_name) return template.render( MAX_NB_EMAIL_FREE_PLAN=config.MAX_NB_EMAIL_FREE_PLAN, URL=config.URL, LANDING_PAGE_URL=config.LANDING_PAGE_URL, YEAR=arrow.now().year, **kwargs, ) def send_email_at_most_times( user: User, alert_type: str, to_email: str, subject, plaintext, html=None, max_times=1, ) -> bool: """Same as send_email with rate control over alert_type. Sent at most `max_times` This is used to inform users about a warning. Return true if the email is sent, otherwise False """ to_email = sanitize_email(to_email) nb_alert = SentAlert.filter_by(alert_type=alert_type, to_email=to_email).count() if nb_alert >= max_times: LOG.w( "%s emails were sent to %s alert type %s", nb_alert, to_email, alert_type, ) return False SentAlert.create(user_id=user.id, alert_type=alert_type, to_email=to_email) Session.commit() send_email(to_email, subject, plaintext, html) return True def sanitize_header(msg: Message, header: str): """remove trailing space and remove linebreak from a header""" header_lowercase = header.lower() for i in reversed(range(len(msg._headers))): header_name = msg._headers[i][0].lower() if header_name == header_lowercase: # msg._headers[i] is a tuple like ('From', 'hey@google.com') if msg._headers[i][1]: msg._headers[i] = ( msg._headers[i][0], msg._headers[i][1].strip().replace("\n", " "), ) def get_header_unicode(header: Union[str, Header]) -> str: """ Convert a header to unicode Should be used to handle headers like From:, To:, CC:, Subject: """ if header is None: return "" ret = "" for to_decoded_str, charset in decode_header(header): if charset is None: if isinstance(to_decoded_str, bytes): decoded_str = to_decoded_str.decode() else: decoded_str = to_decoded_str else: try: decoded_str = to_decoded_str.decode(charset) except (LookupError, UnicodeDecodeError): # charset is unknown LOG.w("Cannot decode %s with %s, try utf-8", to_decoded_str, charset) try: decoded_str = to_decoded_str.decode("utf-8") except UnicodeDecodeError: LOG.w("Cannot UTF-8 decode %s", to_decoded_str) decoded_str = to_decoded_str.decode("utf-8", errors="replace") ret += decoded_str return ret def copy(msg: Message) -> Message: """return a copy of message""" try: return deepcopy(msg) except Exception: LOG.w("deepcopy fails, try string parsing") try: return message_from_string(msg.as_string()) except (UnicodeEncodeError, LookupError): LOG.w("as_string() fails, try bytes parsing") return message_from_bytes(message_to_bytes(msg)) def is_reverse_alias(address: str) -> bool: # to take into account the new reverse-alias that doesn't start with "ra+" if Contact.get_by(reply_email=address): return True return address.endswith(f"@{config.EMAIL_DOMAIN}") and ( address.startswith("reply+") or address.startswith("ra+") ) def parse_id_from_bounce(email_address: str) -> int: return int(email_address[email_address.find("+") : email_address.rfind("+")]) def get_queue_id(msg: Message) -> Optional[str]: """Get the Postfix queue-id from a message""" header_values = msg.get_all(headers.RSPAMD_QUEUE_ID) if header_values: # Get last in case somebody tries to inject a header return header_values[-1] received_header = str(msg[headers.RECEIVED]) if not received_header: return # received_header looks like 'from mail-wr1-x434.google.com (mail-wr1-x434.google.com [IPv6:2a00:1450:4864:20::434])\r\n\t(using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits))\r\n\t(No client certificate requested)\r\n\tby mx1.simplelogin.co (Postfix) with ESMTPS id 4FxQmw1DXdz2vK2\r\n\tfor <jglfdjgld@alias.com>; Fri, 4 Jun 2021 14:55:43 +0000 (UTC)' search_result = re.search("with ESMTPS id [0-9a-zA-Z]{1,}", received_header) if not search_result: return # the "with ESMTPS id 4FxQmw1DXdz2vK2" part with_esmtps = received_header[search_result.start() : search_result.end()] return with_esmtps[len("with ESMTPS id ") :] def should_ignore_bounce(mail_from: str) -> bool: if IgnoreBounceSender.get_by(mail_from=mail_from): LOG.w("do not send back bounce report to %s", mail_from) return True return False def parse_full_address(full_address) -> (str, str): """ parse the email address full format and return the display name and address For ex: ab <cd@xy.com> -> (ab, cd@xy.com) '=?UTF-8?B?TmjGoW4gTmd1eeG7hW4=?= <abcd@gmail.com>' -> ('Nhơn Nguyễn', "abcd@gmail.com") If the parsing fails, raise ValueError """ full_address: EmailAddress = address.parse(full_address) if full_address is None: raise ValueError # address.parse can also parse a URL and return UrlAddress if type(full_address) is not EmailAddress: raise ValueError return full_address.display_name, full_address.address def save_email_for_debugging(msg: Message, file_name_prefix=None) -> str: """Save email for debugging to temporary location Return the file path """ if config.TEMP_DIR: file_name = str(uuid.uuid4()) + ".eml" if file_name_prefix: file_name = "{}-{}".format(file_name_prefix, file_name) with open(os.path.join(config.TEMP_DIR, file_name), "wb") as f: f.write(msg.as_bytes()) LOG.d("email saved to %s", file_name) return file_name return "" def get_verp_info_from_email(email: str) -> Optional[Tuple[VerpType, int]]: """This method processes the email address, checks if it's a signed verp email generated by us to receive bounces and extracts the type of verp email and associated email log id/transactional email id stored as object_id """ idx = email.find("@") if idx == -1: return None username = email[:idx] fields = username.split(".") if len(fields) != 3 or fields[0] != config.VERP_PREFIX: return None try: padding = (8 - (len(fields[1]) % 8)) % 8 payload = base64.b32decode(fields[1].encode("utf-8").upper() + (b"=" * padding)) padding = (8 - (len(fields[2]) % 8)) % 8 signature = base64.b32decode( fields[2].encode("utf-8").upper() + (b"=" * padding) ) except binascii.Error: return None expected_signature = hmac.new( config.VERP_EMAIL_SECRET.encode("utf-8"), payload, VERP_HMAC_ALGO ).digest()[:8] if expected_signature != signature: return None data = json.loads(payload) # verp type, object_id, time if len(data) != 3: return None if data[2] > (time.time() + config.VERP_MESSAGE_LIFETIME - VERP_TIME_START) / 60: return None return VerpType(data[0]), data[1] class VERPTransactional(SLException): """raised an email sent to a transactional VERP can't be handled""" pass class VERPForward(SLException): """raised an email sent to a forward VERP can't be handled""" pass class VERPReply(SLException): """raised an email sent to a reply VERP can't be handled""" pass def handle_hotmail_complaint(message: Message) -> bool: return handle_complaint(message, ProviderComplaintHotmail()) def handle_yahoo_complaint(message: Message) -> bool: return handle_complaint(message, ProviderComplaintYahoo()) class UnsubscribeHandler: def _extract_unsub_info_from_message( self, message: Message ) -> Optional[UnsubscribeData]: header_value = message[headers.SUBJECT] if not header_value: return None return UnsubscribeEncoder.decode_subject(header_value) def handle_unsubscribe_from_message(self, envelope: Envelope, msg: Message) -> str: unsub_data = self._extract_unsub_info_from_message(msg) if not unsub_data: LOG.w("Wrong format subject %s", msg[headers.SUBJECT]) return status.E507 mailbox = Mailbox.get_by(email=envelope.mail_from) if not mailbox: LOG.w("Unknown mailbox %s", envelope.mail_from) return status.E507 if unsub_data.action == UnsubscribeAction.DisableAlias: return self._disable_alias(unsub_data.data, mailbox.user, mailbox) elif unsub_data.action == UnsubscribeAction.DisableContact: return self._disable_contact(unsub_data.data, mailbox.user, mailbox) elif unsub_data.action == UnsubscribeAction.UnsubscribeNewsletter: return self._unsubscribe_user_from_newsletter(unsub_data.data, mailbox.user) elif unsub_data.action == UnsubscribeAction.OriginalUnsubscribeMailto: return self._unsubscribe_original_behaviour(unsub_data.data, mailbox.user) else: raise Exception(f"Unknown unsubscribe action {unsub_data.action}") def handle_unsubscribe_from_request( self, user: User, unsub_request: str ) -> Optional[UnsubscribeData]: unsub_data = UnsubscribeEncoder.decode_subject(unsub_request) if not unsub_data: LOG.w("Wrong request %s", unsub_request) return None if unsub_data.action == UnsubscribeAction.DisableAlias: response_code = self._disable_alias(unsub_data.data, user) elif unsub_data.action == UnsubscribeAction.DisableContact: response_code = self._disable_contact(unsub_data.data, user) elif unsub_data.action == UnsubscribeAction.UnsubscribeNewsletter: response_code = self._unsubscribe_user_from_newsletter( unsub_data.data, user ) elif unsub_data.action == UnsubscribeAction.OriginalUnsubscribeMailto: response_code = self._unsubscribe_original_behaviour(unsub_data.data, user) else: raise Exception(f"Unknown unsubscribe action {unsub_data.action}") if response_code == status.E202: return unsub_data return None def _disable_alias( self, alias_id: int, user: User, mailbox: Optional[Mailbox] = None ) -> str: alias = Alias.get(alias_id) if not alias: return status.E508 if alias.user_id != user.id: LOG.w("Alias doesn't belong to user") return status.E508 # Only alias's owning mailbox can send the unsubscribe request if mailbox and not self._check_email_is_authorized_for_alias( mailbox.email, alias ): return status.E509 alias.enabled = False Session.commit() enable_alias_url = config.URL + f"/dashboard/?highlight_alias_id={alias.id}" for mailbox in alias.mailboxes: send_email( mailbox.email, f"Alias {alias.email} has been disabled successfully", render( "transactional/unsubscribe-disable-alias.txt", user=alias.user, alias=alias.email, enable_alias_url=enable_alias_url, ), render( "transactional/unsubscribe-disable-alias.html", user=alias.user, alias=alias.email, enable_alias_url=enable_alias_url, ), ) return status.E202 def _disable_contact( self, contact_id: int, user: User, mailbox: Optional[Mailbox] = None ) -> str: contact = Contact.get(contact_id) if not contact: return status.E508 if contact.user_id != user.id: LOG.w("Contact doesn't belong to user") return status.E508 # Only contact's owning mailbox can send the unsubscribe request if mailbox and not self._check_email_is_authorized_for_alias( mailbox.email, contact.alias ): return status.E509 alias = contact.alias contact.block_forward = True Session.commit() unblock_contact_url = ( config.URL + f"/dashboard/alias_contact_manager/{alias.id}?highlight_contact_id={contact.id}" ) for mailbox in alias.mailboxes: send_email( mailbox.email, f"Emails from {contact.website_email} to {alias.email} are now blocked", render( "transactional/unsubscribe-block-contact.txt.jinja2", user=alias.user, alias=alias, contact=contact, unblock_contact_url=unblock_contact_url, ), ) return status.E202 def _unsubscribe_user_from_newsletter( self, user_id: int, request_user: User ) -> str: """return the SMTP status""" user = User.get(user_id) if not user: LOG.w("No such user %s", user_id) return status.E510 if user.id != request_user.id: LOG.w("Unauthorized unsubscribe user from", request_user) return status.E511 user.notification = False Session.commit() send_email( user.email, "You have been unsubscribed from SimpleLogin newsletter", render( "transactional/unsubscribe-newsletter.txt", user=user, ), render( "transactional/unsubscribe-newsletter.html", user=user, ), ) return status.E202 def _check_email_is_authorized_for_alias( self, email_address: str, alias: Alias ) -> bool: """return if the email_address is authorized to unsubscribe from an alias or block a contact Usually the mail_from=mailbox.email but it can also be one of the authorized address """ for mailbox in alias.mailboxes: if mailbox.email == email_address: return True for authorized_address in mailbox.authorized_addresses: if authorized_address.email == email_address: LOG.d( "Found an authorized address for %s %s %s", alias, mailbox, authorized_address, ) return True LOG.d( "%s cannot disable alias %s. Alias authorized addresses:%s", email_address, alias, alias.authorized_addresses, ) return False def _unsubscribe_original_behaviour( self, original_unsub_data: UnsubscribeOriginalData, user: User ) -> str: alias = Alias.get(original_unsub_data.alias_id) if not alias: return status.E508 if alias.user_id != user.id: return status.E509 email_domain = get_email_domain_part(alias.email) to_email = sanitize_email(original_unsub_data.recipient) msg = EmailMessage() msg[headers.TO] = to_email msg[headers.SUBJECT] = original_unsub_data.subject msg[headers.FROM] = alias.email msg[headers.MESSAGE_ID] = make_msgid(domain=email_domain) msg[headers.DATE] = formatdate() msg[headers.CONTENT_TYPE] = "text/plain" msg[headers.MIME_VERSION] = "1.0" msg.set_payload("") add_dkim_signature(msg, email_domain) transaction = TransactionalEmail.create(email=to_email, commit=True) sl_sendmail( generate_verp_email( VerpType.transactional, transaction.id, sender_domain=email_domain ), to_email, msg, retries=3, ignore_smtp_error=True, ) return status.E202 def set_message_id(message_id): global _MESSAGE_ID LOG.d("set message_id %s", message_id) _MESSAGE_ID = message_id LOG = _get_logger("SL") class VerpType(EnumE): bounce_forward = 0 bounce_reply = 1 transactional = 2 class Alias(Base, ModelMixin): __tablename__ = "alias" FLAG_PARTNER_CREATED = 1 << 0 user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True ) email = sa.Column(sa.String(128), unique=True, nullable=False) # the name to use when user replies/sends from alias name = sa.Column(sa.String(128), nullable=True, default=None) enabled = sa.Column(sa.Boolean(), default=True, nullable=False) flags = sa.Column( sa.BigInteger(), default=0, server_default="0", nullable=False, index=True ) custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True ) custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id]) # To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature automatic_creation = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # to know whether an alias belongs to a directory directory_id = sa.Column( sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True ) note = sa.Column(sa.Text, default=None, nullable=True) # an alias can be owned by another mailbox mailbox_id = sa.Column( sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True ) # prefix _ to avoid this object being used accidentally. # To have the list of all mailboxes, should use AliasInfo instead _mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined") # If the mailbox has PGP-enabled, user can choose disable the PGP on the alias # this is useful when some senders already support PGP disable_pgp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # a way to bypass the bounce automatic disable mechanism cannot_be_disabled = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # when a mailbox wants to send an email on behalf of the alias via the reverse-alias # several checks are performed to avoid email spoofing # this option allow disabling these checks disable_email_spoofing_check = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # to know whether an alias is added using a batch import batch_import_id = sa.Column( sa.ForeignKey("batch_import.id", ondelete="SET NULL"), nullable=True, default=None, ) # set in case of alias transfer. original_owner_id = sa.Column( sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True ) # alias is pinned on top pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0") # used to transfer an alias to another user transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True) transfer_token_expiration = sa.Column( ArrowType, default=arrow.utcnow, nullable=True ) # have I been pwned hibp_last_check = sa.Column(ArrowType, default=None, index=True) hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp") # to use Postgres full text search. Only applied on "note" column for now # this is a generated Postgres column ts_vector = sa.Column( TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True) ) last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True) __table_args__ = ( Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"), # index on note column using pg_trgm Index( "note_pg_trgm_index", "note", postgresql_ops={"note": "gin_trgm_ops"}, postgresql_using="gin", ), ) user = orm.relationship(User, foreign_keys=[user_id]) mailbox = orm.relationship("Mailbox", lazy="joined") def mailboxes(self): ret = [self.mailbox] for m in self._mailboxes: if m.id is not self.mailbox.id: ret.append(m) ret = [mb for mb in ret if mb.verified] ret = sorted(ret, key=lambda mb: mb.email) return ret def authorized_addresses(self) -> [str]: """return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases Including its mailboxes and their authorized addresses """ mailboxes = self.mailboxes ret = [mb.email for mb in mailboxes] for mailbox in mailboxes: for aa in mailbox.authorized_addresses: ret.append(aa.email) return ret def mailbox_support_pgp(self) -> bool: """return True of one of the mailboxes support PGP""" for mb in self.mailboxes: if mb.pgp_enabled(): return True return False def pgp_enabled(self) -> bool: if self.mailbox_support_pgp() and not self.disable_pgp: return True return False def get_custom_domain(alias_address) -> Optional["CustomDomain"]: alias_domain = validate_email( alias_address, check_deliverability=False, allow_smtputf8=False ).domain # handle the case a SLDomain is also a CustomDomain if SLDomain.get_by(domain=alias_domain) is None: custom_domain = CustomDomain.get_by(domain=alias_domain) if custom_domain: return custom_domain def create(cls, **kw): commit = kw.pop("commit", False) flush = kw.pop("flush", False) new_alias = cls(**kw) user = User.get(new_alias.user_id) if user.is_premium(): limits = config.ALIAS_CREATE_RATE_LIMIT_PAID else: limits = config.ALIAS_CREATE_RATE_LIMIT_FREE # limits is array of (hits,days) for limit in limits: key = f"alias_create_{limit[1]}d:{user.id}" rate_limiter.check_bucket_limit(key, limit[0], limit[1]) email = kw["email"] # make sure email is lowercase and doesn't have any whitespace email = sanitize_email(email) # make sure alias is not in global trash, i.e. DeletedAlias table if DeletedAlias.get_by(email=email): raise AliasInTrashError if DomainDeletedAlias.get_by(email=email): raise AliasInTrashError # detect whether alias should belong to a custom domain if "custom_domain_id" not in kw: custom_domain = Alias.get_custom_domain(email) if custom_domain: new_alias.custom_domain_id = custom_domain.id Session.add(new_alias) DailyMetric.get_or_create_today_metric().nb_alias += 1 if commit: Session.commit() if flush: Session.flush() return new_alias def create_new(cls, user, prefix, note=None, mailbox_id=None): prefix = prefix.lower().strip().replace(" ", "") if not prefix: raise Exception("alias prefix cannot be empty") # find the right suffix - avoid infinite loop by running this at max 1000 times for _ in range(1000): suffix = user.get_random_alias_suffix() email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}" if available_sl_email(email): break return Alias.create( user_id=user.id, email=email, note=note, mailbox_id=mailbox_id or user.default_mailbox_id, ) def delete(cls, obj_id): raise Exception("should use delete_alias(alias,user) instead") def create_new_random( cls, user, scheme: int = AliasGeneratorEnum.word.value, in_hex: bool = False, note: str = None, ): """create a new random alias""" custom_domain = None random_email = None if user.default_alias_custom_domain_id: custom_domain = CustomDomain.get(user.default_alias_custom_domain_id) random_email = generate_random_alias_email( scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain ) elif user.default_alias_public_domain_id: sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id) if sl_domain.premium_only and not user.is_premium(): LOG.w("%s not premium, cannot use %s", user, sl_domain) else: random_email = generate_random_alias_email( scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain ) if not random_email: random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex) alias = Alias.create( user_id=user.id, email=random_email, mailbox_id=user.default_mailbox_id, note=note, ) if custom_domain: alias.custom_domain_id = custom_domain.id return alias def mailbox_email(self): if self.mailbox_id: return self.mailbox.email else: return self.user.email def __repr__(self): return f"<Alias {self.id} {self.email}>" class Contact(Base, ModelMixin): """ Store configuration of sender (website-email) and alias. """ MAX_NAME_LENGTH = 512 __tablename__ = "contact" __table_args__ = ( sa.UniqueConstraint("alias_id", "website_email", name="uq_contact"), ) user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True ) alias_id = sa.Column( sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True ) name = sa.Column( sa.String(512), nullable=True, default=None, server_default=text("NULL") ) website_email = sa.Column(sa.String(512), nullable=False) # the email from header, e.g. AB CD <ab@cd.com> # nullable as this field is added after website_email website_from = sa.Column(sa.String(1024), nullable=True) # when user clicks on "reply", they will reply to this address. # This address allows to hide user personal email # this reply email is created every time a website sends an email to user # it used to have the prefix "reply+" or "ra+" reply_email = sa.Column(sa.String(512), nullable=False, index=True) # whether a contact is created via CC is_cc = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0") pgp_public_key = sa.Column(sa.Text, nullable=True) pgp_finger_print = sa.Column(sa.String(512), nullable=True, index=True) alias = orm.relationship(Alias, backref="contacts") user = orm.relationship(User) # the latest reply sent to this contact latest_reply: Optional[Arrow] = None # to investigate why the website_email is sometimes not correctly parsed # the envelope mail_from mail_from = sa.Column(sa.Text, nullable=True, default=None) # a contact can have an empty email address, in this case it can't receive emails invalid_email = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # emails sent from this contact will be blocked block_forward = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # whether contact is created automatically during the forward phase automatic_created = sa.Column(sa.Boolean, nullable=True, default=False) def email(self): return self.website_email def create(cls, **kw): commit = kw.pop("commit", False) flush = kw.pop("flush", False) new_contact = cls(**kw) website_email = kw["website_email"] # make sure email is lowercase and doesn't have any whitespace website_email = sanitize_email(website_email) # make sure contact.website_email isn't a reverse alias if website_email != config.NOREPLY: orig_contact = Contact.get_by(reply_email=website_email) if orig_contact: raise CannotCreateContactForReverseAlias(str(orig_contact)) Session.add(new_contact) if commit: Session.commit() if flush: Session.flush() return new_contact def website_send_to(self): """return the email address with name. to use when user wants to send an email from the alias Return "First Last | email at example.com" <reverse-alias@SL> """ # Prefer using contact name if possible user = self.user name = self.name email = self.website_email if ( not user or not SenderFormatEnum.has_value(user.sender_format) or user.sender_format == SenderFormatEnum.AT.value ): email = email.replace("@", " at ") elif user.sender_format == SenderFormatEnum.A.value: email = email.replace("@", "(a)") # if no name, try to parse it from website_from if not name and self.website_from: try: name = address.parse(self.website_from).display_name except Exception: # Skip if website_from is wrongly formatted LOG.e( "Cannot parse contact %s website_from %s", self, self.website_from ) name = "" # remove all double quote if name: name = name.replace('"', "") if name: name = name + " | " + email else: name = email # cannot use formataddr here as this field is for email client, not for MTA return f'"{name}" <{self.reply_email}>' def new_addr(self): """ Replace original email by reply_email. Possible formats: - First Last - first at example.com <reply_email> OR - First Last - first(a)example.com <reply_email> OR - First Last <reply_email> - first at example.com <reply_email> - reply_email And return new address with RFC 2047 format """ user = self.user sender_format = user.sender_format if user else SenderFormatEnum.AT.value if sender_format == SenderFormatEnum.NO_NAME.value: return self.reply_email if sender_format == SenderFormatEnum.NAME_ONLY.value: new_name = self.name elif sender_format == SenderFormatEnum.AT_ONLY.value: new_name = self.website_email.replace("@", " at ").strip() elif sender_format == SenderFormatEnum.AT.value: formatted_email = self.website_email.replace("@", " at ").strip() new_name = ( (self.name + " - " + formatted_email) if self.name and self.name != self.website_email.strip() else formatted_email ) else: # SenderFormatEnum.A.value formatted_email = self.website_email.replace("@", "(a)").strip() new_name = ( (self.name + " - " + formatted_email) if self.name and self.name != self.website_email.strip() else formatted_email ) from app.email_utils import sl_formataddr new_addr = sl_formataddr((new_name, self.reply_email)).strip() return new_addr.strip() def last_reply(self) -> "EmailLog": """return the most recent reply""" return ( EmailLog.filter_by(contact_id=self.id, is_reply=True) .order_by(desc(EmailLog.created_at)) .first() ) def __repr__(self): return f"<Contact {self.id} {self.website_email} {self.alias_id}>" class EmailLog(Base, ModelMixin): __tablename__ = "email_log" __table_args__ = (Index("ix_email_log_created_at", "created_at"),) user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True ) contact_id = sa.Column( sa.ForeignKey(Contact.id, ondelete="cascade"), nullable=False, index=True ) alias_id = sa.Column( sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=True, index=True ) # whether this is a reply is_reply = sa.Column(sa.Boolean, nullable=False, default=False) # for ex if alias is disabled, this forwarding is blocked blocked = sa.Column(sa.Boolean, nullable=False, default=False) # can happen when user mailbox refuses the forwarded email # usually because the forwarded email is too spammy bounced = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0") # happen when an email with auto (holiday) reply auto_replied = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) # SpamAssassin result is_spam = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0") spam_score = sa.Column(sa.Float, nullable=True) spam_status = sa.Column(sa.Text, nullable=True, default=None) # do not load this column spam_report = deferred(sa.Column(sa.JSON, nullable=True)) # Point to the email that has been refused refused_email_id = sa.Column( sa.ForeignKey("refused_email.id", ondelete="SET NULL"), nullable=True ) # in forward phase, this is the mailbox that will receive the email # in reply phase, this is the mailbox (or a mailbox's authorized address) that sends the email mailbox_id = sa.Column( sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=True ) # in case of bounce, record on what mailbox the email has been bounced # useful when an alias has several mailboxes bounced_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=True ) # the Message ID message_id = deferred(sa.Column(sa.String(1024), nullable=True)) # in the reply phase, the original message_id is replaced by the SL message_id sl_message_id = deferred(sa.Column(sa.String(512), nullable=True)) refused_email = orm.relationship("RefusedEmail") forward = orm.relationship(Contact) contact = orm.relationship(Contact, backref="email_logs") alias = orm.relationship(Alias) mailbox = orm.relationship("Mailbox", lazy="joined", foreign_keys=[mailbox_id]) user = orm.relationship(User) def bounced_mailbox(self) -> str: if self.bounced_mailbox_id: return Mailbox.get(self.bounced_mailbox_id).email # retro-compatibility return self.contact.alias.mailboxes[0].email def get_action(self) -> str: """return the action name: forward|reply|block|bounced""" if self.is_reply: return "reply" elif self.bounced: return "bounced" elif self.blocked: return "block" else: return "forward" def get_phase(self) -> str: if self.is_reply: return "reply" else: return "forward" def get_dashboard_url(self): return f"{config.URL}/dashboard/refused_email?highlight_id={self.id}" def create(cls, *args, **kwargs): commit = kwargs.pop("commit", False) email_log = super().create(*args, **kwargs) Session.flush() if "alias_id" in kwargs: sql = "UPDATE alias SET last_email_log_id = :el_id WHERE id = :alias_id" Session.execute( sql, {"el_id": email_log.id, "alias_id": kwargs["alias_id"]} ) if commit: Session.commit() return email_log def __repr__(self): return f"<EmailLog {self.id}>" def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") The provided code snippet includes necessary dependencies for implementing the `handle` function. Write a Python function `def handle(envelope: Envelope, msg: Message) -> str` to solve the following problem: Return SMTP status Here is the function: def handle(envelope: Envelope, msg: Message) -> str: """Return SMTP status""" # sanitize mail_from, rcpt_tos mail_from = sanitize_email(envelope.mail_from) rcpt_tos = [sanitize_email(rcpt_to) for rcpt_to in envelope.rcpt_tos] envelope.mail_from = mail_from envelope.rcpt_tos = rcpt_tos # some emails don't have this header, set the default value (7bit) in this case if headers.CONTENT_TRANSFER_ENCODING not in msg: LOG.i("Set CONTENT_TRANSFER_ENCODING") msg[headers.CONTENT_TRANSFER_ENCODING] = "7bit" postfix_queue_id = get_queue_id(msg) if postfix_queue_id: set_message_id(postfix_queue_id) else: LOG.d( "Cannot parse Postfix queue ID from %s %s", msg.get_all(headers.RECEIVED), msg[headers.RECEIVED], ) if should_ignore(mail_from, rcpt_tos): LOG.w("Ignore email mail_from=%s rcpt_to=%s", mail_from, rcpt_tos) return status.E204 # sanitize email headers sanitize_header(msg, headers.FROM) sanitize_header(msg, headers.TO) sanitize_header(msg, headers.CC) sanitize_header(msg, headers.REPLY_TO) sanitize_header(msg, headers.MESSAGE_ID) LOG.d( "==>> Handle mail_from:%s, rcpt_tos:%s, header_from:%s, header_to:%s, " "cc:%s, reply-to:%s, message_id:%s, client_ip:%s, headers:%s, mail_options:%s, rcpt_options:%s", mail_from, rcpt_tos, msg[headers.FROM], msg[headers.TO], msg[headers.CC], msg[headers.REPLY_TO], msg[headers.MESSAGE_ID], msg[headers.SL_CLIENT_IP], msg._headers, envelope.mail_options, envelope.rcpt_options, ) # region mail_from or from_header is a reverse alias which should never happen email_sent_from_reverse_alias = False contact = Contact.get_by(reply_email=mail_from) if contact: email_sent_from_reverse_alias = True from_header = get_header_unicode(msg[headers.FROM]) if from_header: try: _, from_header_address = parse_full_address(from_header) except ValueError: LOG.w("cannot parse the From header %s", from_header) else: contact = Contact.get_by(reply_email=from_header_address) if contact: email_sent_from_reverse_alias = True if email_sent_from_reverse_alias: LOG.w(f"email sent from reverse alias {contact} {contact.alias} {contact.user}") user = contact.user send_email_at_most_times( user, ALERT_FROM_ADDRESS_IS_REVERSE_ALIAS, user.email, "SimpleLogin shouldn't be used with another email forwarding system", render( "transactional/email-sent-from-reverse-alias.txt.jinja2", ), ) # endregion # unsubscribe request if UNSUBSCRIBER and (rcpt_tos == [UNSUBSCRIBER] or rcpt_tos == [OLD_UNSUBSCRIBER]): LOG.d("Handle unsubscribe request from %s", mail_from) return UnsubscribeHandler().handle_unsubscribe_from_message(envelope, msg) # region mail sent to VERP verp_info = get_verp_info_from_email(rcpt_tos[0]) # sent to transactional VERP. Either bounce emails or out-of-office if ( len(rcpt_tos) == 1 and rcpt_tos[0].startswith(TRANSACTIONAL_BOUNCE_PREFIX) and rcpt_tos[0].endswith(TRANSACTIONAL_BOUNCE_SUFFIX) ) or (verp_info and verp_info[0] == VerpType.transactional): if is_bounce(envelope, msg): handle_transactional_bounce( envelope, msg, rcpt_tos[0], verp_info and verp_info[1] ) return status.E205 elif is_automatic_out_of_office(msg): LOG.d( "Ignore out-of-office for transactional emails. Headers: %s", msg.items ) return status.E206 else: raise VERPTransactional # sent to forward VERP, can be either bounce or out-of-office if ( len(rcpt_tos) == 1 and rcpt_tos[0].startswith(BOUNCE_PREFIX) and rcpt_tos[0].endswith(BOUNCE_SUFFIX) ) or (verp_info and verp_info[0] == VerpType.bounce_forward): email_log_id = (verp_info and verp_info[1]) or parse_id_from_bounce(rcpt_tos[0]) email_log = EmailLog.get(email_log_id) if not email_log: LOG.w("No such email log") return status.E512 if is_bounce(envelope, msg): return handle_bounce(envelope, email_log, msg) elif is_automatic_out_of_office(msg): handle_out_of_office_forward_phase(email_log, envelope, msg, rcpt_tos) else: raise VERPForward # sent to reply VERP, can be either bounce or out-of-office if ( len(rcpt_tos) == 1 and rcpt_tos[0].startswith(f"{BOUNCE_PREFIX_FOR_REPLY_PHASE}+") or (verp_info and verp_info[0] == VerpType.bounce_reply) ): email_log_id = (verp_info and verp_info[1]) or parse_id_from_bounce(rcpt_tos[0]) email_log = EmailLog.get(email_log_id) if not email_log: LOG.w("No such email log") return status.E512 # bounce by contact if is_bounce(envelope, msg): return handle_bounce(envelope, email_log, msg) elif is_automatic_out_of_office(msg): handle_out_of_office_reply_phase(email_log, envelope, msg, rcpt_tos) else: raise VERPReply( f"cannot handle email sent to reply VERP, " f"{email_log.alias} -> {email_log.contact} ({email_log}, {email_log.user}" ) # iCloud returns the bounce with mail_from=bounce+{email_log_id}+@simplelogin.co, rcpt_to=alias verp_info = get_verp_info_from_email(mail_from[0]) if ( len(rcpt_tos) == 1 and mail_from.startswith(BOUNCE_PREFIX) and mail_from.endswith(BOUNCE_SUFFIX) ) or (verp_info and verp_info[0] == VerpType.bounce_forward): email_log_id = (verp_info and verp_info[1]) or parse_id_from_bounce(mail_from) email_log = EmailLog.get(email_log_id) alias = Alias.get_by(email=rcpt_tos[0]) LOG.w( "iCloud bounces %s %s, saved to%s", email_log, alias, save_email_for_debugging(msg, file_name_prefix="icloud_bounce_"), ) return handle_bounce(envelope, email_log, msg) # endregion # region hotmail, yahoo complaints if ( len(rcpt_tos) == 1 and mail_from == "staff@hotmail.com" and rcpt_tos[0] == POSTMASTER ): LOG.w("Handle hotmail complaint") # if the complaint cannot be handled, forward it normally if handle_hotmail_complaint(msg): return status.E208 if ( len(rcpt_tos) == 1 and mail_from == "feedback@arf.mail.yahoo.com" and rcpt_tos[0] == POSTMASTER ): LOG.w("Handle yahoo complaint") # if the complaint cannot be handled, forward it normally if handle_yahoo_complaint(msg): return status.E210 # endregion if rate_limited(mail_from, rcpt_tos): LOG.w("Rate Limiting applied for mail_from:%s rcpt_tos:%s", mail_from, rcpt_tos) # add more logging info. TODO: remove if len(rcpt_tos) == 1: alias = Alias.get_by(email=rcpt_tos[0]) if alias: LOG.w( "total number email log on %s, %s is %s, %s", alias, alias.user, EmailLog.filter(EmailLog.alias_id == alias.id).count(), EmailLog.filter(EmailLog.user_id == alias.user_id).count(), ) if should_ignore_bounce(envelope.mail_from): return status.E207 else: return status.E522 # Handle "out-of-office" auto notice, i.e. an automatic response is sent for every forwarded email if len(rcpt_tos) == 1 and is_reverse_alias(rcpt_tos[0]) and mail_from == "<>": contact = Contact.get_by(reply_email=rcpt_tos[0]) LOG.w( "out-of-office email to reverse alias %s. Saved to %s", contact, save_email_for_debugging(msg), # todo: remove ) return status.E206 # result of all deliveries # each element is a couple of whether the delivery is successful and the smtp status res: [(bool, str)] = [] nb_rcpt_tos = len(rcpt_tos) for rcpt_index, rcpt_to in enumerate(rcpt_tos): if rcpt_to in config.NOREPLIES: LOG.i("email sent to {} address from {}".format(NOREPLY, mail_from)) send_no_reply_response(mail_from, msg) return status.E200 # create a copy of msg for each recipient except the last one # as copy() is a slow function if rcpt_index < nb_rcpt_tos - 1: LOG.d("copy message for rcpt %s", rcpt_to) copy_msg = copy(msg) else: copy_msg = msg # Reply case: the recipient is a reverse alias. Used to start with "reply+" or "ra+" if is_reverse_alias(rcpt_to): LOG.d( "Reply phase %s(%s) -> %s", mail_from, copy_msg[headers.FROM], rcpt_to ) is_delivered, smtp_status = handle_reply(envelope, copy_msg, rcpt_to) res.append((is_delivered, smtp_status)) else: # Forward case LOG.d( "Forward phase %s(%s) -> %s", mail_from, copy_msg[headers.FROM], rcpt_to, ) for is_delivered, smtp_status in handle_forward( envelope, copy_msg, rcpt_to ): res.append((is_delivered, smtp_status)) # to know whether both successful and unsuccessful deliveries can happen at the same time nb_success = len([is_success for (is_success, smtp_status) in res if is_success]) # ignore E518 which is a normal condition nb_non_success = len( [ is_success for (is_success, smtp_status) in res if not is_success and smtp_status != status.E518 ] ) if nb_success > 0 and nb_non_success > 0: LOG.e(f"some deliveries fail and some success, {mail_from}, {rcpt_tos}, {res}") for is_success, smtp_status in res: # Consider all deliveries successful if 1 delivery is successful if is_success: return smtp_status # Failed delivery for all, return the first failure return res[0][1]
Return SMTP status
180,061
import flask_migrate from IPython import embed from sqlalchemy_utils import create_database, database_exists, drop_database from app import models from app.config import DB_URI from app.db import Session from app.log import LOG from app.models import User, RecoveryCode if False: # noinspection PyUnreachableCode def create_db(): if not database_exists(DB_URI): LOG.d("db not exist, create database") create_database(DB_URI) # Create all tables # Use flask-migrate instead of db.create_all() flask_migrate.upgrade() # noinspection PyUnreachableCode DB_URI = os.environ["DB_URI"] def reset_db(): if database_exists(DB_URI): drop_database(DB_URI) create_db()
null
180,062
import flask_migrate from IPython import embed from sqlalchemy_utils import create_database, database_exists, drop_database from app import models from app.config import DB_URI from app.db import Session from app.log import LOG from app.models import User, RecoveryCode Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session class User(Base, ModelMixin, UserMixin, PasswordOracle): def directory_quota(self): def subdomain_quota(self): def created_by_partner(self): def subdomain_is_available(): def get_id(self): def create(cls, email, name="", password=None, from_partner=False, **kwargs): def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: def is_paid(self) -> bool: def is_active(self) -> bool: def in_trial(self): def should_show_upgrade_button(self): def is_premium(self, include_partner_subscription: bool = True) -> bool: def upgrade_channel(self) -> str: def max_alias_for_free_account(self) -> int: def can_create_new_alias(self) -> bool: def can_send_or_receive(self) -> bool: def profile_picture_url(self): def suggested_emails(self, website_name) -> (str, [str]): def suggested_names(self) -> (str, [str]): def get_name_initial(self) -> str: def get_paddle_subscription(self) -> Optional["Subscription"]: def verified_custom_domains(self) -> List["CustomDomain"]: def mailboxes(self) -> List["Mailbox"]: def nb_directory(self): def has_custom_domain(self): def custom_domains(self): def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: def default_random_alias_domain(self) -> str: def fido_enabled(self) -> bool: def two_factor_authentication_enabled(self) -> bool: def get_communication_email(self) -> (Optional[str], str, bool): def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: def should_show_app_page(self) -> bool: def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): def can_create_contacts(self) -> bool: def __repr__(self): def change_password(user_id, new_password): user = User.get(user_id) user.set_password(new_password) Session.commit()
null
180,063
import flask_migrate from IPython import embed from sqlalchemy_utils import create_database, database_exists, drop_database from app import models from app.config import DB_URI from app.db import Session from app.log import LOG from app.models import User, RecoveryCode class RecoveryCode(Base, ModelMixin): """allow user to login in case you lose any of your authenticators""" __tablename__ = "recovery_code" __table_args__ = (sa.UniqueConstraint("user_id", "code", name="uq_recovery_code"),) user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) code = sa.Column(sa.String(64), nullable=False) used = sa.Column(sa.Boolean, nullable=False, default=False) used_at = sa.Column(ArrowType, nullable=True, default=None) user = orm.relationship(User) def _hash_code(cls, code: str) -> str: code_hmac = hmac.new( config.RECOVERY_CODE_HMAC_SECRET.encode("utf-8"), code.encode("utf-8"), "sha3_224", ) return base64.urlsafe_b64encode(code_hmac.digest()).decode("utf-8").rstrip("=") def generate(cls, user): """generate recovery codes for user""" # delete all existing codes cls.filter_by(user_id=user.id).delete() Session.flush() nb_code = 0 raw_codes = [] while nb_code < _NB_RECOVERY_CODE: raw_code = random_string(_RECOVERY_CODE_LENGTH) encoded_code = cls._hash_code(raw_code) if not cls.get_by(user_id=user.id, code=encoded_code): cls.create(user_id=user.id, code=encoded_code) raw_codes.append(raw_code) nb_code += 1 LOG.d("Create recovery codes for %s", user) Session.commit() return raw_codes def find_by_user_code(cls, user: User, code: str): hashed_code = cls._hash_code(code) # TODO: Only return hashed codes once there aren't unhashed codes in the db. found_code = cls.get_by(user_id=user.id, code=hashed_code) if found_code: return found_code return cls.get_by(user_id=user.id, code=code) def empty(cls, user): """Delete all recovery codes for user""" cls.filter_by(user_id=user.id).delete() Session.commit() Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") def migrate_recovery_codes(): last_id = -1 while True: recovery_codes = ( RecoveryCode.filter(RecoveryCode.id > last_id) .order_by(RecoveryCode.id) .limit(100) .all() ) batch_codes = len(recovery_codes) old_codes = 0 new_codes = 0 last_code = None last_code_id = None for recovery_code in recovery_codes: if len(recovery_code.code) == models._RECOVERY_CODE_LENGTH: last_code = recovery_code.code last_code_id = recovery_code.id recovery_code.code = RecoveryCode._hash_code(recovery_code.code) old_codes += 1 Session.flush() else: new_codes += 1 last_id = recovery_code.id Session.commit() LOG.i( f"Updated {old_codes}/{batch_codes} for this batch ({new_codes} already updated)" ) if last_code is not None: recovery_code = RecoveryCode.get_by(id=last_code_id) assert RecoveryCode._hash_code(last_code) == recovery_code.code LOG.i("Check is Good") if len(recovery_codes) == 0: break
null
180,064
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # As alembic cannot detect changes in column length, do it manually op.execute('ALTER TABLE email_log ALTER COLUMN message_id TYPE varchar(1024);') op.execute('ALTER TABLE message_id_matching ALTER COLUMN original_message_id TYPE varchar(1024);')
null
180,065
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # As alembic cannot detect changes in column length, do it manually op.execute('ALTER TABLE email_log ALTER COLUMN message_id TYPE varchar(512);') op.execute('ALTER TABLE message_id_matching ALTER COLUMN original_message_id TYPE varchar(512);')
null
180,066
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.execute('UPDATE users SET include_sender_in_reverse_alias = false WHERE include_sender_in_reverse_alias IS NULL') op.alter_column('users', 'include_sender_in_reverse_alias', server_default='0', existing_type=sa.BOOLEAN(), nullable=False) # ### end Alembic commands ###
null
180,067
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('users', 'include_sender_in_reverse_alias', existing_type=sa.BOOLEAN(), nullable=True) # ### end Alembic commands ###
null
180,068
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('authorization_code', sa.Column('nonce', sa.Text(), server_default=sa.text('NULL'), nullable=True)) # ### end Alembic commands ###
null
180,069
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('authorization_code', 'nonce') # ### end Alembic commands ###
null
180,070
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('hibp_notified_alias', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False), sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), sa.Column('alias_id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('notified_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False), sa.ForeignKeyConstraint(['alias_id'], ['alias.id'], ondelete='cascade'), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ###
null
180,071
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('hibp_notified_alias') # ### end Alembic commands ###
null
180,072
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('replace_reverse_alias', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,073
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'replace_reverse_alias') # ### end Alembic commands ###
null
180,074
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('mailbox', sa.Column('disable_pgp', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,075
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('mailbox', 'disable_pgp') # ### end Alembic commands ###
null
180,076
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('payout', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False), sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('amount', sa.Float(), nullable=False), sa.Column('payment_method', sa.String(length=256), nullable=False), sa.Column('number_upgraded_account', sa.Integer(), nullable=False), sa.Column('comment', sa.Text(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ###
null
180,077
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('payout') # ### end Alembic commands ###
null
180,078
from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('is_developer', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,079
from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'is_developer') # ### end Alembic commands ###
null
180,080
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('trial_end', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True)) # ### end Alembic commands ###
null
180,081
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'trial_end') # ### end Alembic commands ###
null
180,082
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('mailbox', sa.Column('pgp_finger_print', sa.String(length=512), nullable=True)) op.add_column('mailbox', sa.Column('pgp_public_key', sa.Text(), nullable=True)) op.add_column('users', sa.Column('can_use_pgp', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,083
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'can_use_pgp') op.drop_column('mailbox', 'pgp_public_key') op.drop_column('mailbox', 'pgp_finger_print') # ### end Alembic commands ###
null
180,084
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('recovery_code', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False), sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('code', sa.String(length=16), nullable=False), sa.Column('used', sa.Boolean(), nullable=False), sa.Column('used_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'code', name='uq_recovery_code') ) # ### end Alembic commands ###
null
180,085
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('recovery_code') # ### end Alembic commands ###
null
180,086
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('flags', sa.BigInteger(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,087
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'flags') # ### end Alembic commands ###
null
180,088
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('uq_mailbox_user', 'mailbox', ['user_id', 'email']) op.drop_constraint('mailbox_email_key', 'mailbox', type_='unique') # ### end Alembic commands ###
null
180,089
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('mailbox_email_key', 'mailbox', ['email']) op.drop_constraint('uq_mailbox_user', 'mailbox', type_='unique') # ### end Alembic commands ###
null
180,090
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'can_use_subdomain') # ### end Alembic commands ###
null
180,091
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('can_use_subdomain', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False)) # ### end Alembic commands ###
null
180,092
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('transactional_email_email_key', 'transactional_email', type_='unique') # ### end Alembic commands ###
null
180,093
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('transactional_email_email_key', 'transactional_email', ['email']) # ### end Alembic commands ###
null
180,094
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('forward_email', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False), sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), sa.Column('gen_email_id', sa.Integer(), nullable=False), sa.Column('website_email', sa.String(length=128), nullable=False), sa.Column('reply_email', sa.String(length=128), nullable=False), sa.ForeignKeyConstraint(['gen_email_id'], ['gen_email.id'], ondelete='cascade'), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('gen_email_id', 'website_email', name='uq_forward_email') ) # ### end Alembic commands ###
null
180,095
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('forward_email') # ### end Alembic commands ###
null
180,096
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('bounce', sa.Column('info', sa.Text(), nullable=True)) # ### end Alembic commands ###
null
180,097
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('bounce', 'info') # ### end Alembic commands ###
null
180,098
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('invalid_mailbox_domain', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False), sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True), sa.Column('domain', sa.String(length=256), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('domain') ) # ### end Alembic commands ###
null
180,099
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('invalid_mailbox_domain') # ### end Alembic commands ###
null
180,100
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('max_spam_score', sa.Integer(), nullable=True)) # ### end Alembic commands ###
null
180,101
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'max_spam_score') # ### end Alembic commands ###
null
180,102
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('custom_domain', sa.Column('random_prefix_generation', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,103
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('custom_domain', 'random_prefix_generation') # ### end Alembic commands ###
null
180,104
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('mailbox', sa.Column('disabled', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,105
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('mailbox', 'disabled') # ### end Alembic commands ###
null
180,106
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('users', sa.Column('alternative_id', sa.String(length=128), nullable=True)) op.create_unique_constraint(None, 'users', ['alternative_id']) # set alternative_id to id op.execute('UPDATE users SET alternative_id = id') # ### end Alembic commands ###
null
180,107
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'users', type_='unique') op.drop_column('users', 'alternative_id') # ### end Alembic commands ###
null
180,108
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('directory', sa.Column('disabled', sa.Boolean(), server_default='0', nullable=False)) # ### end Alembic commands ###
null
180,109
import sqlalchemy_utils from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('directory', 'disabled') # ### end Alembic commands ###
null