<?php
class twitter{
	public $url;
	public $title;
	public $id;
	public $image;
	public $video;
	public $links;
	public $error = false;
	public $msg;
	
	function __construct($url){
		$this->url = $url;
	}
	
	public function videoid() {
		$url = $this->url;
		$arr = explode( "/", $url );
		if ( is_numeric( end( $arr ) ) && end( $arr ) > 5 ) {
			$id = end( $arr );
		} else {
			$regex = '#https?://twitter\.com/(?:\#!/)?(\w+)/status(es)?/(\d+)#is';
			if ( preg_match( $regex, $url, $match ) ) {
				$id = end( $match );
			} else {
				$id = null;
			}
		}
		$this->id = $id;
		return $id;
	}
	
	private function quality($value){
		$preg = preg_match( '/.*?\/\d+x(\d+)\/.*?/i', $value, $match );
		if ( isset( $match[1] ) && is_numeric( $match[1] ) ) {
			$get = $match[1];
			if ( $get > 719 ) {
				return "High Definition";
			} elseif ( $get > 479 && $get < 719 ) {
				return "High Quality";
			} elseif ( $get > 359 && $get < 480 ) {
				return "Medium Quality";
			} else {
				return "Low Quality";
			}
		} else {
			return "Download";
		}
	}
		
	
	public function get_tweet(){
		include( "twitter/autoload.php" );
		if($this->videoid()==false){
			$this->error = true;
			$this->msg = "<div id='download-error'>Tweet doesn't exists.</div>";
			return false;
		}
		$tweet = $connection->get("statuses/show",
		[ "id" => $this->id, 'tweet_mode' => 'extended' ] );
		if ( ! isset( $tweet->full_text ) ) {
			$this->error = true;
			$this->msg = "<div id='download-error'>Tweet doesn't exists.</div>";
			return false;
		}
		$this->title = $tweet->full_text;
		if(!isset($tweet->extended_entities->media[0]->video_info)){
			$this->error = true;
			$this->msg = "<div id='download-error'>No Videos found.</div>";
			return false;
		}
		$this->image = $tweet->entities->media[0]->media_url;
		$media     = (array) $tweet->extended_entities->media;
		$link     = $media[0]->video_info->variants;
		$links = array();
		foreach ( $link as $video ) {
			if ($video->content_type!=='application/x-mpegURL'){
				$search = preg_match("/.*\/(.*)\/.*/i", $video->url,$match);
				if($match[1]=="tweet_video"){
					$match[1] = "Download GIF!";
				}
				$links[] = array("url" => $video->url ,"quality" => $this->quality( $video->url ));
				if($this->quality( $video->url )=="Medium Quality"){
					$this->video = $video->url;
				}
			}
		}
		$this->links = $links;
	}
}
