domingo, 23 de febrero de 2025

TDLib & Process synchronization

Telegram works based on asynchronous RPC calls, so interacting with the API implies sending the payload that represents the call to the function and receiving a result. This mode of operation avoids blockages, but implies the need to correctly manage communication between processes.

 To implement a correct operation on my Bachelor's Degree Final Project,it was necessary to divide the API call management logic into two different actions. On the one hand, the result of the call is handled in class Telegram.java, and on the other hand, a spinlock is used to synchronize communication between processes.


HANDLE THE ANSWER:

To handle client-server interactions, the Telegram.java class adds a DefaultHandler object to each API call. The onResult(TdApi.Object object) method then receives the response when it is available.

The original functionality of the onResult() method was limited to printing the result of the call, a TL (Type Language) object such as the following, through the standard output of the system.




This functionality did not meet the requirements of the project since it was desired to natively retrieve the types of objects handled by Telegram: FoundMessages, Chats, User, etc.

To obtain the desired functionality, a feature of the TDLib design was taken advantage of.  Each type of object has a unique identifier defined in its constructor. For example, in the following figure it can be seen that the identifier -448050478 corresponds to an object type 'photo message'





The implemented solution modifies the onResult() method by adding a switch-case structure where the value of the constructor of the received object is used as a parameter in the switch and then the response is handled according to the corresponding needs. Here's an example.



After the response is captured and the received object is handled successfully, the value of the control variable is set to true to inform the calling method that it can end the spinlock. If there is a problem with the call, the default case is executed and the active wait is terminated.

Once the spinlock is finished, the corresponding object is retrieved and the lock variable is rearmed for the next request. If the result of the call is not as expected, the situation is handled appropriately.





Enjoy, 

Culex



lunes, 19 de agosto de 2024

A piece of humour


I can't help it :)

 


CISO vs Hacker

Enjoy 

 Culex

sábado, 27 de julio de 2024

Proyecto Fin de Grado, consejos y recomendaciones - UNED, TFG, PGF

Bueno este año he tenido el blog totalmente abandonado pero tengo una buena excusa. He estado dedicado todo el año a mi PFG, defendí en Julio y ya por fin he terminado el grado :).

A titulo personal, la experiencia ha sido muy enriquecedora y he disfrutado todo el proceso: desde las primeras etapas donde me estaba documentando y andaba más perdido que un pulpo en un garaje hasta la creación de la memoria que se me atragantó un poco la verdad.

Esta es la razón de este post, dar algunas indicaciones sobre los capítulos más 'abstractos' y alguna recomendación general.

Primero y más importante, si te es posible no dejes la escritura de la memoria para el final. No es que tengas que ir escribiendo la versión final a la vez que desarrollas el proyecto pero ir añadiendo notas en los capítulos te va a ayudar mucho a la hora de ponerse a escribir de verdad.

Segundo, una lista de buenas practicas:

  • Hay que explicar las cosas. No podemos poner un gráfico o un diagrama y no explicarlo.
  • Guiar al lector con indicaciones del tipo, "como se indica en la tabla 2", "ver figura 12", etc.
  • Usar referencias o pie de pagina para añadir url con información.
  • No usar copy-paste para añadir imágenes o tablas. Luego la resolución no es muy buena, mejor insertarlas.


