Ejemplo n.º 1
0
def send_print_progress(_print, op_data, existed_rotated_jpg_url):
    rotated_jpg_url = existed_rotated_jpg_url  # Cache it as it's expensive to generate

    pushed_platforms = set()

    for mobile_device in MobileDevice.objects.filter(user=_print.user):
        if cache.print_status_mobile_push_get(_print.id,
                                              mobile_device.platform):
            continue
        pushed_platforms.add(mobile_device.platform)

        data = dict(type='printProgress',
                    printId=str(_print.id),
                    printerId=str(_print.printer.id),
                    title='',
                    body=_print.filename,
                    picUrl='',
                    completion='0')

        state_text = op_data.get('state', {}).get('text', '')
        data['title'] += state_text if state_text.lower() != 'printing' else ''
        progress = op_data.get('progress')
        if progress:
            completion = progress.get('completion')
            data['completion'] = str(
                max(0, min(100, int(round(completion or 0)))))
            data['title'] += f' {data["completion"] if completion else "-"}%'
            seconds_left = progress.get("printTimeLeft") or 0
            if (isinstance(seconds_left, int)
                    or isinstance(seconds_left, float)):
                data['title'] += f' | ⏱{shortform_duration(seconds_left)}'
                if mobile_device.preferred_timezone:
                    data[
                        'title'] += f' | 🏁{shortform_localtime(seconds_left, mobile_device.preferred_timezone)}'

        printer = _print.printer
        if printer.not_watching_reason():
            data['title'] += ' | 💤'
        else:
            p = calc_normalized_p(printer.detective_sensitivity,
                                  printer.printerprediction)
            if p < 0.33:
                data['title'] += ' | 🟢'
            elif p < 0.66:
                data['title'] += ' | 🟠'
            else:
                data['title'] += ' | 🔴'

        if not rotated_jpg_url:
            rotated_jpg_url = get_rotated_jpg_url(_print)
        if rotated_jpg_url:
            data['picUrl'] = rotated_jpg_url

        send_to_device(data, mobile_device)

    for pushed_platform in pushed_platforms:
        cache.print_status_mobile_push_set(
            _print.id, pushed_platform,
            PRINT_PROGRESS_PUSH_INTERVAL[pushed_platform])
Ejemplo n.º 2
0
    def prediction_json(self, request, pk) -> Response:
        p: Print = get_object_or_404(
            self.get_queryset().select_related('printer'), pk=pk)

        # check as it's null=True
        if not p.prediction_json_url:
            return Response([])

        headers = {
            'If-Modified-Since': request.headers.get('if-modified-since'),
            'If-None-Match': request.headers.get('if-none-match'),
        }

        r = requests.get(
            url=p.prediction_json_url,
            timeout=PREDICTION_FETCH_TIMEOUT,
            headers={k: v
                     for k, v in headers.items() if v is not None})
        r.raise_for_status()

        resp_headers = {
            'Last-Modified': r.headers.get('Last-Modified'),
            'Etag': r.headers.get('Etag')
        }

        # might be cached already
        if r.status_code == 304:
            return Response(None,
                            status=304,
                            headers={
                                k: v
                                for k, v in resp_headers.items()
                                if v is not None
                            })

        data = r.json()

        detective_sensitivity: float = (
            p.printer.detective_sensitivity if p.printer is not None else
            Printer._meta.get_field('detective_sensitivity').get_default())

        for raw_pred in data:
            if 'fields' not in raw_pred:
                # once upon a time in production
                # should not happen, exact cause is TODO/FIXME
                raw_pred['fields'] = {'normalized_p': 0.0}
            else:
                pred = PrinterPrediction(**raw_pred['fields'])
                raw_pred['fields']['normalized_p'] = calc_normalized_p(
                    detective_sensitivity, pred)

        return Response(
            data,
            headers={k: v
                     for k, v in resp_headers.items() if v is not None})
def send_print_progress(_print, op_data):
    pushed_platforms = set()

    for mobile_device in MobileDevice.objects.filter(user=_print.user):
        if cache.print_status_mobile_push_get(_print.id,
                                              mobile_device.platform):
            continue
        pushed_platforms.add(mobile_device.platform)

        data = dict(type='printProgress',
                    printId=str(_print.id),
                    title='',
                    body=_print.filename,
                    picUrl='',
                    completion='0')

        data['title'] += op_data.get("state", {}).get("text", "")
        progress = op_data.get('progress')
        if progress:
            completion = progress.get('completion')
            data['completion'] = str(round(completion or 0))
            data['title'] += f' {data["completion"] if completion else "-"}%'
            data[
                'title'] += f' | {shortform_duration(progress.get("printTimeLeft") or 0)}'
            data[
                'title'] += f'/{shortform_duration((progress.get("printTimeLeft") or 0) + (progress.get("printTime") or 0))}'

        printer = _print.printer
        if printer.not_watching_reason():
            data['title'] += ' | 💤'
        else:
            p = calc_normalized_p(printer.detective_sensitivity,
                                  printer.printerprediction)
            if p < 0.33:
                data['title'] += ' | 🟢'
            elif p < 0.66:
                data['title'] += ' | 🟠'
            else:
                data['title'] += ' | 🔴'

        if printer.pic:
            data['picUrl'] = printer.pic.get('img_url', '')

        send_to_device(data, mobile_device.device_token)

    for pushed_platform in pushed_platforms:
        cache.print_status_mobile_push_set(
            _print.id, pushed_platform,
            PRINT_PROGRESS_PUSH_INTERVAL[pushed_platform])
Ejemplo n.º 4
0
def send_print_progress(printer):
    data = dict(
        type='printProgress',
        printId=str(printer.current_print.id),
        title='',
        body=printer.current_print.filename,
        picUrl='',
    )

    completion = printer.status.get('progress', {}).get('completion')
    data['completion'] = str(round(completion or 0))
    data['title'] += f'{data["completion"] if completion else "-"}%'

    progress = printer.status.get('progress')
    if progress:
        seconds_past = progress.get('printTime', 0)
        seconds_left = progress.get('printTimeLeft', 0)
        data[
            'title'] += f' | {shortform_duration(seconds_left)}/{shortform_duration(seconds_left + seconds_past)}'

    if printer.not_watching_reason():
        data['title'] += ' | 💤'
    else:
        p = calc_normalized_p(printer.detective_sensitivity,
                              printer.printerprediction)
        if p < 0.33:
            data['title'] += ' | ☀'
        elif p < 0.66:
            data['title'] += ' | �'
        else:
            data['title'] += ' | 🌧'

    if printer.pic:
        data['picUrl'] = printer.pic.get('img_url', '')

    for mobile_device in MobileDevice.objects.filter(user=printer.user):
        send_to_device(data, mobile_device.device_token)
Ejemplo n.º 5
0
 def get_normalized_p(self, obj: Printer) -> float:
     return calc_normalized_p(obj.detective_sensitivity,
                              obj.printerprediction)
Ejemplo n.º 6
0
 def get_normalized_p(self, obj: Printer) -> float:
     return calc_normalized_p(obj.detective_sensitivity,
                              obj.printerprediction) if hasattr(
                                  obj, 'printerprediction') else None