SyncCompleteController.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. namespace app\commands;
  3. use app\models\Descarga;
  4. use yii\console\Controller;
  5. use yii\console\ExitCode;
  6. use yii\db\Expression;
  7. use yii\db\Query;
  8. use yii\helpers\ArrayHelper;
  9. class SyncCompleteController extends Controller {
  10. public $ciudad = null;
  11. public $estacion = null;
  12. public $fi = null;
  13. public $ff = null;
  14. public function options($actionId) {
  15. return [
  16. 'ciudad',
  17. 'estacion',
  18. 'fi',
  19. 'ff'
  20. ];
  21. }
  22. public function actionIndex() {
  23. $estados = [
  24. 'AGUASCALIENTES' => 'AGU',
  25. 'BAJA CALIFORNIA' => 'BCN',
  26. 'BAJA CALIFORNIA SUR' => 'BCS',
  27. 'CAMPECHE' => 'CAM',
  28. 'CHIAPAS' => 'CHP',
  29. 'CHIHUAHUA' => 'CHH',
  30. 'CIUDAD DE MÉXICO' => 'CMX',
  31. 'COAHUILA' => 'COA',
  32. 'COLIMA' => 'COL',
  33. 'DURANGO' => 'DUR',
  34. 'GUANAJUATO' => 'GUA',
  35. 'GUERRERO' => 'GRO',
  36. 'HIDALGO' => 'HID',
  37. 'JALISCO' => 'JAL',
  38. 'MEXICO' => 'MEX',
  39. 'MICHOACAN' => 'MIC',
  40. 'MORELOS' => 'MOR',
  41. 'NAYARIT' => 'NAY',
  42. 'NUEVO LEON' => 'NLE',
  43. 'OAXACA' => 'OAX',
  44. 'PUEBLA' => 'PUE',
  45. 'QUERETARO' => 'QUE',
  46. 'QUINTANA ROO' => 'ROO',
  47. 'SAN LUIS POTOSI' => 'SLP',
  48. 'SINALOA' => 'SIN',
  49. 'SONORA' => 'SON',
  50. 'TABASCO' => 'TAB',
  51. 'TAMAULIPAS' => 'TAM',
  52. 'TLAXCALA' => 'TLA',
  53. 'VERACRUZ' => 'VER',
  54. 'YUCATAN' => 'YUC',
  55. 'ZACATECAS' => 'ZAC'
  56. ];
  57. $order = SORT_ASC;
  58. $ciudadEstacion = (new Query())
  59. ->select(["idCiudad", "idEstacion"])
  60. ->from("box")
  61. ->innerJoin("CiudadEstacion", "box.id = {{CiudadEstacion}}.[[idCiudad]]")
  62. ->andWhere([
  63. "box.activo" => true
  64. ])
  65. ->andWhere("[[idGrupo]] is not null")
  66. ->all();
  67. $idCiudades = ArrayHelper::getColumn($ciudadEstacion, "idCiudad");
  68. $ciudades = (new Query())
  69. ->select(["id", "nombre", "idEstado", "timezone", "tipo"])
  70. ->from("box")
  71. ->where(["id" => $idCiudades])
  72. ->indexBy("id")
  73. ->all();
  74. $idEstaciones = ArrayHelper::getColumn($ciudadEstacion, "idEstacion");
  75. $estaciones = (new Query())
  76. ->select(["id", "clave", "siglas", "frecuencia", "descripcion"])
  77. ->from("Estacion")
  78. ->andWhere(["id" => $idEstaciones])
  79. ->indexBy("clave")
  80. ->all();
  81. $fechaInicio = '2021-12-15 00:00:00';
  82. $fechaFin = '2021-12-16 00:00:00';
  83. $this->stdout("{$fechaInicio} - {$fechaFin}\n");
  84. while(true) {
  85. $inicio = time();
  86. $archivos = (new Query())
  87. ->select("hash, box, station, filename, [[timestamp]] at time zone box.timezone as timestamp")
  88. ->from("file")
  89. ->innerJoin("box", "box.id = file.box")
  90. ->andWhere([">=", "[[timestamp]] at time zone box.timezone", $fechaInicio])
  91. // ->andWhere([">=", "[[timestamp]] at time zone box.timezone", new Expression("now() - interval '6 day'")])
  92. ->andWhere(["<", "[[timestamp]] at time zone box.timezone", $fechaFin])
  93. ->orderBy(["timestamp" => $order]);
  94. // $this->stdout("{$archivos->createCommand()->getRawSql()}\n");
  95. $count = 0;
  96. foreach($archivos->each() as $archivo) {
  97. if(!isset($ciudades[$archivo["box"]])) {
  98. continue;
  99. }
  100. $modelo = new Descarga();
  101. $modelo->hash = $archivo["hash"];
  102. $modelo->estacion = $archivo["station"];
  103. $modelo->archivo = $archivo["filename"];
  104. $modelo->ciudad = $archivo["box"];
  105. $modelo->pc = null;
  106. $modelo->fecha = $archivo["timestamp"];
  107. $modelo->descargado = false;
  108. $modelo->nombre = basename($archivo["filename"]);
  109. $ciudad = $ciudades[$archivo["box"]];
  110. $estacion = $estaciones[$archivo["station"]];
  111. $fecha = \DateTime::createFromFormat("Y-m-d H:i:s", $archivo["timestamp"]);
  112. $siglas = explode("-", $estacion["siglas"]);
  113. $tipo = "";
  114. $senal = $siglas[0];
  115. if(isset($siglas[1])) {
  116. $tipo = $siglas[1];
  117. }
  118. if($tipo === "") {
  119. if($ciudad["tipo"] === "tv") {
  120. $tipo = "TDT";
  121. } elseif ($ciudad["tipo"] === "radio") {
  122. $tipo = "FM";
  123. } else {
  124. $tipo = "AM";
  125. }
  126. }
  127. $nombreCiudad = $ciudad["idEstado"];
  128. if($tipo === "AM") {
  129. $desc = explode(",", $estacion["descripcion"]);
  130. $nombreCiudad = $estacion["descripcion"];
  131. if(isset($desc[1])) {
  132. $nombreCiudad = $desc[1];
  133. }
  134. }
  135. if(isset($estados[$nombreCiudad])) {
  136. $nombreCiudad = $estados[$nombreCiudad];
  137. }
  138. $nombreCiudad = str_replace(" ", "_", trim($nombreCiudad));
  139. $y = $fecha->format("Y");
  140. $m = $fecha->format("m");
  141. $d = $fecha->format("d");
  142. $modelo->ruta = "{$y}/{$tipo}/{$nombreCiudad}/{$senal}/{$m}/{$d}";
  143. try {
  144. if(!$modelo->save()) {
  145. $errores = json_encode($modelo->getFirstErrors());
  146. $this->stdout("Error al guardar {$modelo->hash} {$errores}\n");
  147. }
  148. $this->stdout("{$modelo->hash} {$modelo->archivo}\n");
  149. } catch(\Exception $e) {
  150. $this->stdout("{$modelo->hash} {$modelo->archivo} ya existe\n");
  151. }
  152. $count++;
  153. }
  154. $vuelta = time() - $inicio;
  155. $this->stdout("Vuelta: {$vuelta}\n");
  156. }
  157. return ExitCode::OK;
  158. }
  159. public function actionPorFecha() {
  160. if(!$this->fi || !$this->ff) {
  161. $this->stdout("Fecha inicial y final requeridas\n");
  162. return ExitCode::OK;
  163. }
  164. $estados = [
  165. 'AGUASCALIENTES' => 'AGU',
  166. 'BAJA CALIFORNIA' => 'BCN',
  167. 'BAJA CALIFORNIA SUR' => 'BCS',
  168. 'CAMPECHE' => 'CAM',
  169. 'CHIAPAS' => 'CHP',
  170. 'CHIHUAHUA' => 'CHH',
  171. 'CIUDAD DE MÉXICO' => 'CMX',
  172. 'COAHUILA' => 'COA',
  173. 'COLIMA' => 'COL',
  174. 'DURANGO' => 'DUR',
  175. 'GUANAJUATO' => 'GUA',
  176. 'GUERRERO' => 'GRO',
  177. 'HIDALGO' => 'HID',
  178. 'JALISCO' => 'JAL',
  179. 'MEXICO' => 'MEX',
  180. 'MICHOACAN' => 'MIC',
  181. 'MORELOS' => 'MOR',
  182. 'NAYARIT' => 'NAY',
  183. 'NUEVO LEON' => 'NLE',
  184. 'OAXACA' => 'OAX',
  185. 'PUEBLA' => 'PUE',
  186. 'QUERETARO' => 'QUE',
  187. 'QUINTANA ROO' => 'ROO',
  188. 'SAN LUIS POTOSI' => 'SLP',
  189. 'SINALOA' => 'SIN',
  190. 'SONORA' => 'SON',
  191. 'TABASCO' => 'TAB',
  192. 'TAMAULIPAS' => 'TAM',
  193. 'TLAXCALA' => 'TLA',
  194. 'VERACRUZ' => 'VER',
  195. 'YUCATAN' => 'YUC',
  196. 'ZACATECAS' => 'ZAC'
  197. ];
  198. $order = SORT_ASC;
  199. $ciudadEstacion = (new Query())
  200. ->select(["idCiudad", "idEstacion"])
  201. ->from("box")
  202. ->innerJoin("CiudadEstacion", "box.id = {{CiudadEstacion}}.[[idCiudad]]")
  203. ->andWhere([
  204. "box.activo" => true
  205. ])
  206. ->andWhere("[[idGrupo]] is not null")
  207. ->all();
  208. $idCiudades = ArrayHelper::getColumn($ciudadEstacion, "idCiudad");
  209. $ciudades = (new Query())
  210. ->select(["id", "nombre", "idEstado", "timezone", "tipo"])
  211. ->from("box")
  212. ->where(["id" => $idCiudades])
  213. ->indexBy("id")
  214. ->all();
  215. $idEstaciones = ArrayHelper::getColumn($ciudadEstacion, "idEstacion");
  216. $estaciones = (new Query())
  217. ->select(["id", "clave", "siglas", "frecuencia", "descripcion"])
  218. ->from("Estacion")
  219. ->andWhere(["id" => $idEstaciones])
  220. ->indexBy("clave")
  221. ->all();
  222. $inicio = time();
  223. $archivos = (new Query())
  224. ->select("hash, box, station, filename, [[timestamp]] at time zone box.timezone as timestamp")
  225. ->from("file")
  226. ->innerJoin("box", "box.id = file.box")
  227. ->andWhere([">=", "[[timestamp]] at time zone box.timezone", "{$this->fi} 00:00:00"])
  228. // ->andWhere([">=", "[[timestamp]] at time zone box.timezone", new Expression("now() - interval '6 day'")])
  229. ->andWhere(["<=", "[[timestamp]] at time zone box.timezone", "{$this->ff} 00:00:00"])
  230. ->orderBy(["timestamp" => $order]);
  231. $this->stdout("{$archivos->createCommand()->getRawSql()}\n");
  232. $count = 0;
  233. foreach($archivos->each() as $archivo) {
  234. if(!isset($ciudades[$archivo["box"]]) || !isset($estaciones[$archivo["station"]])) {
  235. continue;
  236. }
  237. $modelo = new Descarga();
  238. $modelo->hash = $archivo["hash"];
  239. $modelo->estacion = $archivo["station"];
  240. $modelo->archivo = $archivo["filename"];
  241. $modelo->ciudad = $archivo["box"];
  242. $modelo->pc = null;
  243. $modelo->fecha = $archivo["timestamp"];
  244. $modelo->descargado = false;
  245. $modelo->nombre = basename($archivo["filename"]);
  246. $ciudad = $ciudades[$archivo["box"]];
  247. $estacion = $estaciones[$archivo["station"]];
  248. $fecha = \DateTime::createFromFormat("Y-m-d H:i:s", $archivo["timestamp"]);
  249. $siglas = explode("-", $estacion["siglas"]);
  250. $tipo = "";
  251. $senal = $siglas[0];
  252. if(isset($siglas[1])) {
  253. $tipo = $siglas[1];
  254. }
  255. if($tipo === "") {
  256. if($ciudad["tipo"] === "tv") {
  257. $tipo = "TDT";
  258. } elseif ($ciudad["tipo"] === "radio") {
  259. $tipo = "FM";
  260. } else {
  261. $tipo = "AM";
  262. }
  263. }
  264. $nombreCiudad = $ciudad["idEstado"];
  265. if($tipo === "AM") {
  266. $desc = explode(",", $estacion["descripcion"]);
  267. $nombreCiudad = $estacion["descripcion"];
  268. if(isset($desc[1])) {
  269. $nombreCiudad = $desc[1];
  270. }
  271. }
  272. if(isset($estados[$nombreCiudad])) {
  273. $nombreCiudad = $estados[$nombreCiudad];
  274. }
  275. $nombreCiudad = str_replace(" ", "_", trim($nombreCiudad));
  276. $y = $fecha->format("Y");
  277. $m = $fecha->format("m");
  278. $d = $fecha->format("d");
  279. $modelo->ruta = "{$y}/{$tipo}/{$nombreCiudad}/{$senal}/{$m}/{$d}";
  280. try {
  281. if(!$modelo->save()) {
  282. $errores = json_encode($modelo->getFirstErrors());
  283. $this->stdout("Error al guardar {$modelo->hash} {$errores}\n");
  284. }
  285. $this->stdout("{$modelo->hash} {$modelo->archivo}\n");
  286. } catch(\Exception $e) {
  287. $this->stdout("{$modelo->hash} {$modelo->archivo} ya existe\n");
  288. }
  289. $count++;
  290. }
  291. $vuelta = time() - $inicio;
  292. $this->stdout("Vuelta: {$vuelta}\n");
  293. return ExitCode::OK;
  294. }
  295. }