googleapis#drive_v3 TypeScript Examples

The following examples show how to use googleapis#drive_v3. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: driveHandler.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
/**
     * @desc gets every file in a google drive folder
     * @param folder - the folder to get the files from
     * @param pageToken - the page token to get the next page of files
     * @param trashed - if the files should be trashed or not
     */
    readFolder = async (folder: string, trashed = 'false', pageToken?: string): Promise<drive_v3.Schema$File[]> => {
        pageToken = pageToken || "";
        let res = await this.drive.files.list({
            q: `'${folder}' in parents and trashed = ${trashed}`,
            fields: 'nextPageToken, files(id, name, size, mimeType, trashed, parents)',
            spaces: 'drive',
            orderBy: 'name',
            pageSize: 1000,
            supportsAllDrives: true,
            includeItemsFromAllDrives: true,
            pageToken: pageToken
        });

        let files = res.data.files || [];
        let temp = !!res.data.nextPageToken ? await this.readFolder(folder, trashed, res.data.nextPageToken) : [];
        return files.concat(temp);
    }
Example #2
Source File: driveHandler.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
/**
     * @desc gets a specific file by name from a specific google drive folder
     * @param fileName - name of file to find
     * @param folder - the folder to get the file from
     */
    findFile = async (fileName: string, folder: string): Promise<drive_v3.Schema$File | false> => {
        let res = await this.drive.files.list({
            q: `'${folder}' in parents and trashed = false and name = "${fileName}"`,
            fields: 'files(id, name, size, mimeType)',
            spaces: 'drive',
            orderBy: 'name',
            supportsAllDrives: true,
            includeItemsFromAllDrives: true,
            pageSize: 10
        });

        let files = res.data.files || [];
        return files.length > 0 ? files[0] : false;
    }
Example #3
Source File: driveHandler.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
/**
     * @desc builds a video header based on specific data requested by the user
     * @param range - HTTP request range to be requested
     * @param video - the video to build the header for
     */
    buildRange = (range: string, video: drive_v3.Schema$File) => {
        let videoRes = {
            mimeType: '',
            fileSize: 0,
            start: 0,
            end: 0,
            chunkSize: 0
        };
        videoRes.mimeType = video.mimeType!;
        videoRes.fileSize = parseInt(video.size!, 10);
        const parts = range
            .replace(/bytes=/, "")
            .split("-")

        videoRes.start = parseInt(parts[0], 10)
        videoRes.end = parseInt(parts[1]) > 0 ? parseInt(parts[1], 10) : videoRes.fileSize - 1
        videoRes.chunkSize = (videoRes.end - videoRes.start) + 1;

        return videoRes;
    }
Example #4
Source File: driveHandler.ts    From frames with Mozilla Public License 2.0 6 votes vote down vote up
/**
     * @desc gets a google drive file's metadata
     * @param fileId - id for file to be requested
     */
    getFile = async (fileId: string): Promise<drive_v3.Schema$File | null> => {
        return new Promise(resolve => {
            this.drive.files.get({
                fileId: fileId,
                supportsAllDrives: true,
                fields: "id, name, size, parents, mimeType, contentHints/thumbnail, videoMediaMetadata, thumbnailLink, explicitlyTrashed"
            }).then(response => resolve(response.data))
                .catch(() => resolve(null))
        })
    }
