def detect_filetype(header):
    """Returns Kepler and TESS file types given their primary header.

    This function will detect the file type by looking at both the TELESCOP and
    CREATOR keywords in the first extension of the FITS header. If the file is
    recognized as a Kepler or TESS data product, one of the following strings
    will be returned:

        * `'KeplerTargetPixelFile'`
        * `'TessTargetPixelFile'`
        * `'KeplerLightCurveFile'`
        * `'TessLightCurveFile'`

    If the file is not recognized as a Kepler or TESS data product, then
    `None` will be returned.

    Parameters
    ----------
    header : astropy.io.fits.Header object
        The primary header of a FITS file.

    Returns
    -------
    filetype : str or None
        A string describing the detected filetype. If the filetype is not
        recognized, `None` will be returned.
    """
    try:
        if 'TELESCOP' in header.keys():
            telescop = header['telescop'].lower()
        else:
            telescop = header['mission'].lower()
        creator = header['creator'].lower()
        origin = header['origin'].lower()
        if telescop == 'kepler':
            if 'targetpixel' in creator:
                return 'KeplerTargetPixelFile'
            elif 'fluxexporter' in creator or 'lightcurve' in creator or 'lightcurve' in creator:
                return 'KeplerLightCurveFile'
        elif telescop == 'tess':
            if 'targetpixel' in creator:
                return 'TessTargetPixelFile'
            elif 'lightcurve' in creator:
                return 'TessLightCurveFile'
            elif 'stsci' in origin:
                return 'TessTargetPixelFile'
    except (KeyError, AttributeError):
        return None
