SyncCompleteController.php 9.8 KB

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