# coding=utf-8

import json
import requests
from django.core.management import BaseCommand
from api.models import FeedOperateV2


class Command(BaseCommand):

    @staticmethod
    def get_image_base_info(url, suffix='-imageinfo?ref'):
        full_path = url + suffix
        resp = requests.get(full_path, verify=False)  # 不进行ssl验证，避免 SSLError
        data = json.loads(resp.text)
        ret_data = {
            'width': 0,
            'height': 0
        }
        if resp.status_code == 200:
            ret_data['width'] = data['width']
            ret_data['height'] = data['height']

        return ret_data

    def handle(self, *args, **options):
        data = FeedOperateV2.objects.all()
        for item in data:
            image_url = item.image
            if image_url:
                result = self.get_image_base_info(image_url)
            item.height = result['height']
            item.width = result['width']
            try:
                item.save()
            except Exception as e:
                print(e)

        print("done")
