sftp_id_retrieve.py 9.63 KB
Newer Older
Gregory Martin committed
1 2 3 4 5 6 7 8 9 10
"""
Check SFTP dropboxes for YT Video ID XML information

"""
import datetime
import fnmatch
import os
import shutil
import sys
import xml.etree.ElementTree as ET
Gregory Martin committed
11 12 13 14 15 16 17 18 19 20 21 22
from datetime import timedelta
from os.path import expanduser

import django
import pysftp
from django.utils.timezone import utc

from control.veda_utils import ErrorObject, Metadata, VideoProto
from control.veda_val import VALAPICall
from frontend.abvid_reporting import report_status
from VEDA_OS01.models import URL, Encode, Video
from youtube_callback.daemon import get_course
Gregory Martin committed
23 24 25 26

project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_path not in sys.path:
    sys.path.append(project_path)
27 28

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'VEDA.settings.local')
Gregory Martin committed
29 30 31 32 33 34 35 36
django.setup()


"""
Defaults:
"""
homedir = expanduser("~")
workdir = os.path.join(homedir, 'download_data_holding')
Gregory Martin committed
37
YOUTUBE_LOOKBACK_DAYS = 4
Gregory Martin committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76


def callfunction(course):
    """

    :param course:
    :return:
    """
    if os.path.exists(workdir):
        shutil.rmtree(workdir)
    os.mkdir(workdir)

    xml_downloader(course)

    for file in os.listdir(workdir):
        print file
        upload_data = domxml_parser(file)

        if upload_data is not None:
            print upload_data
            urlpatch(upload_data)


def xml_downloader(course):
    """

    :param course:
    :return:
    """

    private_key = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        'static_files',
        'youtubekey'
    )

    cnopts = pysftp.CnOpts()
    cnopts.hostkeys = None

Gregory Martin committed
77 78 79 80 81 82 83 84 85 86
    with pysftp.Connection(
        'partnerupload.google.com',
        username=course.yt_logon,
        private_key=private_key,
        port=19321,
        cnopts=cnopts
    ) as s1:
        s1.timeout = 60.0
        for d in s1.listdir_attr():
            crawl_sftp(d=d, s1=s1)
Gregory Martin committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110


def crawl_sftp(d, s1):
    """
    crawl the sftp dir and dl the XML files for parsing

    :param d: directory
    :param s1: sftp connection
    :return: None
    """
    dirtime = datetime.datetime.fromtimestamp(d.st_mtime)
    if dirtime < datetime.datetime.now() - timedelta(days=YOUTUBE_LOOKBACK_DAYS):
        return None
    if d.filename == "files_to_be_removed.txt":
        return None
    if d.filename == 'FAILED':
        return None
    try:
        s1.cwd(d.filename)
    except:
        return None

    for f in s1.listdir_attr():
        filetime = datetime.datetime.fromtimestamp(f.st_mtime)
Gregory Martin committed
111 112 113 114 115
        if not filetime > datetime.datetime.now() - timedelta(days=YOUTUBE_LOOKBACK_DAYS):
            continue
        if fnmatch.fnmatch(f.filename, '*.xml') or fnmatch.fnmatch(f.filename, '*.csv'):
            # Determine If there are extant downloaded status files for this same ID,
            # If yes, increment filename
Gregory Martin committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
            x = 0
            while True:
                """
                Just in case something runs out
                """
                if x > 20:
                    break
                file_to_find = f.filename.split('.')[0] + \
                    str(x) + \
                    '.' + \
                    f.filename.split('.')[1]
                if os.path.exists(os.path.join(workdir, file_to_find)):
                    x += 1
                else:
                    break
            print "%s : %s" % (f.filename, file_to_find)
            s1.get(
                f.filename,
                os.path.join(workdir, file_to_find)
            )
    s1.cwd('..')


def domxml_parser(file):
    """

    :param file:
    :return:
    """

    if 'status-' not in file:
147
        return
Gregory Martin committed
148 149 150 151 152 153 154 155 156 157 158 159

    upload_data = {
        'datetime': None,
        'status': None,
        'duplicate_url': None,
        'edx_id': file.strip('status-').split('_')[0],
        'file_suffix': None,
        'youtube_id': None
    }
    try:
        tree = ET.parse(os.path.join(workdir, file))
    except ET.ParseError:
160 161 162
        return
    except IOError:
        return