Example #5
Source File: driveHandler.ts    From frames with Mozilla Public License 2.0 5 votes vote down vote up
private readonly drive: drive_v3.Drive;
Example #6
Source File: scanner.ts    From frames with Mozilla Public License 2.0 5 votes vote down vote up
/**
     * @desc searches TMDB for the best match for a given file
     * @param item - the file to be scanned
     * @param type - the type of media to be scanned
     */
    public async scanMediaHelper(item: drive_v3.Schema$File, type: MediaType) {
        const ext = path.extname(item.name!)
        let name = Scanner.prepareString(item.name!), year = 0;
        let backup: ScanPick[] = [], results: ScanPick[] = [];

        if (item.mimeType !== 'application/vnd.google-apps.folder' && type === MediaType.SHOW)
            return {backup, results};

        else if ((item.mimeType === 'application/vnd.google-apps.folder' && type === MediaType.MOVIE) || (type === MediaType.MOVIE && !(ext === '.mp4' || ext === '.m4v')))
            return {backup, results};

        if (type === MediaType.MOVIE) {
            let matches = name.match(/(?<name>^\d{4}.*?)\s+(?<year>\d{4})/);
            matches = matches ? matches : name.match(/(?<name>(^\w+.*?\d+)|^\w+.*?)\s+(?<year>\d{4})/);

            if (matches && matches.groups) {
                name = matches.groups.name;
                year = parseInt(matches.groups.year);

            } else {
                let data = item.name!.match(/(?<name>^.*?)\d+p/);
                let tmpName = data && data.groups && data.groups.name ? data.groups.name : item.name!;
                tmpName = rename(tmpName, dicDo);
                data = tmpName.match(/\d{4}/g);
                let temp = data && data.length ? data[data.length - 1] : new Date().getFullYear();
                let tmpYear = parseInt(`${temp}`);
                tmpName = tmpName.replace(`${temp}`, '');
                if (tmpYear !== new Date().getFullYear() && tmpName !== rename(item.name!, dicDo)) {
                    year = tmpYear;
                    name = tmpName;
                }
            }

            year = parseInt(`${year}`);
        }

        let response = await this.tmdb?.searchMedia(type, name) || [];
        console.log(`${type} ${name}`, response.length);

        results = response.map(item => {
            return {
                tmdbId: item.id,
                name: item.title || item.name || '',
                drift: Scanner.prepareString(item.title || item.name || '').Levenshtein(name),
                popularity: item.popularity,
                backdrop: item.backdrop_path ? `https://image.tmdb.org/t/p/original${item.backdrop_path}` : null,
                year: new Date(type === MediaType.MOVIE ? item.release_date : item.first_air_date).getFullYear()
            }
        });
        backup = this.sortArray(results, ['drift', 'popularity'], ['asc', 'desc']);

        if (type === MediaType.SHOW && backup.length > 0)
            backup = backup.length ? [backup[0]] : [];

        else if (type === MediaType.MOVIE) {
            backup = backup.filter(item => (year - 1 <= item.year && item.year <= year + 1));
            backup = backup.length > 1 ? backup.filter(item => item.year === year && item.drift < 3) : backup;
            backup = backup.length > 1 ? backup.filter(item => item.drift < 2) : backup;
            backup = backup.length > 1 ? backup.filter(item => item.drift < 1) : backup;

            if (backup.length !== 1 || (year === new Date().getFullYear() || year === 0)) {
                backup = results.filter(item => item.backdrop !== null);
                backup = this.sortArray(backup, ['drift', 'popularity'], ['asc', 'desc']);
                backup = backup.length ? [backup[0]] : [];
            }
        }

        console.log(`${type} ${name}`, backup.length);
        return {backup, results};
    }
Example #7
Source File: scanner.ts    From frames with Mozilla Public License 2.0 5 votes vote down vote up
/**
     * @desc scans a new media item and attempts to add it to the database
     * @param item - the show folder to scan
     * @param type - the type of media to be scanned
     * @param media - the media already in the database
     * @param keepOld - whether to keep the old media or not
     */
    public async scanMedia(item: drive_v3.Schema$File, type: MediaType, media: Media[], keepOld = true) {
        let obj: { name: string, tmdbId: number, year: number };
        let {backup, results} = await this.scanMediaHelper(item, type);

        if (results.length === 1 || backup.length === 1) {
            obj = backup.length ? backup[0] : results[0];

            const existing = media.find(e => e.tmdbId === obj.tmdbId && e.type === type);

            if (existing !== undefined) {
                if (keepOld) {
                    await this.drive?.deleteFile(item.id!);
                    return;
                }

                const video = await this.prisma.folder.findFirst({where: {showId: existing.id}});
                if (video) await this.checkAndDelete(video.location, item.id as string, this.moviesLocation === '' || this.showsLocation === '');
                return;
            }

            const imageData = await this.tmdb?.getImagesForAutoScan(obj.tmdbId, obj.name || '', type, obj.year) || {
                poster: '',
                backdrop: '',
                logo: ''
            };
            const res = await this.buildMediaObj(imageData, obj, type);
            if (res) {
                await this.addMedia(res.mediaData, res.castCrew, item.id as string);
                return;
            }
        }

        console.log(`${item.name} couldn't be added no media found`);
    }
