SyncController.php 11 KB

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