Skip to content

Commit

Permalink
Sort the channels by channels view on the last 30 days
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel authored and daniel committed Jun 6, 2020
1 parent b9455a6 commit 8da9ba4
Show file tree
Hide file tree
Showing 12 changed files with 165 additions and 44 deletions.
62 changes: 62 additions & 0 deletions install/removeViewsStatisticsErrors.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

//streamer config
require_once '../videos/configuration.php';
require_once $global['systemRootPath'] . 'objects/playlist.php';

if (!isCommandLineInterface()) {
return die('Command Line only');
}

echo "Start fixing statistics" . PHP_EOL;

$session_id = array();
$sql = "SELECT distinct(session_id) as session_id FROM videos_statistics ";
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $key => $row) {
$session_id[] = $row['session_id'];
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}


foreach ($session_id as $id) {
echo "Process session_id = {$id}\n";
ob_flush();
$sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE session_id = '{$id}'";
echo $sql . PHP_EOL;
$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
$rows = array();
if ($res != false) {
foreach ($fullData as $row) {
$sql2 = "SELECT id FROM videos_statistics WHERE videos_id = {$row['videos_id']} AND session_id = '{$id}' ORDER BY `when` DESC LIMIT 1";
echo $sql . PHP_EOL;
$res2 = sqlDAL::readSql($sql2);
$fullData2 = sqlDAL::fetchAllAssoc($res2);
sqlDAL::close($res2);
if ($res != false) {
foreach ($fullData2 as $key2 => $row2) {
$sql = "DELETE FROM videos_statistics ";
$sql .= " WHERE videos_id = {$row['videos_id']} AND session_id = '{$id}' AND id != {$row2['id']} ";

echo $sql . PHP_EOL;
ob_flush();
sqlDAL::writeSql($sql);
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}
} else {
die($sql . '\nError : (' . $global['mysqli']->errno . ') ' . $global['mysqli']->error);
}
}

echo "Finish fixing statistics" . PHP_EOL;
5 changes: 3 additions & 2 deletions objects/Channel.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class Channel{

static function getChannels($activeOnly=true){
static function getChannels($activeOnly=true, $FIND_IN_SET = ""){
global $global;
$sql = "SELECT u.*, "
. " (SELECT count(v.id) FROM videos v where v.users_id = u.id) as total_videos "
Expand All @@ -17,7 +17,8 @@ static function getChannels($activeOnly=true){
if($activeOnly){
$sql .= " AND u.status = 'a' ";
}
$sql .= BootGrid::getSqlFromPost(array('user', 'about'));
$sql .= BootGrid::getSqlFromPost(array('user', 'about'), "", "", false, $FIND_IN_SET);

$res = sqlDAL::readSql($sql);
$fullResult = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
Expand Down
7 changes: 5 additions & 2 deletions objects/bootGrid.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php
class BootGrid {

static function getSqlFromPost($searchFieldsNames = array(), $keyPrefix = "", $alternativeOrderBy = "", $doNotSearch=false) {
static function getSqlFromPost($searchFieldsNames = array(), $keyPrefix = "", $alternativeOrderBy = "", $doNotSearch=false, $FIND_IN_SET = "") {
if(empty($doNotSearch)){
$sql = self::getSqlSearchFromPost($searchFieldsNames);
}else{
Expand All @@ -14,7 +14,10 @@ static function getSqlFromPost($searchFieldsNames = array(), $keyPrefix = "", $a
$_POST['sort'][$_GET['columns'][$index]['data']] = $_GET['order'][0]['dir'];
}

if (!empty($_POST['sort'])) {

if(!empty($FIND_IN_SET)){
$sql .= " ORDER BY FIND_IN_SET({$FIND_IN_SET}) ";
}else if (!empty($_POST['sort'])) {
$orderBy = array();
foreach ($_POST['sort'] as $key => $value) {
$direction = "ASC";
Expand Down
2 changes: 1 addition & 1 deletion objects/video.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ function addViewPercent($percent = 25) {
// allow users to count a view again in case it is refreshed
static function unsetAddView($videos_id) {
// allow users to count a view again in case it is refreshed
if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time']+30 <= time()) {// added 30 seconds tolerance
if (!empty($_SESSION['addViewCount'][$videos_id]['time']) && $_SESSION['addViewCount'][$videos_id]['time'] <= time()) {
_session_start();
unset($_SESSION['addViewCount'][$videos_id]);
}
Expand Down
6 changes: 4 additions & 2 deletions objects/videoAddViewCount.json.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
if (empty($obj)) {
die("Object not found");
}

_session_start();
if (empty($_SESSION['addViewCount'])) {
$_SESSION['addViewCount'] = array();
}
Expand All @@ -30,14 +30,16 @@
if ($percent >= $value) {
if (empty($_SESSION['addViewCount'][$_POST['id']][$value]) && !empty($_POST['currentTime'])) {
if ($obj->addViewPercent($value)) {
_session_start();
$_SESSION['addViewCount'][$_POST['id']][$value] = 1;
}
}
}
}
}
}
if (empty($_SESSION['addViewCount'][$_POST['id']]['time'])) {
$resp = $obj->addView();
_session_start();
$_SESSION['addViewCount'][$_POST['id']]['time'] = strtotime("+{$seconds} seconds");
} else if (!empty($_POST['currentTime'])) {
$resp = VideoStatistic::updateStatistic($obj->getId(), User::getId(), intval($_POST['currentTime']));
Expand Down
73 changes: 60 additions & 13 deletions objects/video_statistic.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ static function create($videos_id, $currentTime = 0) {
global $global;
/**
* Dont crash if is an old version
$res = sqlDAL::readSql("SHOW TABLES LIKE 'videos_statistics'");
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
if (empty($result)) {
echo "<div class='alert alert-danger'>You need to <a href='{$global['webSiteRootURL']}update'>update your system</a></div>";
return false;
}
*/
$res = sqlDAL::readSql("SHOW TABLES LIKE 'videos_statistics'");
$result = sqlDal::num_rows($res);
sqlDAL::close($res);
if (empty($result)) {
echo "<div class='alert alert-danger'>You need to <a href='{$global['webSiteRootURL']}update'>update your system</a></div>";
return false;
}
*/
if (empty($videos_id)) {
die(__("You need a video to generate statistics"));
}
Expand Down Expand Up @@ -95,10 +95,10 @@ function save() {
static function getLastStatistics($videos_id, $users_id = 0) {
if (!empty($users_id)) {
$sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND users_id = ? ORDER BY modified DESC LIMIT 1 ";
$res = sqlDAL::readSql($sql, 'ii', array($videos_id, $users_id));
$res = sqlDAL::readSql($sql, 'ii', array($videos_id, $users_id), true);
} else {
$sql = "SELECT * FROM videos_statistics WHERE videos_id = ? AND session_id = ? ORDER BY modified DESC LIMIT 1 ";
$res = sqlDAL::readSql($sql, 'is', array($videos_id, session_id()));
$res = sqlDAL::readSql($sql, 'is', array($videos_id, session_id()), true);
}
$result = sqlDAL::fetchAssoc($res);
sqlDAL::close($res);
Expand Down Expand Up @@ -155,7 +155,7 @@ static function getStatisticTotalViews($videos_id, $uniqueUsers = false, $startD
static function getTotalLastDaysAsync($video_id, $numberOfDays) {
global $global, $advancedCustom;
$md5 = ("{$video_id}_{$numberOfDays}");
$path = getCacheDir()."getTotalLastDaysAsync/";
$path = getCacheDir() . "getTotalLastDaysAsync/";
make_path($path);
$cacheFileName = "{$path}{$md5}";
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) {
Expand Down Expand Up @@ -199,7 +199,7 @@ static function getTotalToday($video_id, $hour = 0, $returnArray = array()) {

static function getTotalTodayAsync($video_id) {
global $global, $advancedCustom;
$cacheFileName = getCacheDir()."getTotalTodayAsync_{$video_id}";
$cacheFileName = getCacheDir() . "getTotalTodayAsync_{$video_id}";
if (empty($advancedCustom->AsyncJobs) || !file_exists($cacheFileName)) {
if (file_exists($cacheFileName . ".lock")) {
return array();
Expand Down Expand Up @@ -269,4 +269,51 @@ function setSession_id($session_id) {
$this->session_id = $session_id;
}

static function getChannelsWithMoreViews($daysLimit = 30) {
global $global;
// get unique videos ids from the requested timeframe
$sql = "SELECT distinct(videos_id) as videos_id FROM videos_statistics WHERE DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) ";

$res = sqlDAL::readSql($sql);
$fullData = sqlDAL::fetchAllAssoc($res);
sqlDAL::close($res);
// get the channel owner from each of those videos
$channels = array();
if ($res != false) {
foreach ($fullData as $row) {
$users_id = Video::getOwner($row['videos_id']);
if (empty($channels[$users_id])) {
$channels[$users_id] = array();
}
$channels[$users_id][] = $row['videos_id'];
}

foreach ($channels as $key => $value) {
// count how many views each one has
$sql2 = "SELECT count(id) as total FROM videos_statistics WHERE videos_id IN (" . implode(",", $value) . ") AND DATE(created) >= DATE_SUB(DATE(NOW()), INTERVAL {$daysLimit} DAY) ";
$res2 = sqlDAL::readSql($sql2);
$result2 = sqlDAL::fetchAssoc($res2);
sqlDAL::close($res2);
if (!empty($result2)) {
$channels[$key]['users_id'] = $key;
$channels[$key]['total'] = intval($result2['total']);
}
}
}
// return more first
usort($channels, function($a, $b) {
return $b['total'] - $a['total'];
});
return $channels;
}

static function getUsersIDFromChannelsWithMoreViews($daysLimit = 30) {
$channels = self::getChannelsWithMoreViews($daysLimit);
$users_id = array();
foreach ($channels as $value) {
$users_id[] = $value['users_id'];
}
return $users_id;
}

}
33 changes: 16 additions & 17 deletions plugin/API/API.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,36 +136,35 @@ public function get_api_category($parameters) {
public function get_api_video_from_program($parameters){
global $global;
$playlists = AVideoPlugin::loadPlugin("PlayLists");
$obj = $this->startResponseObject($parameters);
if(empty($obj->playlists_id)){
return new ApiObject("Playlist ID is empty", true, $obj);
if(empty($parameters['playlists_id'])){
return new ApiObject("Playlist ID is empty", true, $parameters);
}
$videos = PlayLists::getOnlyVideosAndAudioIDFromPlaylistLight($obj->playlists_id);
$videos = PlayLists::getOnlyVideosAndAudioIDFromPlaylistLight($parameters['playlists_id']);

if(empty($videos)){
return new ApiObject("There are no videos for this playlist", true, $obj);
return new ApiObject("There are no videos for this playlist", true, $parameters);
}

if(empty($obj->index)){
$obj->index = 0;
if(empty($parameters['index'])){
$parameters['index'] = 0;
}

if(empty($videos[$obj->index])){
$videos_id = $videos[0];
if(empty($videos[$parameters['index']])){
$video = $videos[0];
}else{
$videos_id = $videos[$obj->index];
$video = $videos[$parameters['index']];
}

$obj->nextIndex = $obj->index+1;
$parameters['nextIndex'] = $parameters['index']+1;

if(empty($videos[$obj->nextIndex])){
$obj->nextIndex = 0;
if(empty($videos[$parameters['nextIndex']])){
$parameters['nextIndex'] = 0;
}
$videoPath = Video::getHigherVideoPathFromID($video['id']);
$parameters['videos_id'] = $video['id'];
$parameters['path'] = $videoPath;

$video = Video::getHigherVideosPathsFromID($videos_id);
$obj->path = $video;
$obj->nextIndex = $video;
return new ApiObject("", false, $obj);
return new ApiObject("", false, $parameters);
}

/**
Expand Down
3 changes: 2 additions & 1 deletion plugin/PlayLists/PlayLists.php
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,8 @@ static function getOnlyVideosAndAudioIDFromPlaylistLight($playlists_id) {
global $global;
$sql = "SELECT * FROM playlists_has_videos p "
. " LEFT JOIN videos v ON videos_id = v.id "
. " WHERE playlists_id = ? AND v.status IN ('" . implode("','", Video::getViewableStatus(true)) . "')";
. " WHERE playlists_id = ? AND v.status IN ('" . implode("','", Video::getViewableStatus(true)) . "')"
. " AND (`type` = 'video' OR `type` = 'audio' ) ORDER BY p.`order` ";

$sort = @$_POST['sort'];
$_POST['sort'] = array();
Expand Down
8 changes: 4 additions & 4 deletions plugin/PlayLists/playProgramsLive.json.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
die(json_encode($obj));
}

$live = AVideoPlugin::loadPluginIfEnabled("Live");
$live = AVideoPlugin::getObjectDataIfEnabled("Live");
if (empty($live)) {
$obj->msg = __("Live Plugin is not enabled");
_error_log("playProgramsLive:: {$obj->msg}");
Expand Down Expand Up @@ -70,14 +70,14 @@
}

Live::stopLive($users_id);

$videosListToLive = "{$encoder}videosListToLive.php?playlists_id={$playlists_id}&APISecret={$api->APISecret}&webSiteRootURL={$global['webSiteRootURL']}&user=".User::getUserName()."&pass=".User::getUserPass()."&liveKey={$key}&rtmp=". urlencode($live->server);
$webSiteRootURL = urlencode($global['webSiteRootURL']);
$videosListToLive = "{$encoder}videosListToLive?playlists_id={$playlists_id}&APISecret={$api->APISecret}&webSiteRootURL={$webSiteRootURL}&user=".User::getUserName()."&pass=".User::getUserPass()."&liveKey={$key}&rtmp=". urlencode($live->server);

$cmd = "wget -O/dev/null -q \"{$videosListToLive}\" > /dev/null 2>/dev/null &";
_error_log("playProgramsLive:: {$cmd}");
//echo "** executing command {$cmd}\n";
exec($cmd);


$obj->videosListToLive = $videosListToLive;
$obj->error = false;
die(json_encode($obj));
2 changes: 1 addition & 1 deletion view/channelProgram.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
<a href="<?php echo $link; ?>" class="btn btn-xs btn-default playAll hrefLink" ><span class="fa fa-play"></span> <?php echo __("Play All"); ?></a><?php echo $playListButtons; ?>
<?php
$liveLink = PlayLists::getLiveLink($program['id']);
if(false && !empty($liveLink)){
if(!empty($liveLink)){
?>
<a href="<?php echo $liveLink; ?>" class="btn btn-xs btn-default playAll hrefLink" ><i class="fas fa-broadcast-tower"></i> <?php echo __("Play Live"); ?></a>
<?php
Expand Down
5 changes: 4 additions & 1 deletion view/channels.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@
} else {
$_POST['current'] = 1;
}

$users_id_array = VideoStatistic::getUsersIDFromChannelsWithMoreViews();

$current = $_POST['current'];
$_POST['rowCount'] = 10;
$channels = Channel::getChannels();
$channels = Channel::getChannels(true, "u.id, '". implode(",", $users_id_array)."'");

$totalPages = ceil($totalChannels / $_POST['rowCount']);
?>
Expand Down
3 changes: 3 additions & 0 deletions view/userLogin.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<?php
if (empty($_COOKIE) && empty($_GET['cookieLogin'])) {
// TODO implement a popup login for cross domain cookie block
}
if (empty($_GET['redirectUri'])) {
if (!empty($_SERVER["HTTP_REFERER"])) {
// if comes from the streamer domain
Expand Down

0 comments on commit 8da9ba4

Please sign in to comment.