Gregory Martin committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    root = tree.getroot()
    for child in root:

        if child.tag == 'timestamp':
            upload_data['datetime'] = datetime.datetime.strptime(
                child.text,
                '%Y-%m-%dT%H:%M:%S'
            ).replace(tzinfo=utc)

        elif child.tag == 'action':
            if child.get('name') == 'Process file':
                for c in child:
                    if c.tag == 'status_detail':
                        if c.text == 'The file size cannot be zero.':
                            return None

                    if c.tag == 'action':
                        if c.get('name') == 'Submit video':
                            for d in c:

                                if d.tag == 'status':
                                    upload_data['status'] = d.text

                                elif d.tag == 'status_detail':
                                    if d.text != 'Live!':
                                        if 'duplicate upload' in d.text:
                                            upload_data['duplicate_url'] = d.text[::-1].split(' ')[0][::-1].split('.')[0]  # nopep8 TODO: refactor to fix
                                            upload_data['status'] = 'Duplicate'

                                elif d.tag == 'in_file':
                                    try:
                                        upload_data['file_suffix'] = d.text.split('\'')[1].split('_')[1].split('.')[0]  # nopep8
                                    except IndexError:
                                        upload_data['file_suffix'] = '100'
                                elif d.tag == 'id':
                                    upload_data['youtube_id'] = d.text
    return upload_data


def urlpatch(upload_data):
    """

    # :param upload_data: dict
    # :return:
    """
    if upload_data['status'] == 'Failure':
        return None
    try:
        test_id = Video.objects.filter(edx_id=upload_data['edx_id']).latest()
    except:
        upload_data['status'] = 'Failure'

    if upload_data['status'] == 'Success':
        url_query = URL.objects.filter(
            encode_url=upload_data['youtube_id']
        )

        if len(url_query) == 0:
            u1 = URL(
                videoID=Video.objects.filter(
                    edx_id=test_id.edx_id
                ).latest()
            )
            u1.encode_profile = Encode.objects.get(
                encode_suffix=upload_data['file_suffix']
            )
            u1.encode_url = upload_data['youtube_id']
            u1.url_date = upload_data['datetime']
            u1.encode_duration = test_id.video_orig_duration
            u1.encode_bitdepth = 0
            u1.encode_size = 0
            u1.save()

            """
            Report to Email

            """
            if 'EDXABVID' in upload_data['edx_id']:
                v1 = Video.objects.filter(edx_id=upload_data['edx_id']).latest()
                if v1.abvid_serial is not None:

                    report_status(
                        status="Complete",
                        abvid_serial=v1.abvid_serial,
                        youtube_id=upload_data['youtube_id']
                    )

        video_check = Video.objects.filter(edx_id=test_id.edx_id).latest()

        if video_check.video_trans_status == 'Youtube Duplicate':
            Video.objects.filter(
                edx_id=video_check.edx_id
            ).update(
                video_trans_status='Progress'
            )

        """
        Update Status & VAL
        """
        video_proto = VideoProto(
            veda_id=test_id.edx_id,
            val_id=test_id.studio_id,
            client_title=test_id.client_title,
            duration=test_id.video_orig_duration,
            bitrate='0',
            s3_filename=test_id.studio_id
        )
        print test_id.video_orig_duration
        VF = Metadata(
            video_object=test_id
        )

        encode_list = VF._FAULT(
            video_object=test_id
        )

        """
        Review can stop here
        """
        if upload_data['file_suffix'] == 'RVW':
            return None

        if len(encode_list) == 0:
Gregory Martin committed
286
            Video.objects.filter(edx_id=upload_data['edx_id']).update(video_trans_status='Complete')
Gregory Martin committed
287 288 289 290
            val_status = 'file_complete'
        else:
            val_status = 'transcode_active'

Gregory Martin committed
291
        ApiConn = VALAPICall(
Gregory Martin committed
292 293 294 295 296
            video_proto=video_proto,
            val_status=val_status,
            endpoint_url=upload_data['youtube_id'],
            encode_profile='youtube'
        )
Gregory Martin committed
297
        ApiConn.call()
Gregory Martin committed
298 299 300 301 302 303

    elif upload_data['status'] == 'Duplicate' and \
            upload_data['file_suffix'] == '100':

        url_query = URL.objects.filter(
            videoID=Video.objects.filter(
Gregory Martin committed
304
                edx_id=upload_data['edx_id']
Gregory Martin committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318
            ).latest(),
            encode_profile=Encode.objects.get(
                encode_suffix=upload_data['file_suffix']
            )
        )
        if len(url_query) == 0:

            if 'EDXABVID' in upload_data['edx_id']:
                report_status(
                    status="Youtube Duplicate",
                    abvid_serial=test_id.abvid_serial,
                    youtube_id=''
                )

Gregory Martin committed
319
            Video.objects.filter(edx_id=upload_data['edx_id']).update(video_trans_status='Youtube Duplicate')
Gregory Martin committed
320 321 322 323 324 325 326 327
            video_proto = VideoProto(
                veda_id=test_id.edx_id,
                val_id=test_id.studio_id,
                client_title=test_id.client_title,
                duration=test_id.video_orig_duration,
                bitrate='0',
                s3_filename=test_id.studio_id
            )
Gregory Martin committed
328
            ApiConn = VALAPICall(
Gregory Martin committed
329 330 331 332 333
                video_proto=video_proto,
                val_status="duplicate",
                endpoint_url="DUPLICATE",
                encode_profile='youtube'
            )
Gregory Martin committed
334
            ApiConn.call()