StoredFile.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. <?php
  2. require_once 'formatters/LengthFormatter.php';
  3. require_once 'formatters/SamplerateFormatter.php';
  4. require_once 'formatters/BitrateFormatter.php';
  5. /**
  6. * Application_Model_StoredFile class
  7. *
  8. * @package Airtime
  9. * @subpackage StorageServer
  10. * @copyright 2010 Sourcefabric O.P.S.
  11. * @license http://www.gnu.org/licenses/gpl.txt
  12. * @see MetaData
  13. */
  14. class Application_Model_StoredFile
  15. {
  16. /**
  17. * @holds propel database object
  18. */
  19. private $_file;
  20. /**
  21. * @holds PDO object reference
  22. */
  23. private $_con;
  24. /**
  25. * array of db metadata -> propel
  26. */
  27. private $_dbMD = array (
  28. "track_title" => "DbTrackTitle",
  29. "artist_name" => "DbArtistName",
  30. "album_title" => "DbAlbumTitle",
  31. "genre" => "DbGenre",
  32. "mood" => "DbMood",
  33. "track_number" => "DbTrackNumber",
  34. "bpm" => "DbBpm",
  35. "label" => "DbLabel",
  36. "composer" => "DbComposer",
  37. "encoded_by" => "DbEncodedBy",
  38. "conductor" => "DbConductor",
  39. "year" => "DbYear",
  40. "info_url" => "DbInfoUrl",
  41. "isrc_number" => "DbIsrcNumber",
  42. "copyright" => "DbCopyright",
  43. "length" => "DbLength",
  44. "bit_rate" => "DbBitRate",
  45. "sample_rate" => "DbSampleRate",
  46. "mime" => "DbMime",
  47. //"md5" => "DbMd5",
  48. "ftype" => "DbFtype",
  49. "language" => "DbLanguage",
  50. "replay_gain" => "DbReplayGain",
  51. "directory" => "DbDirectory",
  52. "owner_id" => "DbOwnerId",
  53. "cuein" => "DbCueIn",
  54. "cueout" => "DbCueOut",
  55. );
  56. function __construct($file, $con) {
  57. $this->_file = $file;
  58. $this->_con = $con;
  59. }
  60. public function getId()
  61. {
  62. return $this->_file->getDbId();
  63. }
  64. public function getFormat()
  65. {
  66. return $this->_file->getDbFtype();
  67. }
  68. public function getPropelOrm()
  69. {
  70. return $this->_file;
  71. }
  72. public function setFormat($p_format)
  73. {
  74. $this->_file->setDbFtype($p_format);
  75. }
  76. /* This function is only called after liquidsoap
  77. * has notified that a track has started playing.
  78. */
  79. public function setLastPlayedTime($p_now)
  80. {
  81. $this->_file->setDbLPtime($p_now);
  82. /* Normally we would only call save after all columns have been set
  83. * like in setDbColMetadata(). But since we are only setting one
  84. * column in this case it is OK.
  85. */
  86. $this->_file->save();
  87. }
  88. public static function createWithFile($f, $con) {
  89. $storedFile = new Application_Model_StoredFile($f, $con);
  90. return $storedFile;
  91. }
  92. /**
  93. * Set multiple metadata values using defined metadata constants.
  94. *
  95. * @param array $p_md
  96. * example: $p_md['MDATA_KEY_URL'] = 'http://www.fake.com'
  97. */
  98. public function setMetadata($p_md=null)
  99. {
  100. if (is_null($p_md)) {
  101. $this->setDbColMetadata();
  102. } else {
  103. $dbMd = array();
  104. if (isset($p_md["MDATA_KEY_YEAR"])) {
  105. // We need to make sure to clean this value before
  106. // inserting into database. If value is outside of range
  107. // [-2^31, 2^31-1] then postgresl will throw error when
  108. // trying to retrieve this value. We could make sure
  109. // number is within these bounds, but simplest is to do
  110. // substring to 4 digits (both values are garbage, but
  111. // at least our new garbage value won't cause errors).
  112. // If the value is 2012-01-01, then substring to first 4
  113. // digits is an OK result. CC-3771
  114. $year = $p_md["MDATA_KEY_YEAR"];
  115. if (strlen($year) > 4) {
  116. $year = substr($year, 0, 4);
  117. }
  118. if (!is_numeric($year)) {
  119. $year = 0;
  120. }
  121. $p_md["MDATA_KEY_YEAR"] = $year;
  122. }
  123. # Translate metadata attributes from media monitor (MDATA_KEY_*)
  124. # to their counterparts in constants.php (usually the column names)
  125. $track_length = $p_md['MDATA_KEY_DURATION'];
  126. $track_length_in_sec = Application_Common_DateHelper::calculateLengthInSeconds($track_length);
  127. foreach ($p_md as $mdConst => $mdValue) {
  128. if (defined($mdConst)) {
  129. if ($mdConst == "MDATA_KEY_CUE_OUT") {
  130. if ($mdValue == '0.0') {
  131. $mdValue = $track_length_in_sec;
  132. } else {
  133. $this->_file->setDbSilanCheck(true)->save();
  134. }
  135. }
  136. $dbMd[constant($mdConst)] = $mdValue;
  137. }
  138. }
  139. $this->setDbColMetadata($dbMd);
  140. }
  141. }
  142. /**
  143. * Set multiple metadata values using database columns as indexes.
  144. *
  145. * @param array $p_md
  146. * example: $p_md['url'] = 'http://www.fake.com'
  147. */
  148. public function setDbColMetadata($p_md=null)
  149. {
  150. if (is_null($p_md)) {
  151. foreach ($this->_dbMD as $dbColumn => $propelColumn) {
  152. $method = "set$propelColumn";
  153. $this->_file->$method(null);
  154. }
  155. } else {
  156. $owner = $this->_file->getFkOwner();
  157. // if owner_id is already set we don't want to set it again.
  158. if (!$owner) { // no owner detected, we try to assign one.
  159. // if MDATA_OWNER_ID is not set then we default to the
  160. // first admin user we find
  161. if (!array_key_exists('owner_id', $p_md)) {
  162. //$admins = Application_Model_User::getUsers(array('A'));
  163. $admins = Application_Model_User::getUsersOfType('A');
  164. if (count($admins) > 0) { // found admin => pick first one
  165. $owner = $admins[0];
  166. }
  167. }
  168. // get the user by id and set it like that
  169. else {
  170. $user = CcSubjsQuery::create()
  171. ->findPk($p_md['owner_id']);
  172. if ($user) {
  173. $owner = $user;
  174. }
  175. }
  176. if ($owner) {
  177. $this->_file->setDbOwnerId( $owner->getDbId() );
  178. } else {
  179. Logging::info("Could not find suitable owner for file
  180. '".$p_md['filepath']."'");
  181. }
  182. }
  183. # We don't want to process owner_id in bulk because we already
  184. # processed it in the code above. This is done because owner_id
  185. # needs special handling
  186. if (array_key_exists('owner_id', $p_md)) {
  187. unset($p_md['owner_id']);
  188. }
  189. foreach ($p_md as $dbColumn => $mdValue) {
  190. // don't blank out name, defaults to original filename on first
  191. // insertion to database.
  192. if ($dbColumn == "track_title" && (is_null($mdValue) || $mdValue == "")) {
  193. continue;
  194. }
  195. # TODO : refactor string evals
  196. if (isset($this->_dbMD[$dbColumn])) {
  197. $propelColumn = $this->_dbMD[$dbColumn];
  198. $method = "set$propelColumn";
  199. /* We need to set track_number to null if it is an empty string
  200. * because propel defaults empty strings to zeros */
  201. if ($dbColumn == "track_number" && empty($mdValue)) $mdValue = null;
  202. $this->_file->$method($mdValue);
  203. }
  204. }
  205. }
  206. $this->_file->setDbMtime(new DateTime("now", new DateTimeZone("UTC")));
  207. $this->_file->save($this->_con);
  208. }
  209. /**
  210. * Set metadata element value
  211. *
  212. * @param string $category
  213. * Metadata element by metadata constant
  214. * @param string $value
  215. * value to store, if NULL then delete record
  216. */
  217. public function setMetadataValue($p_category, $p_value)
  218. {
  219. // constant() was used because it gets quoted constant name value from
  220. // api_client.py. This is the wrapper funtion
  221. $this->setDbColMetadataValue(constant($p_category), $p_value);
  222. }
  223. /**
  224. * Set metadata element value
  225. *
  226. * @param string $category
  227. * Metadata element by db column
  228. * @param string $value
  229. * value to store, if NULL then delete record
  230. */
  231. public function setDbColMetadataValue($p_category, $p_value)
  232. {
  233. //don't blank out name, defaults to original filename on first insertion to database.
  234. if ($p_category == "track_title" && (is_null($p_value) || $p_value == "")) {
  235. return;
  236. }
  237. if (isset($this->_dbMD[$p_category])) {
  238. // TODO : fix this crust -- RG
  239. $propelColumn = $this->_dbMD[$p_category];
  240. $method = "set$propelColumn";
  241. $this->_file->$method($p_value);
  242. $this->_file->save();
  243. }
  244. }
  245. /**
  246. * Get metadata as array, indexed by the column names in the database.
  247. *
  248. * @return array
  249. */
  250. public function getDbColMetadata()
  251. {
  252. $md = array();
  253. foreach ($this->_dbMD as $dbColumn => $propelColumn) {
  254. $method = "get$propelColumn";
  255. $md[$dbColumn] = $this->_file->$method();
  256. }
  257. return $md;
  258. }
  259. /**
  260. * Get metadata as array, indexed by the constant names.
  261. *
  262. * @return array
  263. */
  264. public function getMetadata()
  265. {
  266. $c = get_defined_constants(true);
  267. $md = array();
  268. /* Create a copy of dbMD here and create a "filepath" key inside of
  269. * it. The reason we do this here, instead of creating this key inside
  270. * dbMD is because "filepath" isn't really metadata, and we don't want
  271. * filepath updated everytime the metadata changes. Also it needs extra
  272. * processing before we can write it to the database (needs to be split
  273. * into base and relative path)
  274. * */
  275. $dbmd_copy = $this->_dbMD;
  276. $dbmd_copy["filepath"] = "DbFilepath";
  277. foreach ($c['user'] as $constant => $value) {
  278. if (preg_match('/^MDATA_KEY/', $constant)) {
  279. if (isset($dbmd_copy[$value])) {
  280. $propelColumn = $dbmd_copy[$value];
  281. $method = "get$propelColumn";
  282. $md[$constant] = $this->_file->$method();
  283. }
  284. }
  285. }
  286. return $md;
  287. }
  288. /**
  289. * Returns an array of playlist objects that this file is a part of.
  290. * @return array
  291. */
  292. public function getPlaylists()
  293. {
  294. $con = Propel::getConnection();
  295. $sql = <<<SQL
  296. SELECT playlist_id
  297. FROM cc_playlist
  298. WHERE file_id = :file_id
  299. SQL;
  300. $stmt = $con->prepare($sql);
  301. $stmt->bindParam(':file_id', $this->id, PDO::PARAM_INT);
  302. if ($stmt->execute()) {
  303. $ids = $stmt->fetchAll();
  304. } else {
  305. $msg = implode(',', $stmt->errorInfo());
  306. throw new Exception("Error: $msg");
  307. }
  308. if (is_array($ids) && count($ids) > 0) {
  309. return array_map( function ($id) {
  310. return Application_Model_Playlist::RecallById($id);
  311. }, $ids);
  312. } else {
  313. return array();
  314. }
  315. }
  316. /**
  317. * Delete stored virtual file
  318. *
  319. * @param boolean $p_deleteFile
  320. *
  321. */
  322. public function delete()
  323. {
  324. $filepath = $this->getFilePath();
  325. // Check if the file is scheduled to be played in the future
  326. if (Application_Model_Schedule::IsFileScheduledInTheFuture($this->getId())) {
  327. throw new DeleteScheduledFileException();
  328. }
  329. $userInfo = Zend_Auth::getInstance()->getStorage()->read();
  330. $user = new Application_Model_User($userInfo->id);
  331. $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER));
  332. if (!$isAdminOrPM && $this->getFileOwnerId() != $user->getId()) {
  333. throw new FileNoPermissionException();
  334. }
  335. $music_dir = Application_Model_MusicDir::getDirByPK($this->_file->getDbDirectory());
  336. $type = $music_dir->getType();
  337. if (file_exists($filepath) && $type == "stor") {
  338. $data = array("filepath" => $filepath, "delete" => 1);
  339. try {
  340. Application_Model_RabbitMq::SendMessageToMediaMonitor("file_delete", $data);
  341. } catch (Exception $e) {
  342. Logging::error($e->getMessage());
  343. return;
  344. }
  345. }
  346. // set hidden flag to true
  347. $this->_file->setDbHidden(true);
  348. $this->_file->save();
  349. // need to explicitly update any playlist's and block's length
  350. // that contains the file getting deleted
  351. $fileId = $this->_file->getDbId();
  352. $plRows = CcPlaylistcontentsQuery::create()->filterByDbFileId()->find();
  353. foreach ($plRows as $row) {
  354. $pl = CcPlaylistQuery::create()->filterByDbId($row->getDbPlaylistId($fileId))->findOne();
  355. $pl->setDbLength($pl->computeDbLength(Propel::getConnection(CcPlaylistPeer::DATABASE_NAME)));
  356. $pl->save();
  357. }
  358. $blRows = CcBlockcontentsQuery::create()->filterByDbFileId($fileId)->find();
  359. foreach ($blRows as $row) {
  360. $bl = CcBlockQuery::create()->filterByDbId($row->getDbBlockId())->findOne();
  361. $bl->setDbLength($bl->computeDbLength(Propel::getConnection(CcBlockPeer::DATABASE_NAME)));
  362. $bl->save();
  363. }
  364. }
  365. /**
  366. * This function is for when media monitor detects deletion of file
  367. * and trying to update airtime side
  368. *
  369. * @param boolean $p_deleteFile
  370. *
  371. */
  372. public function deleteByMediaMonitor($deleteFromPlaylist=false)
  373. {
  374. $filepath = $this->getFilePath();
  375. if ($deleteFromPlaylist) {
  376. Application_Model_Playlist::DeleteFileFromAllPlaylists($this->getId());
  377. }
  378. // set file_exists flag to false
  379. $this->_file->setDbFileExists(false);
  380. $this->_file->save();
  381. }
  382. public function getRealFileExtension() {
  383. $path = $this->_file->getDbFilepath();
  384. $path_elements = explode('.', $path);
  385. if (count($path_elements) < 2) {
  386. return "";
  387. } else {
  388. return $path_elements[count($path_elements) - 1];
  389. }
  390. }
  391. /**
  392. * Return suitable extension.
  393. *
  394. * @return string
  395. * file extension without a dot
  396. */
  397. public function getFileExtension()
  398. {
  399. $possible_ext = $this->getRealFileExtension();
  400. if ($possible_ext !== "") {
  401. return $possible_ext;
  402. }
  403. // We fallback to guessing the extension from the mimetype if we
  404. // cannot extract it from the file name
  405. $mime = $this->_file->getDbMime();
  406. if ($mime == "audio/ogg" || $mime == "application/ogg") {
  407. return "ogg";
  408. } elseif ($mime == "audio/mp3" || $mime == "audio/mpeg") {
  409. return "mp3";
  410. } elseif ($mime == "audio/x-flac") {
  411. return "flac";
  412. } elseif ($mime == "audio/mp4") {
  413. return "mp4";
  414. } else {
  415. throw new Exception("Unknown $mime");
  416. }
  417. }
  418. /**
  419. * Get real filename of raw media data
  420. *
  421. * @return string
  422. */
  423. public function getFilePath()
  424. {
  425. $music_dir = Application_Model_MusicDir::getDirByPK($this->
  426. _file->getDbDirectory());
  427. $directory = $music_dir->getDirectory();
  428. $filepath = $this->_file->getDbFilepath();
  429. return Application_Common_OsPath::join($directory, $filepath);
  430. }
  431. /**
  432. * Set real filename of raw media data
  433. *
  434. * @return string
  435. */
  436. public function setFilePath($p_filepath)
  437. {
  438. $path_info = Application_Model_MusicDir::splitFilePath($p_filepath);
  439. if (is_null($path_info)) {
  440. return -1;
  441. }
  442. $musicDir = Application_Model_MusicDir::getDirByPath($path_info[0]);
  443. $this->_file->setDbDirectory($musicDir->getId());
  444. $this->_file->setDbFilepath($path_info[1]);
  445. $this->_file->save($this->_con);
  446. }
  447. /**
  448. * Get the URL to access this file
  449. */
  450. public function getFileUrl()
  451. {
  452. $CC_CONFIG = Config::getConfig();
  453. $protocol = empty($_SERVER['HTTPS']) ? "http" : "https";
  454. $serverName = $_SERVER['SERVER_NAME'];
  455. $serverPort = $_SERVER['SERVER_PORT'];
  456. $subDir = $CC_CONFIG['baseDir'];
  457. if ($subDir[0] === "/") {
  458. $subDir = substr($subDir, 1, strlen($subDir) - 1);
  459. }
  460. $baseUrl = "{$protocol}://{$serverName}:{$serverPort}/{$subDir}";
  461. return $this->getRelativeFileUrl($baseUrl);
  462. }
  463. /**
  464. * Sometimes we want a relative URL and not a full URL. See bug
  465. * http://dev.sourcefabric.org/browse/CC-2403
  466. */
  467. public function getRelativeFileUrl($baseUrl)
  468. {
  469. return $baseUrl."api/get-media/file/".$this->getId().".".$this->getFileExtension();
  470. }
  471. public static function Insert($md, $con)
  472. {
  473. // save some work by checking if filepath is given right away
  474. if ( !isset($md['MDATA_KEY_FILEPATH']) ) {
  475. return null;
  476. }
  477. $file = new CcFiles();
  478. $now = new DateTime("now", new DateTimeZone("UTC"));
  479. $file->setDbUtime($now);
  480. $file->setDbMtime($now);
  481. $storedFile = new Application_Model_StoredFile($file, $con);
  482. // removed "//" in the path. Always use '/' for path separator
  483. // TODO : it might be better to just call OsPath::normpath on the file
  484. // path. Also note that mediamonitor normalizes the paths anyway
  485. // before passing them to php so it's not necessary to do this at all
  486. $filepath = str_replace("//", "/", $md['MDATA_KEY_FILEPATH']);
  487. $res = $storedFile->setFilePath($filepath);
  488. if ($res === -1) {
  489. return null;
  490. }
  491. $storedFile->setMetadata($md);
  492. return $storedFile;
  493. }
  494. /* TODO: Callers of this function should use a Propel transaction. Start
  495. * by creating $con outside the function with beingTransaction() */
  496. public static function RecallById($p_id=null, $con=null) {
  497. //TODO
  498. if (is_null($con)) {
  499. $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
  500. }
  501. if (isset($p_id)) {
  502. $f = CcFilesQuery::create()->findPK(intval($p_id), $con);
  503. return is_null($f) ? null : self::createWithFile($f, $con);
  504. } else {
  505. throw new Exception("No arguments passed to RecallById");
  506. }
  507. }
  508. public function getName()
  509. {
  510. $info = pathinfo($this->getFilePath());
  511. return $info['filename'];
  512. }
  513. /**
  514. * Fetch the Application_Model_StoredFile by looking up its filepath.
  515. *
  516. * @param string $p_filepath path of file stored in Airtime.
  517. * @return Application_Model_StoredFile|NULL
  518. */
  519. public static function RecallByFilepath($p_filepath, $con)
  520. {
  521. $path_info = Application_Model_MusicDir::splitFilePath($p_filepath);
  522. if (is_null($path_info)) {
  523. return null;
  524. }
  525. $music_dir = Application_Model_MusicDir::getDirByPath($path_info[0]);
  526. $file = CcFilesQuery::create()
  527. ->filterByDbDirectory($music_dir->getId())
  528. ->filterByDbFilepath($path_info[1])
  529. ->findOne($con);
  530. return is_null($file) ? null : self::createWithFile($file, $con);
  531. }
  532. public static function RecallByPartialFilepath($partial_path, $con)
  533. {
  534. $path_info = Application_Model_MusicDir::splitFilePath($partial_path);
  535. if (is_null($path_info)) {
  536. return null;
  537. }
  538. $music_dir = Application_Model_MusicDir::getDirByPath($path_info[0]);
  539. $files = CcFilesQuery::create()
  540. ->filterByDbDirectory($music_dir->getId())
  541. ->filterByDbFilepath("$path_info[1]%")
  542. ->find($con);
  543. $res = array();
  544. foreach ($files as $file) {
  545. $storedFile = new Application_Model_StoredFile($file, $con);
  546. $res[] = $storedFile;
  547. }
  548. return $res;
  549. }
  550. public static function getLibraryColumns()
  551. {
  552. return array("id", "track_title", "artist_name", "album_title",
  553. "genre", "length", "year", "utime", "mtime", "ftype",
  554. "track_number", "mood", "bpm", "composer", "info_url",
  555. "bit_rate", "sample_rate", "isrc_number", "encoded_by", "label",
  556. "copyright", "mime", "language", "filepath", "owner_id",
  557. "conductor", "replay_gain", "lptime", "is_playlist", "is_scheduled",
  558. "cuein", "cueout" );
  559. }
  560. public static function searchLibraryFiles($datatables)
  561. {
  562. $baseUrl = Application_Common_OsPath::getBaseDir();
  563. $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
  564. $displayColumns = self::getLibraryColumns();
  565. $plSelect = array();
  566. $blSelect = array();
  567. $fileSelect = array();
  568. $streamSelect = array();
  569. foreach ($displayColumns as $key) {
  570. if ($key === "id") {
  571. $plSelect[] = "PL.id AS ".$key;
  572. $blSelect[] = "BL.id AS ".$key;
  573. $fileSelect[] = "FILES.id AS $key";
  574. $streamSelect[] = "ws.id AS ".$key;
  575. }
  576. elseif ($key === "track_title") {
  577. $plSelect[] = "name AS ".$key;
  578. $blSelect[] = "name AS ".$key;
  579. $fileSelect[] = $key;
  580. $streamSelect[] = "name AS ".$key;
  581. }
  582. elseif ($key === "ftype") {
  583. $plSelect[] = "'playlist'::varchar AS ".$key;
  584. $blSelect[] = "'block'::varchar AS ".$key;
  585. $fileSelect[] = $key;
  586. $streamSelect[] = "'stream'::varchar AS ".$key;
  587. }
  588. elseif ($key === "artist_name") {
  589. $plSelect[] = "login AS ".$key;
  590. $blSelect[] = "login AS ".$key;
  591. $fileSelect[] = $key;
  592. $streamSelect[] = "login AS ".$key;
  593. }
  594. elseif ($key === "owner_id") {
  595. $plSelect[] = "login AS ".$key;
  596. $blSelect[] = "login AS ".$key;
  597. $fileSelect[] = "sub.login AS $key";
  598. $streamSelect[] = "login AS ".$key;
  599. }
  600. elseif ($key === "replay_gain") {
  601. $plSelect[] = "NULL::NUMERIC AS ".$key;
  602. $blSelect[] = "NULL::NUMERIC AS ".$key;
  603. $fileSelect[] = $key;
  604. $streamSelect[] = "NULL::NUMERIC AS ".$key;
  605. }
  606. elseif ($key === "lptime") {
  607. $plSelect[] = "NULL::TIMESTAMP AS ".$key;
  608. $blSelect[] = "NULL::TIMESTAMP AS ".$key;
  609. $fileSelect[] = $key;
  610. $streamSelect[] = $key;
  611. }
  612. elseif ($key === "is_scheduled" || $key === "is_playlist") {
  613. $plSelect[] = "NULL::boolean AS ".$key;
  614. $blSelect[] = "NULL::boolean AS ".$key;
  615. $fileSelect[] = $key;
  616. $streamSelect[] = "NULL::boolean AS ".$key;
  617. }
  618. elseif ($key === "cuein" || $key === "cueout") {
  619. $plSelect[] = "NULL::INTERVAL AS ".$key;
  620. $blSelect[] = "NULL::INTERVAL AS ".$key;
  621. $fileSelect[] = $key;
  622. $streamSelect[] = "NULL::INTERVAL AS ".$key;
  623. }
  624. //file length is displayed based on cueout - cuein.
  625. else if ($key === "length") {
  626. $plSelect[] = $key;
  627. $blSelect[] = $key;
  628. $fileSelect[] = "(cueout - cuein)::INTERVAL AS length";
  629. $streamSelect[] = $key;
  630. }
  631. //same columns in each table.
  632. else if (in_array($key, array("utime", "mtime"))) {
  633. $plSelect[] = $key;
  634. $blSelect[] = $key;
  635. $fileSelect[] = $key;
  636. $streamSelect[] = $key;
  637. }
  638. elseif ($key === "year") {
  639. $plSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
  640. $blSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
  641. $fileSelect[] = "year AS ".$key;
  642. $streamSelect[] = "EXTRACT(YEAR FROM utime)::varchar AS ".$key;
  643. }
  644. //need to cast certain data as ints for the union to search on.
  645. else if (in_array($key, array("track_number", "bit_rate", "sample_rate", "bpm"))) {
  646. $plSelect[] = "NULL::int AS ".$key;
  647. $blSelect[] = "NULL::int AS ".$key;
  648. $fileSelect[] = $key;
  649. $streamSelect[] = "NULL::int AS ".$key;
  650. }
  651. elseif ($key === "filepath") {
  652. $plSelect[] = "NULL::VARCHAR AS ".$key;
  653. $blSelect[] = "NULL::VARCHAR AS ".$key;
  654. $fileSelect[] = $key;
  655. $streamSelect[] = "url AS ".$key;
  656. }
  657. else if ($key == "mime") {
  658. $plSelect[] = "NULL::VARCHAR AS ".$key;
  659. $blSelect[] = "NULL::VARCHAR AS ".$key;
  660. $fileSelect[] = $key;
  661. $streamSelect[] = $key;
  662. }
  663. else {
  664. $plSelect[] = "NULL::text AS ".$key;
  665. $blSelect[] = "NULL::text AS ".$key;
  666. $fileSelect[] = $key;
  667. $streamSelect[] = "NULL::text AS ".$key;
  668. }
  669. }
  670. $plSelect = "SELECT ". join(",", $plSelect);
  671. $blSelect = "SELECT ". join(",", $blSelect);
  672. $fileSelect = "SELECT ". join(",", $fileSelect);
  673. $streamSelect = "SELECT ". join(",", $streamSelect);
  674. $type = intval($datatables["type"]);
  675. $plTable = "({$plSelect} FROM cc_playlist AS PL LEFT JOIN cc_subjs AS sub ON (sub.id = PL.creator_id))";
  676. $blTable = "({$blSelect} FROM cc_block AS BL LEFT JOIN cc_subjs AS sub ON (sub.id = BL.creator_id))";
  677. $fileTable = "({$fileSelect} FROM cc_files AS FILES LEFT JOIN cc_subjs AS sub ON (sub.id = FILES.owner_id) WHERE file_exists = 'TRUE' AND hidden='FALSE')";
  678. //$fileTable = "({$fileSelect} FROM cc_files AS FILES WHERE file_exists = 'TRUE')";
  679. $streamTable = "({$streamSelect} FROM cc_webstream AS ws LEFT JOIN cc_subjs AS sub ON (sub.id = ws.creator_id))";
  680. $unionTable = "({$plTable} UNION {$blTable} UNION {$fileTable} UNION {$streamTable}) AS RESULTS";
  681. //choose which table we need to select data from.
  682. // TODO : use constants instead of numbers -- RG
  683. switch ($type) {
  684. case 0:
  685. $fromTable = $unionTable;
  686. break;
  687. case 1:
  688. $fromTable = $fileTable." AS File"; //need an alias for the table if it's standalone.
  689. break;
  690. case 2:
  691. $fromTable = $plTable." AS Playlist"; //need an alias for the table if it's standalone.
  692. break;
  693. case 3:
  694. $fromTable = $blTable." AS Block"; //need an alias for the table if it's standalone.
  695. break;
  696. case 4:
  697. $fromTable = $streamTable." AS StreamTable"; //need an alias for the table if it's standalone.
  698. break;
  699. default:
  700. $fromTable = $unionTable;
  701. }
  702. // update is_scheduled to false for tracks that
  703. // have already played out
  704. self::updatePastFilesIsScheduled();
  705. $results = Application_Model_Datatables::findEntries($con, $displayColumns, $fromTable, $datatables);
  706. $displayTimezone = new DateTimeZone(Application_Model_Preference::GetUserTimezone());
  707. $utcTimezone = new DateTimeZone("UTC");
  708. foreach ($results['aaData'] as &$row) {
  709. $row['id'] = intval($row['id']);
  710. //taken from Datatables.php, needs to be cleaned up there.
  711. if (isset($r['ftype'])) {
  712. if ($r['ftype'] == 'playlist') {
  713. $pl = new Application_Model_Playlist($r['id']);
  714. $r['length'] = $pl->getLength();
  715. } elseif ($r['ftype'] == "block") {
  716. $bl = new Application_Model_Block($r['id']);
  717. $r['bl_type'] = $bl->isStatic() ? 'static' : 'dynamic';
  718. $r['length'] = $bl->getLength();
  719. }
  720. }
  721. if ($row['ftype'] === "audioclip") {
  722. $cuein_formatter = new LengthFormatter($row["cuein"]);
  723. $row["cuein"] = $cuein_formatter->format();
  724. $cueout_formatter = new LengthFormatter($row["cueout"]);
  725. $row["cueout"] = $cueout_formatter->format();
  726. $cuein = Application_Common_DateHelper::playlistTimeToSeconds($row["cuein"]);
  727. $cueout = Application_Common_DateHelper::playlistTimeToSeconds($row["cueout"]);
  728. $row_length = Application_Common_DateHelper::secondsToPlaylistTime($cueout - $cuein);
  729. $formatter = new SamplerateFormatter($row['sample_rate']);
  730. $row['sample_rate'] = $formatter->format();
  731. $formatter = new BitrateFormatter($row['bit_rate']);
  732. $row['bit_rate'] = $formatter->format();
  733. //soundcloud status
  734. $file = Application_Model_StoredFile::RecallById($row['id']);
  735. $row['soundcloud_id'] = $file->getSoundCloudId();
  736. // for audio preview
  737. $row['audioFile'] = $row['id'].".".pathinfo($row['filepath'], PATHINFO_EXTENSION);
  738. }
  739. else {
  740. $row['audioFile'] = $row['id'];
  741. $row_length = $row['length'];
  742. }
  743. $len_formatter = new LengthFormatter($row_length);
  744. $row['length'] = $len_formatter->format();
  745. //convert mtime and utime to localtime
  746. $row['mtime'] = new DateTime($row['mtime'], $utcTimezone);
  747. $row['mtime']->setTimeZone($displayTimezone);
  748. $row['mtime'] = $row['mtime']->format('Y-m-d H:i:s');
  749. $row['utime'] = new DateTime($row['utime'], $utcTimezone);
  750. $row['utime']->setTimeZone($displayTimezone);
  751. $row['utime'] = $row['utime']->format('Y-m-d H:i:s');
  752. //need to convert last played to localtime if it exists.
  753. if (isset($row['lptime'])) {
  754. $row['lptime'] = new DateTime($row['lptime'], $utcTimezone);
  755. $row['lptime']->setTimeZone($displayTimezone);
  756. $row['lptime'] = $row['lptime']->format('Y-m-d H:i:s');
  757. }
  758. // we need to initalize the checkbox and image row because we do not retrieve
  759. // any data from the db for these and datatables will complain
  760. $row['checkbox'] = "";
  761. $row['image'] = "";
  762. $type = substr($row['ftype'], 0, 2);
  763. $row['tr_id'] = "{$type}_{$row['id']}";
  764. }
  765. return $results;
  766. }
  767. public static function uploadFile($p_targetDir)
  768. {
  769. // HTTP headers for no cache etc
  770. header('Content-type: text/plain; charset=UTF-8');
  771. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  772. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  773. header("Cache-Control: no-store, no-cache, must-revalidate");
  774. header("Cache-Control: post-check=0, pre-check=0", false);
  775. header("Pragma: no-cache");
  776. // Settings
  777. $cleanupTargetDir = false; // Remove old files
  778. $maxFileAge = 60 * 60; // Temp file age in seconds
  779. // 5 minutes execution time
  780. @set_time_limit(5 * 60);
  781. // usleep(5000);
  782. // Get parameters
  783. $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
  784. $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
  785. $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
  786. # TODO : should not log __FILE__ itself. there is general logging for
  787. # this
  788. Logging::info(__FILE__.":uploadFile(): filename=$fileName to $p_targetDir");
  789. // Clean the fileName for security reasons
  790. //this needs fixing for songs not in ascii.
  791. //$fileName = preg_replace('/[^\w\._]+/', '', $fileName);
  792. // Create target dir
  793. if (!file_exists($p_targetDir))
  794. @mkdir($p_targetDir);
  795. // Remove old temp files
  796. if (is_dir($p_targetDir) && ($dir = opendir($p_targetDir))) {
  797. while (($file = readdir($dir)) !== false) {
  798. $filePath = $p_targetDir . DIRECTORY_SEPARATOR . $file;
  799. // Remove temp files if they are older than the max age
  800. if (preg_match('/\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
  801. @unlink($filePath);
  802. }
  803. closedir($dir);
  804. } else
  805. die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": _("Failed to open temp directory.")}, "id" : "id"}');
  806. // Look for the content type header
  807. if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
  808. $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
  809. if (isset($_SERVER["CONTENT_TYPE"]))
  810. $contentType = $_SERVER["CONTENT_TYPE"];
  811. // create temp file name (CC-3086)
  812. // we are not using mktemp command anymore.
  813. // plupload support unique_name feature.
  814. $tempFilePath= $p_targetDir . DIRECTORY_SEPARATOR . $fileName;
  815. // Old IBM code...
  816. if (strpos($contentType, "multipart") !== false) {
  817. if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
  818. // Open temp file
  819. $out = fopen($tempFilePath, $chunk == 0 ? "wb" : "ab");
  820. if ($out) {
  821. // Read binary input stream and append it to temp file
  822. $in = fopen($_FILES['file']['tmp_name'], "rb");
  823. if ($in) {
  824. while (($buff = fread($in, 4096)))
  825. fwrite($out, $buff);
  826. } else
  827. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": _("Failed to open input stream.")}, "id" : "id"}');
  828. fclose($out);
  829. unlink($_FILES['file']['tmp_name']);
  830. } else
  831. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": _("Failed to open output stream.")}, "id" : "id"}');
  832. } else
  833. die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": _("Failed to move uploaded file.")}, "id" : "id"}');
  834. } else {
  835. // Open temp file
  836. $out = fopen($tempFilePath, $chunk == 0 ? "wb" : "ab");
  837. if ($out) {
  838. // Read binary input stream and append it to temp file
  839. $in = fopen("php://input", "rb");
  840. if ($in) {
  841. while (($buff = fread($in, 4096)))
  842. fwrite($out, $buff);
  843. } else
  844. die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": _("Failed to open input stream.")}, "id" : "id"}');
  845. fclose($out);
  846. } else
  847. die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": _("Failed to open output stream.")}, "id" : "id"}');
  848. }
  849. return $tempFilePath;
  850. }
  851. /**
  852. * Check, using disk_free_space, the space available in the $destination_folder folder to see if it has
  853. * enough space to move the $audio_file into and report back to the user if not.
  854. **/
  855. public static function isEnoughDiskSpaceToCopy($destination_folder, $audio_file)
  856. {
  857. //check to see if we have enough space in the /organize directory to copy the file
  858. $freeSpace = disk_free_space($destination_folder);
  859. $fileSize = filesize($audio_file);
  860. return $freeSpace >= $fileSize;
  861. }
  862. public static function copyFileToStor($p_targetDir, $fileName, $tempname)
  863. {
  864. $audio_file = $p_targetDir . DIRECTORY_SEPARATOR . $tempname;
  865. Logging::info('copyFileToStor: moving file '.$audio_file);
  866. $storDir = Application_Model_MusicDir::getStorDir();
  867. $stor = $storDir->getDirectory();
  868. // check if "organize" dir exists and if not create one
  869. if (!file_exists($stor."/organize")) {
  870. if (!mkdir($stor."/organize", 0777)) {
  871. return array(
  872. "code" => 109,
  873. "message" => _("Failed to create 'organize' directory."));
  874. }
  875. }
  876. if (chmod($audio_file, 0644) === false) {
  877. Logging::info("Warning: couldn't change permissions of $audio_file to 0644");
  878. }
  879. // Check if we have enough space before copying
  880. if (!self::isEnoughDiskSpaceToCopy($stor, $audio_file)) {
  881. $freeSpace = disk_free_space($stor);
  882. $fileSize = filesize($audio_file);
  883. return array("code" => 107,
  884. "message" => sprintf(_("The file was not uploaded, there is "
  885. ."%s MB of disk space left and the file you are "
  886. ."uploading has a size of %s MB."), $freeSpace, $fileSize));
  887. }
  888. // Check if liquidsoap can play this file
  889. if (!self::liquidsoapFilePlayabilityTest($audio_file)) {
  890. return array(
  891. "code" => 110,
  892. "message" => _("This file appears to be corrupted and will not "
  893. ."be added to media library."));
  894. }
  895. // Did all the checks for real, now trying to copy
  896. $audio_stor = Application_Common_OsPath::join($stor, "organize",
  897. $fileName);
  898. $user = Application_Model_User::getCurrentUser();
  899. if (is_null($user)) {
  900. $uid = Application_Model_User::getFirstAdminId();
  901. } else {
  902. $uid = $user->getId();
  903. }
  904. $id_file = "$audio_stor.identifier";
  905. if (file_put_contents($id_file, $uid) === false) {
  906. Logging::info("Could not write file to identify user: '$uid'");
  907. Logging::info("Id file path: '$id_file'");
  908. Logging::info("Defaulting to admin (no identification file was
  909. written)");
  910. } else {
  911. Logging::info("Successfully written identification file for
  912. uploaded '$audio_stor'");
  913. }
  914. //if the uploaded file is not UTF-8 encoded, let's encode it. Assuming source
  915. //encoding is ISO-8859-1
  916. $audio_stor = mb_detect_encoding($audio_stor, "UTF-8") == "UTF-8" ? $audio_stor : utf8_encode($audio_stor);
  917. Logging::info("copyFileToStor: moving file $audio_file to $audio_stor");
  918. // Martin K.: changed to rename: Much less load + quicker since this is
  919. // an atomic operation
  920. if (@rename($audio_file, $audio_stor) === false) {
  921. //something went wrong likely there wasn't enough space in .
  922. //the audio_stor to move the file too warn the user that .
  923. //the file wasn't uploaded and they should check if there .
  924. //is enough disk space .
  925. unlink($audio_file); //remove the file after failed rename
  926. unlink($id_file); // Also remove the identifier file
  927. return array(
  928. "code" => 108,
  929. "message" => _("The file was not uploaded, this error can occur if the computer "
  930. ."hard drive does not have enough disk space or the stor "
  931. ."directory does not have correct write permissions."));
  932. }
  933. // Now that we successfully added this file, we will add another tag
  934. // file that will identify the user that owns it
  935. return null;
  936. }
  937. /*
  938. * Pass the file through Liquidsoap and test if it is readable. Return True if readable, and False otherwise.
  939. */
  940. public static function liquidsoapFilePlayabilityTest($audio_file)
  941. {
  942. $LIQUIDSOAP_ERRORS = array('TagLib: MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream.');
  943. // Ask Liquidsoap if file is playable
  944. /* CC-5990/5991 - Changed to point directly to liquidsoap, removed PATH export */
  945. $command = sprintf('liquidsoap -v -c "output.dummy(audio_to_stereo(single(%s)))" 2>&1',
  946. escapeshellarg($audio_file));
  947. exec("export PATH=/usr/local/bin:/usr/bin:/bin/usr/bin/ && $command", $output, $rv);
  948. $isError = count($output) > 0 && in_array($output[0], $LIQUIDSOAP_ERRORS);
  949. Logging::info("Is error?! : " . $isError);
  950. Logging::info("ls playability response: " . $rv);
  951. return ($rv == 0 && !$isError);
  952. }
  953. public static function getFileCount()
  954. {
  955. $sql = "SELECT count(*) as cnt FROM cc_files WHERE file_exists";
  956. return Application_Common_Database::prepareAndExecute($sql, array(),
  957. Application_Common_Database::COLUMN);
  958. }
  959. /**
  960. *
  961. * Enter description here ...
  962. * @param $dir_id - if this is not provided, it returns all files with full
  963. * path constructed.
  964. */
  965. public static function listAllFiles($dir_id=null, $all=true)
  966. {
  967. $con = Propel::getConnection();
  968. $sql = <<<SQL
  969. SELECT filepath AS fp
  970. FROM CC_FILES AS f
  971. WHERE f.directory = :dir_id
  972. SQL;
  973. if (!$all) {
  974. $sql .= " AND f.file_exists = 'TRUE'";
  975. }
  976. $stmt = $con->prepare($sql);
  977. $stmt->bindParam(':dir_id', $dir_id);
  978. if ($stmt->execute()) {
  979. $rows = $stmt->fetchAll();
  980. } else {
  981. $msg = implode(',', $stmt->errorInfo());
  982. throw new Exception("Error: $msg");
  983. }
  984. $results = array();
  985. foreach ($rows as $row) {
  986. $results[] = $row["fp"];
  987. }
  988. return $results;
  989. }
  990. //TODO: MERGE THIS FUNCTION AND "listAllFiles" -MK
  991. public static function listAllFiles2($dir_id=null, $limit="ALL")
  992. {
  993. $con = Propel::getConnection();
  994. $sql = <<<SQL
  995. SELECT id,
  996. filepath AS fp
  997. FROM cc_files
  998. WHERE directory = :dir_id
  999. AND file_exists = 'TRUE'
  1000. AND replay_gain IS NULL LIMIT :lim
  1001. SQL;
  1002. $stmt = $con->prepare($sql);
  1003. $stmt->bindParam(':dir_id', $dir_id);
  1004. $stmt->bindParam(':lim', $limit);
  1005. if ($stmt->execute()) {
  1006. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1007. } else {
  1008. $msg = implode(',', $stmt->errorInfo());
  1009. throw new Exception("Error: $msg");
  1010. }
  1011. return $rows;
  1012. }
  1013. public static function getAllFilesWithoutSilan() {
  1014. $con = Propel::getConnection();
  1015. $sql = <<<SQL
  1016. SELECT f.id,
  1017. m.directory || f.filepath AS fp
  1018. FROM cc_files as f
  1019. JOIN cc_music_dirs as m ON f.directory = m.id
  1020. WHERE file_exists = 'TRUE'
  1021. AND silan_check IS FALSE Limit 100
  1022. SQL;
  1023. $stmt = $con->prepare($sql);
  1024. if ($stmt->execute()) {
  1025. $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  1026. } else {
  1027. $msg = implode(',', $stmt->errorInfo());
  1028. throw new Exception("Error: $msg");
  1029. }
  1030. return $rows;
  1031. }
  1032. /* Gets number of tracks uploaded to
  1033. * Soundcloud in the last 24 hours
  1034. */
  1035. public static function getSoundCloudUploads()
  1036. {
  1037. try {
  1038. $sql = <<<SQL
  1039. SELECT soundcloud_id AS id,
  1040. soundcloud_upload_time
  1041. FROM CC_FILES
  1042. WHERE (id != -2
  1043. AND id != -3)
  1044. AND (soundcloud_upload_time >= (now() - (INTERVAL '1 day')))
  1045. SQL;
  1046. $rows = Application_Common_Database::prepareAndExecute($sql);
  1047. return count($rows);
  1048. } catch (Exception $e) {
  1049. header('HTTP/1.0 503 Service Unavailable');
  1050. Logging::info("Could not connect to database.");
  1051. exit;
  1052. }
  1053. }
  1054. public function setSoundCloudLinkToFile($link_to_file)
  1055. {
  1056. $this->_file->setDbSoundCloudLinkToFile($link_to_file)
  1057. ->save();
  1058. }
  1059. public function getSoundCloudLinkToFile()
  1060. {
  1061. return $this->_file->getDbSoundCloudLinkToFile();
  1062. }
  1063. public function setSoundCloudFileId($p_soundcloud_id)
  1064. {
  1065. $this->_file->setDbSoundCloudId($p_soundcloud_id)
  1066. ->save();
  1067. }
  1068. public function getSoundCloudId()
  1069. {
  1070. return $this->_file->getDbSoundCloudId();
  1071. }
  1072. public function setSoundCloudErrorCode($code)
  1073. {
  1074. $this->_file->setDbSoundCloudErrorCode($code)
  1075. ->save();
  1076. }
  1077. public function getSoundCloudErrorCode()
  1078. {
  1079. return $this->_file->getDbSoundCloudErrorCode();
  1080. }
  1081. public function setSoundCloudErrorMsg($msg)
  1082. {
  1083. $this->_file->setDbSoundCloudErrorMsg($msg)
  1084. ->save();
  1085. }
  1086. public function getSoundCloudErrorMsg()
  1087. {
  1088. return $this->_file->getDbSoundCloudErrorMsg();
  1089. }
  1090. public function getDirectory()
  1091. {
  1092. return $this->_file->getDbDirectory();
  1093. }
  1094. public function setFileExistsFlag($flag)
  1095. {
  1096. $this->_file->setDbFileExists($flag)
  1097. ->save();
  1098. }
  1099. public function setFileHiddenFlag($flag)
  1100. {
  1101. $this->_file->setDbHidden($flag)
  1102. ->save();
  1103. }
  1104. public function setSoundCloudUploadTime($time)
  1105. {
  1106. $this->_file->setDbSoundCloundUploadTime($time)
  1107. ->save();
  1108. }
  1109. // This method seems to be unsued everywhere so I've commented it out
  1110. // If it's absence does not have any effect then it will be completely
  1111. // removed soon
  1112. //public function getFileExistsFlag()
  1113. //{
  1114. //return $this->_file->getDbFileExists();
  1115. //}
  1116. public function getFileOwnerId()
  1117. {
  1118. return $this->_file->getDbOwnerId();
  1119. }
  1120. // note: never call this method from controllers because it does a sleep
  1121. public function uploadToSoundCloud()
  1122. {
  1123. $CC_CONFIG = Config::getConfig();
  1124. $file = $this->_file;
  1125. if (is_null($file)) {
  1126. return "File does not exist";
  1127. }
  1128. if (Application_Model_Preference::GetUploadToSoundcloudOption()) {
  1129. for ($i=0; $i<$CC_CONFIG['soundcloud-connection-retries']; $i++) {
  1130. $description = $file->getDbTrackTitle();
  1131. $tag = array();
  1132. $genre = $file->getDbGenre();
  1133. $release = $file->getDbUtime();
  1134. try {
  1135. $soundcloud = new Application_Model_Soundcloud();
  1136. $soundcloud_res = $soundcloud->uploadTrack(
  1137. $this->getFilePath(), $this->getName(), $description,
  1138. $tag, $release, $genre);
  1139. $this->setSoundCloudFileId($soundcloud_res['id']);
  1140. $this->setSoundCloudLinkToFile($soundcloud_res['permalink_url']);
  1141. $this->setSoundCloudUploadTime(new DateTime("now"), new DateTimeZone("UTC"));
  1142. break;
  1143. } catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
  1144. $code = $e->getHttpCode();
  1145. $msg = $e->getHttpBody();
  1146. // TODO : Do not parse JSON by hand
  1147. $temp = explode('"error":',$msg);
  1148. $msg = trim($temp[1], '"}');
  1149. $this->setSoundCloudErrorCode($code);
  1150. $this->setSoundCloudErrorMsg($msg);
  1151. // setting sc id to -3 which indicates error
  1152. $this->setSoundCloudFileId(SOUNDCLOUD_ERROR);
  1153. if (!in_array($code, array(0, 100))) {
  1154. break;
  1155. }
  1156. }
  1157. sleep($CC_CONFIG['soundcloud-connection-wait']);
  1158. }
  1159. }
  1160. }
  1161. public static function setIsPlaylist($p_playlistItems, $p_type, $p_status) {
  1162. foreach ($p_playlistItems as $item) {
  1163. $file = self::RecallById($item->getDbFileId());
  1164. $fileId = $file->_file->getDbId();
  1165. if ($p_type == 'playlist') {
  1166. // we have to check if the file is in another playlist before
  1167. // we can update
  1168. if (!is_null($fileId) && !in_array($fileId, Application_Model_Playlist::getAllPlaylistFiles())) {
  1169. $file->_file->setDbIsPlaylist($p_status)->save();
  1170. }
  1171. } elseif ($p_type == 'block') {
  1172. if (!is_null($fileId) && !in_array($fileId, Application_Model_Block::getAllBlockFiles())) {
  1173. $file->_file->setDbIsPlaylist($p_status)->save();
  1174. }
  1175. }
  1176. }
  1177. }
  1178. public static function setIsScheduled($fileId, $status) {
  1179. $file = self::RecallById($fileId);
  1180. $updateIsScheduled = false;
  1181. if (!is_null($fileId) && !in_array($fileId,
  1182. Application_Model_Schedule::getAllFutureScheduledFiles())) {
  1183. $file->_file->setDbIsScheduled($status)->save();
  1184. $updateIsScheduled = true;
  1185. }
  1186. return $updateIsScheduled;
  1187. }
  1188. /**
  1189. *
  1190. * Updates the is_scheduled flag to false for tracks that are no longer
  1191. * scheduled in the future. We do this by checking the difference between
  1192. * all files scheduled in the future and all files with is_scheduled = true.
  1193. * The difference of the two result sets is what we need to update.
  1194. */
  1195. public static function updatePastFilesIsScheduled()
  1196. {
  1197. $futureScheduledFilesSelectCriteria = new Criteria();
  1198. $futureScheduledFilesSelectCriteria->addSelectColumn(CcSchedulePeer::FILE_ID);
  1199. $futureScheduledFilesSelectCriteria->setDistinct();
  1200. $futureScheduledFilesSelectCriteria->add(CcSchedulePeer::ENDS, gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN);
  1201. $stmt = CcSchedulePeer::doSelectStmt($futureScheduledFilesSelectCriteria);
  1202. $filesScheduledInFuture = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
  1203. $filesCurrentlySetWithIsScheduledSelectCriteria = new Criteria();
  1204. $filesCurrentlySetWithIsScheduledSelectCriteria->addSelectColumn(CcFilesPeer::ID);
  1205. $filesCurrentlySetWithIsScheduledSelectCriteria->add(CcFilesPeer::IS_SCHEDULED, true);
  1206. $stmt = CcFilesPeer::doSelectStmt($filesCurrentlySetWithIsScheduledSelectCriteria);
  1207. $filesCurrentlySetWithIsScheduled = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
  1208. $diff = array_diff($filesCurrentlySetWithIsScheduled, $filesScheduledInFuture);
  1209. $con = Propel::getConnection(CcFilesPeer::DATABASE_NAME);
  1210. $selectCriteria = new Criteria();
  1211. $selectCriteria->add(CcFilesPeer::ID, $diff, Criteria::IN);
  1212. $updateCriteria = new Criteria();
  1213. $updateCriteria->add(CcFilesPeer::IS_SCHEDULED, false);
  1214. BasePeer::doUpdate($selectCriteria, $updateCriteria, $con);
  1215. }
  1216. }
  1217. class DeleteScheduledFileException extends Exception {}
  1218. class FileDoesNotExistException extends Exception {}
  1219. class FileNoPermissionException extends Exception {}