<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Ninegag
 *
 * @author Nexthon
 */
/*
  {source_info}{"name":"9gag.com","website":"https:\/\/www.9gag.com\/"}{end_source_info}
 */

class Ninegag
{

    public function getMediaInfo($url)
    {
        $path = parse_url($url, PHP_URL_PATH);
        $pieces = explode('/', $path);
        $id = $pieces[2];

        $result = file_get_contents($url);

        $videoHDlink = "https://img-9gag-fun.9cache.com/photo/" . $id . "_460sv.mp4";
        $videoSDlink = "https://img-9gag-fun.9cache.com/photo/" . $id . "_460svwm.webm";

        if ($videoSDlink)
        {

            $data['found'] = 1;
            $data['id'] = $id;
            $links = array();

            $links['SD'] = $videoSDlink;
            if (!empty($videoHDlink))
            {
                $links['HD'] = $videoHDlink;
            }


            $image = "http://images-cdn.9gag.com/photo/" . $id . "_460s.jpg";
            $data['image'] = $image;

            if ($result)
            {
                $title = getStringBetween($result, '<meta property="og:title" content="', '" />');
                ;
                $description = getStringBetween($result, '<meta property="og:description" content="', '" />');


                $data['title'] = $title;

                $data['description'] = $description;
            }



            $formatCodes = array(
                "SD" => array("order" => "1", "height" => "{{height}}", "ext" => "mp4", "resolution" => "SD", "video" => "true", "video_only" => "false"),
                "HD" => array("order" => "2", "height" => "{{height}}", "ext" => "mp4", "resolution" => "HD", "video" => "true", "video_only" => "false")
            );
            $videos = array();
            foreach ($formatCodes as $formatId => $formatData)
            {
                if (isset($links[$formatId]))
                {
                    $link = array();
                    $link['data'] = $formatData;
                    $link['formatId'] = $formatId;
                    $link['order'] = $formatData['order'];
                    $link['url'] = $links[$formatId];
                    $link['title'] = $title . "." . $formatData['ext'];
                    $link['size'] = "unknown";
                    array_push($videos, $link);
                }
            }
            $data['videos'] = $videos;
        }

        return $data;
    }

}