Example #8
Source File: editMedia.tsx    From frames with Mozilla Public License 2.0 4 votes vote down vote up
function General({state}: { state: EditMedia }) {
    const [file, setFile] = useState<drive_v3.Schema$File | null>(null);
    const [tmdb, setTmdb] = useRecoilState(TmdbAtom);
    const [tmdbI, setTmdbI] = useState('');
    const [type, setType] = useRecoilState(TypeAtom);
    const [name, setName] = useRecoilState(NameAtom);
    const setLocation = useSetRecoilState(LocationAtom);
    const setFound = useSetRecoilState(FoundAtom);
    const [search, setSearch] = useState('');
    const setInform = useSetRecoilState(InformDisplayContext);
    const {
        response,
        abort: resAbort
    } = useFetcher<UpdateMediaSearch[]>('/api/update/mediaSearch?value=' + search + '&lib=' + (type === 'MOVIE' ? 'movie' : 'show'));
    const {
        response: data,
        abort: dataAbort
    } = useFetcher<{ file: string, found: boolean } | false>('/api/update/getMedia?value=' + tmdbI + '&lib=' + (type === 'MOVIE' ? 'movie' : 'show'));
    const {
        response: firstState,
        abort: firstAbort
    } = useFetcher<{ file: drive_v3.Schema$File | null, tmdbId: number } | null>('/api/update/getMediaFile?id=' + state.media?.id)

    useEffect(() => {
        if (state.media && firstState) {
            firstState.file && setFile(firstState.file);
            setTmdb(firstState.tmdbId);
            setName(state.media.name);
            setType(state.media.type)
        }
    }, [firstState])

    useEffect(() => {
        if (state.unScan){
            firstAbort.cancel();
            setFile(state.unScan.file);
            setType(state.unScan.type);
            if (state.unScan.res.length === 1) {
                setFound(state.unScan.available);
                setTmdb(state.unScan.res[0].tmdbId);
                setName(state.unScan.res[0].name);
            }
        }
    }, [state])

    useEffect(() => {
        if (file)
            setLocation(file.id!);
    }, [file])

    useEffect(() => {
        if (search === '')
            resAbort.cancel();

        return () => resAbort.cancel();
    }, [search])

    useEffect(() => {
        if (isNaN(parseInt(tmdbI)))
            dataAbort.cancel();
        return () => dataAbort.cancel();
    }, [tmdbI])

    useEffect(() => {
        if (data) {
            if (data.found && ((tmdb !== parseInt(tmdbI) && state.media) || state.unScan)) {
                setFound(true);
                setInform({
                    type: "error",
                    heading: 'Existing Media',
                    message: data.file + ' already exists consider deleting this duplicate'
                })
            }

            setTmdb(+(tmdbI));
            setName(data.file);
        }
    }, [data])

    if (file)
        return (
            <div className={ss.genInput}>
                <label>fileName</label>
                <br/>
                <input type="text" disabled={true} value={file.name!}/>
                <br/>
                <label>Media Name: {name}</label>
                <br/>
                <input type="text" onChange={e => setSearch(e.currentTarget.value)} defaultValue={name}/>
                <br/>
                <label>The Movie Database ID: {tmdb}</label>
                <input type="text" onChange={e => setTmdbI(e.currentTarget.value)} defaultValue={tmdb}/>

                <ul className={ss.list}>
                    {response?.map((e, v) => <li key={v} onClick={() => {
                        setName(e.name);
                        setType(e.type);
                        setTmdb(e.id);
                    }
                    }>name: {e.name} date: {e.date}</li>)}
                </ul>
            </div>
        )

    else return null;
}
Example #9
Source File: scanner.ts    From frames with Mozilla Public License 2.0 4 votes vote down vote up
/**
     * @desc scans the episode file and adds the new episode to the database
     * @param file - the file to scan
     * @param seasons - the seasons in the show folder
     * @param tmdbEpisodes - the episodes in tmdb
     * @param episodes - the episodes in the database
     * @param ignoreScan - whether to scan the entire library thoroughly or quickly
     */
    public async scanEpisode(file: drive_v3.Schema$File, seasons: drive_v3.Schema$File[], tmdbEpisodes: tmdbEpisode[], episodes: FrameEpisodeScan[], ignoreScan: boolean) {
        const maxSeason = tmdbEpisodes[tmdbEpisodes.length - 1].season_number;
        const maxEpisode = tmdbEpisodes[tmdbEpisodes.length - 1].episode_number;
        const firstSeason = tmdbEpisodes[0].season_number;
        const firstEpisode = tmdbEpisodes[0].episode_number;
        let tmdbEpisode: tmdbEpisode[] = [];
        const showId = -1;

        const season = seasons.find(s => s.id === file!.parents![0]);
        let seasonMatch = season?.name!.match(/Season\s(?<season>\d+)/i) || null;
        let seasonNumber = seasonMatch ? parseInt(seasonMatch.groups!.season) : -1;
        const name = Scanner.prepareString(file.name!);
        const slimName = name.replace(/S\d+E\d+/i, '');

        let match = name.match(/(S|SEASON)\s*(?<season>\d+).*?(E|EPISODE)\s*(?<episode>\d+)/i) || null;
        match = match ? match : name.match(/^(?<firstEpisode>\d{2}) | (?<triEpisode>\d{3})/);
        seasonNumber = seasonNumber === -1 ? parseInt(match?.groups?.season || '') : seasonNumber;
        match = match ? match : name.match(/(?<anyEpisode>\d{2})/);
        let episodeNumber = parseInt(match?.groups?.episode || match?.groups?.triEpisode || match?.groups?.firstEpisode || match?.groups?.anyEpisode || '');
        episodeNumber = Math.floor(episodeNumber / (seasonNumber * 100)) === 1 ? episodeNumber - (seasonNumber * 100) : episodeNumber;

        for (const e of tmdbEpisodes) {
            const rgx = new RegExp(`(E|EPISODE)\\s*(0)*${e.episode_number}.*?(${Scanner.prepareString(e.name!)})*`, 'i');
            const rgx2 = new RegExp(`(S|SEASON)\\s*(0)*${e.season_number}.*?(E|EPISODE)\\s*(0)*${e.episode_number}`);
            const rgx3 = new RegExp(`${Scanner.prepareString(e.name!)}`);

            if (rgx.test(slimName) || rgx2.test(name) || rgx3.test(name))
                tmdbEpisode.push(e);
        }

        if (tmdbEpisode.length > 1) {
            const temp = tmdbEpisode.filter(e => name.includes(Scanner.prepareString(e.name!)));
            if (temp.length > 0)
                tmdbEpisode = temp;
        }

        if (tmdbEpisode.length > 1) {
            const temp = tmdbEpisode.filter(e => e.episode_number === episodeNumber || e.season_number === seasonNumber);
            if (temp.length > 0)
                tmdbEpisode = temp;
        }

        if (tmdbEpisode.length > 1) {
            const temp = tmdbEpisode.filter(e => e.episode_number === episodeNumber && (match?.groups?.firstEpisode !== undefined || match?.groups?.triEpisode !== undefined));
            if (temp.length > 0)
                tmdbEpisode = temp;
        }

        if (tmdbEpisode.length > 1) {
            const temp = tmdbEpisode.filter(e => e.season_number === seasonNumber && e.episode_number === episodeNumber);
            if (temp.length > 0)
                tmdbEpisode = temp;
        }

        const temp = tmdbEpisodes.find(e => e.season_number === seasonNumber && e.episode_number === episodeNumber);
        const alreadyAdded = episodes.find(e => e.seasonId === seasonNumber && e.episode === episodeNumber);
        console.log(`${name} ${seasonNumber} ${episodeNumber} ${tmdbEpisode.length} ${alreadyAdded}`);

        if (!alreadyAdded) {
            const rgx = new RegExp(`(s|season)\\s*(0)*${seasonNumber}.*?(e|episode)\\s*(0)*${episodeNumber}`, 'i');
            if (rgx.test(name) && temp) {
                const backdrop = temp.still_path ? `https://image.tmdb.org/t/p/original${temp.still_path}` : null;
                const overview = temp.overview ? temp.overview : null;
                const name = temp.name ? temp.name : null;
                const episode: FrameEpisodeScan = {
                    backdrop,
                    name,
                    overview,
                    location: file.id!,
                    seasonId: temp.season_number,
                    episode: temp.episode_number,
                    showId
                };
                episodes.push(episode);
                console.log(episodes.length)

            } else if (temp) {
                const backdrop = temp.still_path ? `https://image.tmdb.org/t/p/original${temp.still_path}` : null;
                const overview = temp.overview ? temp.overview : null;
                const name = temp.name ? temp.name : null;
                const episode: FrameEpisodeScan = {
                    backdrop,
                    name,
                    overview,
                    location: file.id!,
                    seasonId: temp.season_number,
                    episode: temp.episode_number,
                    showId
                };
                episodes.push(episode);
                console.log(episodes.length);

            } else if (tmdbEpisode.length === 1) {
                const e = tmdbEpisode[0];
                const rgx3 = new RegExp(`${Scanner.prepareString(e.name!)}`);
                const bool = [rgx3.test(slimName) && e.episode_number === episodeNumber, e.episode_number === episodeNumber && e.season_number === seasonNumber].filter(b => b).length > 1;

                if (bool) {
                    const backdrop = e.still_path ? `https://image.tmdb.org/t/p/original${e.still_path}` : null;
                    const overview = e.overview ? e.overview : null;
                    const name = e.name ? e.name : null;
                    const episode: FrameEpisodeScan = {
                        backdrop,
                        name,
                        overview,
                        location: file.id!,
                        seasonId: e.season_number,
                        episode: e.episode_number,
                        showId
                    };
                    episodes.push(episode);
                }

            } else if (firstEpisode <= episodeNumber && episodeNumber <= maxEpisode && firstSeason <= seasonNumber && seasonNumber <= maxSeason) {
                const backdrop = null;
                const overview = null;
                const name = null;
                const episode: FrameEpisodeScan = {
                    backdrop,
                    name,
                    overview,
                    location: file.id!,
                    seasonId: seasonNumber,
                    episode: episodeNumber,
                    showId
                };
                episodes.push(episode);

            } else if (ignoreScan) {
                const backdrop = null;
                const overview = null;
                const name = null;
                const episode: FrameEpisodeScan = {
                    backdrop,
                    name,
                    overview,
                    location: file.id!,
                    seasonId: seasonNumber,
                    episode: episodeNumber,
                    showId
                };
                episodes.push(episode);
            }
        }
    }