Y por ultimo, algunas indicaciones sobre como abordar algunos capítulos:

  • Resumen: Un buen resumen es casi una síntesis absoluta de lo que has hecho (conviene reescribirlo al final) presentar tema, objetivos y resultados. También describir  que aporta el proyecto respecto a otros trabajos.
  • Capítulo 1. Introducción, objetivos y estructura: La introducción debe situar al lector en el dominio del trabajo, destacando la importancia del problema que se va a resolver, si se está ya resolviendo de alguna manera y porqué tiene sentido realizar el trabajo.  Los objetivos son a futuro, no podemos hablar como si el proyecto estuviese terminado. Se debe especificar el objetivo general del trabajo y luego dividir ese objetivo en distintos subobjetivos más específicos y las tareas en que se descomponen.
  •  Capítulo 2. Estado del arte: Es un estudio previo al proyecto para documentarse y con el objetivo de convertirse en un experto en el dominio del trabajo. El estado del arte debe exponer cómo se está abordando el problema del PFG en la actualidad, qué otras herramientas podemos encontrar que permitan realizar funciones similares a las que aborda el PFG, es decir, cómo se ha solucionado el problema hasta el momento. Este análisis nos debe llevar a motivar la realización del trabajo para solventar o superar esas limitaciones o problemas identificados. Estaría bien citar y analizar de manera resumida algunos de los ejemplos siempre destacando sus ventajas e inconvenientes o limitaciones respecto al objetivo del PFG. En la conclusión debe quedar claro la motivación de hacer el PFG porque no hay nada que haga justo lo que queremos, o si lo hay tiene una serie de limitaciones o desventajas frente al desarrollo de la herramienta que se aborda en el PFG. Explicar pros y cons de las soluciones actuales y que aporta nuestro proyecto respecto de las soluciones existentes
  • Capítulo 3. Estudio de viabilidad: en el detalle del presupuesto hay que justificar los datos explicando cómo se han obtenido y citando las fuentes. Al presupuesto se tendrían que añadir los costes indirectos asociados al uso de instalaciones, el margen de beneficio, cuotas a la seguridad social y los impuestos correspondientes. 
  • Capítulos 4,5,6: No llenar la memoria de diagramas sin explicar. Es más útil elegir la secuencia principal de funcionamiento, poner los diagramas que la explican y explicar el diagrama aunque sea brevemente.
  • Capítulo 7. Conclusiones y trabajo futuro: En este capítulo se exponen las conclusiones alcanzadas una vez finalizado el proyecto y valorados los resultados obtenidos respecto de los objetivos definidos en el capítulo 1. También, se proponen líneas de trabajo futuras. En las conclusiones, recordar los objetivos y explicar los resultados obtenidos y la valía del trabajo


Respecto a la defensa solo decir que puede que haya sido la parte más sencilla de todo el proceso. Eso si, es importante para subir nota y no se debe de descuidar.

Por favor, lo anterior son solo algunas ideas que me habría gustado leer antes de empezar a escribir mi memoria y que pienso que pueden ser de interés pero son solo eso, ideas, no se pueden tomar como si fuesen la biblia.

Enjoy!

Culex.


jueves, 28 de diciembre de 2023

un poco de humor

 


Enjoy!

Culex

martes, 26 de diciembre de 2023

TDLib & Java example on Windows 10

Although the instructions provide on github are quite completed there were some issues I had to solve myself for doing the example works, so I share here my experience.

Getting the system ready:

  • Download and install Microsoft Visual Studio. Enable C++ support while installing.
  • Download and install CMake; choose "Add CMake to the system PATH" option while installing.
  • Download and install Git.
  • Download and unpack PHP. Add the path to php.exe to the PATH environment variable
  • Download and install JDK.
  • Close and re-open PowerShell if the PATH environment variable was changed

 Building TDLIB Binaries 

  • Run these commands in PowerShell to build TDLib and to install it to td/tdlib:

 Building JNI & Java example

  • Run these commands in PowerShell  but taking into account next remarks

I had to install  gperf manually and  add the path to gperf.exe to the PATH environment variable.

The first cmake  -DCMAKE_BUILD has to be modified as follows (taking into account you path to TDLib sources is D:\TDLib\td)

cmake -A x64 -DCMAKE_BUILD_TYPE=Release -DTD_ENABLE_JNI=ON -DCMAKE_INSTALL_PREFIX:PATH=../example/java/td .. -DCMAKE_TOOLCHAIN_FILE=D:/TDLib/td/vcpkg/scripts/buildsystems/vcpkg.cmake

The second  cmake  -DCMAKE_BUILD has to be modified as follows,   

cmake -DCMAKE_BUILD_TYPE=Release -DTd_DIR=D:/TDLib/td/example/java/td/lib/cmake/Td -DCMAKE_INSTALL_PREFIX:PATH=.. ..

Before this last command, I get an error when I run ‘mkdir build’ because the directory already exists but it seems not to be a problem since everything works fine

 


 

Enjoy, 

Culex